// SPDX-FileCopyrightText: Copyright (c) 2011, Duane Merrill. All rights reserved.
// SPDX-FileCopyrightText: Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved.
// SPDX-License-Identifier: BSD-3

/**
 * @file
 * @brief cub::DeviceReduceByKey provides device-wide, parallel operations for
 *        reducing segments of values residing within device-accessible memory.
 */

#pragma once

#include <cub/config.cuh>

#if defined(_CCCL_IMPLICIT_SYSTEM_HEADER_GCC)
#  pragma GCC system_header
#elif defined(_CCCL_IMPLICIT_SYSTEM_HEADER_CLANG)
#  pragma clang system_header
#elif defined(_CCCL_IMPLICIT_SYSTEM_HEADER_MSVC)
#  pragma system_header
#endif // no system header

#include <cub/agent/agent_reduce_by_key.cuh>
#include <cub/detail/cc_dispatch.cuh>
#include <cub/device/dispatch/dispatch_common.cuh>
#include <cub/device/dispatch/dispatch_scan.cuh>
#include <cub/device/dispatch/tuning/tuning_reduce_by_key.cuh>
#include <cub/thread/thread_operators.cuh>
#include <cub/util_arch.cuh>
#include <cub/util_device.cuh>
#include <cub/util_math.cuh>
#include <cub/util_vsmem.cuh>

#include <thrust/system/cuda/detail/core/triple_chevron_launch.h>

#include <cuda/std/__host_stdlib/sstream>

CUB_NAMESPACE_BEGIN

/******************************************************************************
 * Kernel entry points
 *****************************************************************************/

namespace detail::reduce_by_key
{
template <typename PrecedingKeyItT, typename AccumT, typename GlobalOffsetT>
struct streaming_context
{
  bool first_partition;
  bool last_partition;
  PrecedingKeyItT preceding_key_it;

  // We use a double-buffer to track the aggregate of the last run of the previous partition
  AccumT* preceding_prefix;
  AccumT* prefix_out;

  // We use a double-buffer to track the number of runs of previous partition
  GlobalOffsetT* d_num_previous_uniques_in;
  GlobalOffsetT* d_num_accumulated_uniques_out;

  _CCCL_DEVICE _CCCL_FORCEINLINE GlobalOffsetT num_accumulated_uniques_out() const
  {
    return first_partition ? GlobalOffsetT{0} : *d_num_previous_uniques_in;
  };

  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE bool is_first_partition() const
  {
    return first_partition;
  }
  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE bool is_last_partition() const
  {
    return last_partition;
  }

  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE auto predecessor_key() const
  {
    return *preceding_key_it;
  }

  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE AccumT prefix() const
  {
    return *preceding_prefix;
  }

  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE void write_prefix(AccumT prefix) const
  {
    *prefix_out = prefix;
  }

  _CCCL_HOST_DEVICE _CCCL_FORCEINLINE GlobalOffsetT* previous_uniques_ptr() const
  {
    return d_num_previous_uniques_in;
  }

  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE GlobalOffsetT num_uniques() const
  {
    return num_accumulated_uniques_out();
  }

  template <typename NumUniquesT>
  _CCCL_FORCEINLINE _CCCL_HOST_DEVICE GlobalOffsetT add_num_uniques(NumUniquesT num_uniques) const
  {
    GlobalOffsetT total_uniques = num_accumulated_uniques_out() + static_cast<GlobalOffsetT>(num_uniques);

    // Otherwise, just write out the number of unique items in this partition
    *d_num_accumulated_uniques_out = total_uniques;

    return total_uniques;
  }
};

/**
 * @brief Multi-block reduce-by-key sweep kernel entry point
 *
 * @tparam PolicySelector
 *   Selects the tuning policy
 *
 * @tparam KeysInputIteratorT
 *   Random-access input iterator type for keys
 *
 * @tparam UniqueOutputIteratorT
 *   Random-access output iterator type for keys
 *
 * @tparam ValuesInputIteratorT
 *   Random-access input iterator type for values
 *
 * @tparam AggregatesOutputIteratorT
 *   Random-access output iterator type for values
 *
 * @tparam NumRunsOutputIteratorT
 *   Output iterator type for recording number of segments encountered
 *
 * @tparam ScanTileStateT
 *   Tile status interface type
 *
 * @tparam EqualityOpT
 *   KeyT equality operator type
 *
 * @tparam ReductionOpT
 *   ValueT reduction operator type
 *
 * @tparam OffsetT
 *   Signed integer type for global offsets
 *
 * @param d_keys_in
 *   Pointer to the input sequence of keys
 *
 * @param d_unique_out
 *   Pointer to the output sequence of unique keys (one key per run)
 *
 * @param d_values_in
 *   Pointer to the input sequence of corresponding values
 *
 * @param d_aggregates_out
 *   Pointer to the output sequence of value aggregates (one aggregate per run)
 *
 * @param d_num_runs_out
 *   Pointer to total number of runs encountered
 *   (i.e., the length of d_unique_out)
 *
 * @param tile_state
 *   Tile status interface
 *
 * @param start_tile
 *   The starting tile for the current grid
 *
 * @param equality_op
 *   KeyT equality operator
 *
 * @param reduction_op
 *   ValueT reduction operator
 *
 * @param num_items
 *   Total number of items to select from
 */
template <typename PolicySelector,
          typename KeysInputIteratorT,
          typename UniqueOutputIteratorT,
          typename ValuesInputIteratorT,
          typename AggregatesOutputIteratorT,
          typename NumRunsOutputIteratorT,
          typename ScanTileStateT,
          typename EqualityOpT,
          typename ReductionOpT,
          typename OffsetT,
          typename AccumT,
          typename StreamingContextT>
#if _CCCL_HAS_CONCEPTS()
  requires reduce_by_key_policy_selector<PolicySelector>
#endif
__launch_bounds__(int(current_policy<PolicySelector>().threads_per_block))
  _CCCL_KERNEL_ATTRIBUTES void DeviceReduceByKeyKernel(
    const KeysInputIteratorT d_keys_in,
    const UniqueOutputIteratorT d_unique_out,
    const ValuesInputIteratorT d_values_in,
    const AggregatesOutputIteratorT d_aggregates_out,
    const NumRunsOutputIteratorT d_num_runs_out,
    ScanTileStateT tile_state,
    const int start_tile,
    EqualityOpT equality_op,
    ReductionOpT reduction_op,
    const OffsetT num_items,
    const StreamingContextT streaming_context,
    vsmem_t vsmem)
{
  static constexpr reduce_by_key_policy policy = current_policy<PolicySelector>();
  using AgentReduceByKeyPolicyT                = AgentReduceByKeyPolicy<
                   policy.threads_per_block,
                   policy.items_per_thread,
                   policy.load_algorithm,
                   policy.load_modifier,
                   policy.scan_algorithm,
                   delay_constructor_t<policy.delay_constructor.kind,
                                       policy.delay_constructor.delay,
                                       policy.delay_constructor.l2_write_latency>>;

  using vsmem_helper_t = vsmem_helper_default_fallback_policy_t<
    AgentReduceByKeyPolicyT,
    AgentReduceByKey,
    KeysInputIteratorT,
    UniqueOutputIteratorT,
    ValuesInputIteratorT,
    AggregatesOutputIteratorT,
    NumRunsOutputIteratorT,
    EqualityOpT,
    ReductionOpT,
    OffsetT,
    AccumT,
    StreamingContextT>;

  // Thread block type for reducing tiles of value segments
  using agent_reduce_by_key_t = typename vsmem_helper_t::agent_t;

  // Static shared memory allocation
  __shared__ typename vsmem_helper_t::static_temp_storage_t static_temp_storage;

  // Get temporary storage
  typename agent_reduce_by_key_t::TempStorage& temp_storage =
    vsmem_helper_t::get_temp_storage(static_temp_storage, vsmem);

  // Process tiles
  agent_reduce_by_key_t(
    temp_storage,
    d_keys_in,
    d_unique_out,
    d_values_in,
    d_aggregates_out,
    d_num_runs_out,
    equality_op,
    reduction_op,
    streaming_context)
    .ConsumeRange(num_items, tile_state, start_tile);

  // If applicable, hints to discard modified cache lines for vsmem
  vsmem_helper_t::discard_temp_storage(temp_storage);
}
} // namespace detail::reduce_by_key

/******************************************************************************
 * Dispatch
 ******************************************************************************/

/**
 * @brief Utility class for dispatching the appropriately-tuned kernels for
 *        DeviceReduceByKey
 *
 * @tparam KeysInputIteratorT
 *   Random-access input iterator type for keys
 *
 * @tparam UniqueOutputIteratorT
 *   Random-access output iterator type for keys
 *
 * @tparam ValuesInputIteratorT
 *   Random-access input iterator type for values
 *
 * @tparam AggregatesOutputIteratorT
 *   Random-access output iterator type for values
 *
 * @tparam NumRunsOutputIteratorT
 *   Output iterator type for recording number of segments encountered
 *
 * @tparam EqualityOpT
 *   KeyT equality operator type
 *
 * @tparam ReductionOpT
 *   ValueT reduction operator type
 *
 * @tparam OffsetT
 *   Signed integer type for global offsets
 *
 * @tparam PolicyHub
 *   Implementation detail, do not specify directly, requirements on the
 *   content of this type are subject to breaking change.
 */
// TODO(bgruber): deprecate when we make the tuning API public and remove in CCCL 4.0
template <typename KeysInputIteratorT,
          typename UniqueOutputIteratorT,
          typename ValuesInputIteratorT,
          typename AggregatesOutputIteratorT,
          typename NumRunsOutputIteratorT,
          typename EqualityOpT,
          typename ReductionOpT,
          typename OffsetT,
          typename AccumT    = ::cuda::std::__accumulator_t<ReductionOpT,
                                                            cub::detail::it_value_t<ValuesInputIteratorT>,
                                                            cub::detail::it_value_t<ValuesInputIteratorT>>,
          typename PolicyHub = detail::reduce_by_key::policy_hub<
            ReductionOpT,
            AccumT,
            cub::detail::non_void_value_t<UniqueOutputIteratorT, cub::detail::it_value_t<KeysInputIteratorT>>>>
struct DispatchReduceByKey
{
  //-------------------------------------------------------------------------
  // Types and constants
  //-------------------------------------------------------------------------

  // The input values type
  using ValueInputT = cub::detail::it_value_t<ValuesInputIteratorT>;

  // Type used to provide context for streaming invocations (this is currently not used by ReduceByKey yet)
  using streaming_context_t = NullType;

  static constexpr int INIT_KERNEL_THREADS = 128;

  // Tile status descriptor interface type
  using ScanTileStateT = ReduceByKeyScanTileState<AccumT, OffsetT>;

  void* d_temp_storage;
  size_t& temp_storage_bytes;
  KeysInputIteratorT d_keys_in;
  UniqueOutputIteratorT d_unique_out;
  ValuesInputIteratorT d_values_in;
  AggregatesOutputIteratorT d_aggregates_out;
  NumRunsOutputIteratorT d_num_runs_out;
  EqualityOpT equality_op;
  ReductionOpT reduction_op;
  OffsetT num_items;
  cudaStream_t stream;

  CUB_RUNTIME_FUNCTION _CCCL_FORCEINLINE DispatchReduceByKey(
    void* d_temp_storage,
    size_t& temp_storage_bytes,
    KeysInputIteratorT d_keys_in,
    UniqueOutputIteratorT d_unique_out,
    ValuesInputIteratorT d_values_in,
    AggregatesOutputIteratorT d_aggregates_out,
    NumRunsOutputIteratorT d_num_runs_out,
    EqualityOpT equality_op,
    ReductionOpT reduction_op,
    OffsetT num_items,
    cudaStream_t stream)
      : d_temp_storage(d_temp_storage)
      , temp_storage_bytes(temp_storage_bytes)
      , d_keys_in(d_keys_in)
      , d_unique_out(d_unique_out)
      , d_values_in(d_values_in)
      , d_aggregates_out(d_aggregates_out)
      , d_num_runs_out(d_num_runs_out)
      , equality_op(equality_op)
      , reduction_op(reduction_op)
      , num_items(num_items)
      , stream(stream)
  {}

  //---------------------------------------------------------------------
  // Dispatch entrypoints
  //---------------------------------------------------------------------

  template <typename ActivePolicyT, typename ScanInitKernelT, typename ReduceByKeyKernelT>
  CUB_RUNTIME_FUNCTION _CCCL_VISIBILITY_HIDDEN _CCCL_FORCEINLINE cudaError_t
  Invoke(ScanInitKernelT init_kernel, ReduceByKeyKernelT reduce_by_key_kernel)
  {
    using vsmem_helper_t = detail::vsmem_helper_default_fallback_policy_t<
      typename ActivePolicyT::ReduceByKeyPolicyT,
      detail::reduce_by_key::AgentReduceByKey,
      KeysInputIteratorT,
      UniqueOutputIteratorT,
      ValuesInputIteratorT,
      AggregatesOutputIteratorT,
      NumRunsOutputIteratorT,
      EqualityOpT,
      ReductionOpT,
      OffsetT,
      AccumT,
      streaming_context_t>;

    constexpr int threads_per_block = vsmem_helper_t::agent_policy_t::BLOCK_THREADS;
    constexpr int items_per_thread  = vsmem_helper_t::agent_policy_t::ITEMS_PER_THREAD;

    cudaError error = cudaSuccess;
    do
    {
      // Get device ordinal
      int device_ordinal;
      error = CubDebug(cudaGetDevice(&device_ordinal));
      if (cudaSuccess != error)
      {
        break;
      }

      // Number of input tiles
      int tile_size = threads_per_block * items_per_thread;
      int num_tiles = static_cast<int>(::cuda::ceil_div(num_items, tile_size));

      // The amount of virtual shared memory to allocate
      const auto vsmem_size = num_tiles * vsmem_helper_t::vsmem_per_block;

      // Specify temporary storage allocation requirements
      size_t tile_descriptor_memory{};
      error = CubDebug(ScanTileStateT::AllocationSize(num_tiles, tile_descriptor_memory));
      if (cudaSuccess != error)
      {
        break; // bytes needed for tile status descriptors
      }
      size_t allocation_sizes[2] = {tile_descriptor_memory, vsmem_size};

      // Compute allocation pointers into the single storage blob (or compute
      // the necessary size of the blob)
      void* allocations[2] = {};

      error = CubDebug(detail::alias_temporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes));
      if (cudaSuccess != error)
      {
        break;
      }

      if (d_temp_storage == nullptr)
      {
        // Return if the caller is simply requesting the size of the storage
        // allocation
        break;
      }

      // Construct the tile status interface
      ScanTileStateT tile_state;
      error = CubDebug(tile_state.Init(num_tiles, allocations[0], allocation_sizes[0]));
      if (cudaSuccess != error)
      {
        break;
      }

      // Log init_kernel configuration
      int init_grid_size = ::cuda::std::max(1, ::cuda::ceil_div(num_tiles, INIT_KERNEL_THREADS));

#ifdef CUB_DEBUG_LOG
      _CubLog("Invoking init_kernel<<<%d, %d, 0, %lld>>>()\n", init_grid_size, INIT_KERNEL_THREADS, (long long) stream);
#endif // CUB_DEBUG_LOG

      // Invoke init_kernel to initialize tile descriptors
      error = CubDebug(
        THRUST_NS_QUALIFIER::cuda_cub::detail::triple_chevron(init_grid_size, INIT_KERNEL_THREADS, 0, stream)
          .doit(init_kernel, tile_state, num_tiles, d_num_runs_out));
      if (cudaSuccess != error)
      {
        break;
      }

      // Sync the stream if specified to flush runtime errors
      error = CubDebug(detail::DebugSyncStream(stream));
      if (cudaSuccess != error)
      {
        break;
      }

      // Return if empty problem: note, we're initializing d_num_runs_out to 0 in init_kernel above
      if (num_items == 0)
      {
        break;
      }

      // Get SM occupancy for reduce_by_key_kernel
      int reduce_by_key_sm_occupancy;
      error = CubDebug(MaxSmOccupancy(reduce_by_key_sm_occupancy, reduce_by_key_kernel, threads_per_block));

      if (cudaSuccess != error)
      {
        break;
      }

      // Get max x-dimension of grid
      int max_dim_x;
      error = CubDebug(cudaDeviceGetAttribute(&max_dim_x, cudaDevAttrMaxGridDimX, device_ordinal));
      if (cudaSuccess != error)
      {
        break;
      }

      // Run grids in epochs (in case number of tiles exceeds max x-dimension
      int scan_grid_size = ::cuda::std::min(num_tiles, max_dim_x);
      for (int start_tile = 0; start_tile < num_tiles; start_tile += scan_grid_size)
      {
// Log reduce_by_key_kernel configuration
#ifdef CUB_DEBUG_LOG
        _CubLog("Invoking %d reduce_by_key_kernel<<<%d, %d, 0, %lld>>>(), %d "
                "items per thread, %d SM occupancy\n",
                start_tile,
                scan_grid_size,
                threads_per_block,
                (long long) stream,
                items_per_thread,
                reduce_by_key_sm_occupancy);
#endif // CUB_DEBUG_LOG

        // Invoke reduce_by_key_kernel
        error = CubDebug(
          THRUST_NS_QUALIFIER::cuda_cub::detail::triple_chevron(scan_grid_size, threads_per_block, 0, stream)
            .doit(reduce_by_key_kernel,
                  d_keys_in,
                  d_unique_out,
                  d_values_in,
                  d_aggregates_out,
                  d_num_runs_out,
                  tile_state,
                  start_tile,
                  equality_op,
                  reduction_op,
                  num_items,
                  streaming_context_t{},
                  cub::detail::vsmem_t{allocations[1]}));
        if (cudaSuccess != error)
        {
          break;
        }

        // Sync the stream if specified to flush runtime errors
        error = CubDebug(detail::DebugSyncStream(stream));
        if (cudaSuccess != error)
        {
          break;
        }
      }
    } while (false);

    return error;
  }

  template <typename ActivePolicyT>
  CUB_RUNTIME_FUNCTION _CCCL_FORCEINLINE cudaError_t Invoke()
  {
    return Invoke<ActivePolicyT>(
      detail::scan::DeviceCompactInitKernel<ScanTileStateT, NumRunsOutputIteratorT>,
      detail::reduce_by_key::DeviceReduceByKeyKernel<
        detail::reduce_by_key::policy_selector_from_hub<PolicyHub>,
        KeysInputIteratorT,
        UniqueOutputIteratorT,
        ValuesInputIteratorT,
        AggregatesOutputIteratorT,
        NumRunsOutputIteratorT,
        ScanTileStateT,
        EqualityOpT,
        ReductionOpT,
        OffsetT,
        AccumT,
        streaming_context_t>);
  }

  /**
   * Internal dispatch routine
   * @param[in] d_temp_storage
   *   Device-accessible allocation of temporary storage. When `nullptr`, the
   *   required allocation size is written to `temp_storage_bytes` and no
   *   work is done.
   *
   * @param[in,out] temp_storage_bytes
   *   Reference to size in bytes of `d_temp_storage` allocation
   *
   * @param[in] d_keys_in
   *   Pointer to the input sequence of keys
   *
   * @param[out] d_unique_out
   *   Pointer to the output sequence of unique keys (one key per run)
   *
   * @param[in] d_values_in
   *   Pointer to the input sequence of corresponding values
   *
   * @param[out] d_aggregates_out
   *   Pointer to the output sequence of value aggregates
   *   (one aggregate per run)
   *
   * @param[out] d_num_runs_out
   *   Pointer to total number of runs encountered
   *   (i.e., the length of d_unique_out)
   *
   * @param[in] equality_op
   *   KeyT equality operator
   *
   * @param[in] reduction_op
   *   ValueT reduction operator
   *
   * @param[in] num_items
   *   Total number of items to select from
   *
   * @param[in] stream
   *   CUDA stream to launch kernels within. Default is stream<sub>0</sub>.
   */
  CUB_RUNTIME_FUNCTION _CCCL_FORCEINLINE static cudaError_t Dispatch(
    void* d_temp_storage,
    size_t& temp_storage_bytes,
    KeysInputIteratorT d_keys_in,
    UniqueOutputIteratorT d_unique_out,
    ValuesInputIteratorT d_values_in,
    AggregatesOutputIteratorT d_aggregates_out,
    NumRunsOutputIteratorT d_num_runs_out,
    EqualityOpT equality_op,
    ReductionOpT reduction_op,
    OffsetT num_items,
    cudaStream_t stream)
  {
    cudaError error = cudaSuccess;

    do
    {
      // Get PTX version
      int ptx_version = 0;
      error           = CubDebug(PtxVersion(ptx_version));
      if (cudaSuccess != error)
      {
        break;
      }

      DispatchReduceByKey dispatch(
        d_temp_storage,
        temp_storage_bytes,
        d_keys_in,
        d_unique_out,
        d_values_in,
        d_aggregates_out,
        d_num_runs_out,
        equality_op,
        reduction_op,
        num_items,
        stream);

      // Dispatch
      error = CubDebug(PolicyHub::MaxPolicy::Invoke(ptx_version, dispatch));
      if (cudaSuccess != error)
      {
        break;
      }
    } while (false);

    return error;
  }
};

namespace detail::reduce_by_key
{
// we move the conversion of the policy to the agent policy and its use out of the lambda below, so MSVC does not ICE
template <typename PolicyGetter, typename... Args>
_CCCL_HOST_DEVICE_API auto determine_threads_items_vsmem(PolicyGetter policy_getter)
{
  // TODO(bgruber): refactor this in the future
  constexpr reduce_by_key_policy policy = policy_getter();
  using Policy                          = AgentReduceByKeyPolicy<
                             policy.threads_per_block,
                             policy.items_per_thread,
                             policy.load_algorithm,
                             policy.load_modifier,
                             policy.scan_algorithm,
                             delay_constructor_t<policy.delay_constructor.kind,
                                                 policy.delay_constructor.delay,
                                                 policy.delay_constructor.l2_write_latency>>;
  using vsmem_helper_t = vsmem_helper_default_fallback_policy_t<Policy, AgentReduceByKey, Args...>;
  return ::cuda::std::tuple{vsmem_helper_t::agent_policy_t::BLOCK_THREADS,
                            vsmem_helper_t::agent_policy_t::ITEMS_PER_THREAD,
                            vsmem_helper_t::vsmem_per_block};
}

template <
  typename OverrideAccumT = use_default,
  typename KeysInputIteratorT,
  typename UniqueOutputIteratorT,
  typename ValuesInputIteratorT,
  typename AggregatesOutputIteratorT,
  typename NumRunsOutputIteratorT,
  typename EqualityOpT,
  typename ReductionOpT,
  typename OffsetT,
  typename AccumT = ::cuda::std::conditional_t<
    !::cuda::std::is_same_v<OverrideAccumT, use_default>,
    OverrideAccumT,
    ::cuda::std::__accumulator_t<ReductionOpT, it_value_t<ValuesInputIteratorT>, it_value_t<ValuesInputIteratorT>>>,
  typename KeyT           = non_void_value_t<UniqueOutputIteratorT, it_value_t<KeysInputIteratorT>>,
  typename PolicySelector = policy_selector_from_types<ReductionOpT, AccumT, KeyT>>
#if _CCCL_HAS_CONCEPTS()
  requires reduce_by_key::reduce_by_key_policy_selector<PolicySelector>
#endif // _CCCL_HAS_CONCEPTS()
CUB_RUNTIME_FUNCTION _CCCL_FORCEINLINE static cudaError_t dispatch(
  void* d_temp_storage,
  size_t& temp_storage_bytes,
  KeysInputIteratorT d_keys_in,
  UniqueOutputIteratorT d_unique_out,
  ValuesInputIteratorT d_values_in,
  AggregatesOutputIteratorT d_aggregates_out,
  NumRunsOutputIteratorT d_num_runs_out,
  EqualityOpT equality_op,
  ReductionOpT reduction_op,
  OffsetT num_items,
  cudaStream_t stream,
  PolicySelector policy_selector = {})
{
  using streaming_context_t = NullType; // streaming context not used for ReduceByKey yet
  using ScanTileStateT      = ReduceByKeyScanTileState<AccumT, OffsetT>;
  [[maybe_unused]] static constexpr int init_kernel_threads = 128;

  ::cuda::compute_capability cc{};
  if (const auto error = CubDebug(ptx_compute_cap(cc)))
  {
    return error;
  }

  return detail::dispatch_compute_cap(policy_selector, cc, [&](auto policy_getter) {
#if _CCCL_HOSTED() && defined(CUB_DEBUG_LOG)
    NV_IF_TARGET(NV_IS_HOST, ({
                   ::std::stringstream ss;
                   ss << policy_getter();
                   _CubLog("Dispatching DeviceReduceByKey to compute capability %d.%d with tuning: %s\n",
                           cc.major_cap(),
                           cc.minor_cap(),
                           ss.str().c_str());
                 }))
#endif // _CCCL_HOSTED() && defined(CUB_DEBUG_LOG)

    const auto [threads_per_block, items_per_thread, vsmem_per_block] = determine_threads_items_vsmem<
      decltype(policy_getter),
      KeysInputIteratorT,
      UniqueOutputIteratorT,
      ValuesInputIteratorT,
      AggregatesOutputIteratorT,
      NumRunsOutputIteratorT,
      EqualityOpT,
      ReductionOpT,
      OffsetT,
      AccumT,
      streaming_context_t>(policy_getter);

    // Number of input tiles
    const int tile_size = threads_per_block * items_per_thread;
    const int num_tiles = static_cast<int>(::cuda::ceil_div(num_items, tile_size));

    // The amount of virtual shared memory to allocate
    const auto vsmem_size = num_tiles * vsmem_per_block;

    size_t tile_descriptor_memory{};
    if (const auto error = CubDebug(ScanTileStateT::AllocationSize(num_tiles, tile_descriptor_memory)))
    {
      return error;
    }
    size_t allocation_sizes[2] = {tile_descriptor_memory, vsmem_size};
    void* allocations[2]       = {};

    if (const auto error =
          CubDebug(detail::alias_temporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes)))
    {
      return error;
    }

    if (d_temp_storage == nullptr)
    {
      return cudaSuccess;
    }

    ScanTileStateT tile_state;
    if (const auto error = CubDebug(tile_state.Init(num_tiles, allocations[0], allocation_sizes[0])))
    {
      return error;
    }

    const int init_grid_size = ::cuda::std::max(1, ::cuda::ceil_div(num_tiles, init_kernel_threads));
#ifdef CUB_DEBUG_LOG
    _CubLog("Invoking init_kernel<<<%d, %d, 0, %lld>>>()\n", init_grid_size, init_kernel_threads, (long long) stream);
#endif
    if (const auto error = CubDebug(
          THRUST_NS_QUALIFIER::cuda_cub::detail::triple_chevron(init_grid_size, init_kernel_threads, 0, stream)
            .doit(detail::scan::DeviceCompactInitKernel<ScanTileStateT, NumRunsOutputIteratorT>,
                  tile_state,
                  num_tiles,
                  d_num_runs_out)))
    {
      return error;
    }
    if (const auto error = CubDebug(detail::DebugSyncStream(stream)))
    {
      return error;
    }
    if (num_items == 0)
    {
      return cudaSuccess;
    }

    auto reduce_by_key_kernel = &DeviceReduceByKeyKernel<
      PolicySelector,
      KeysInputIteratorT,
      UniqueOutputIteratorT,
      ValuesInputIteratorT,
      AggregatesOutputIteratorT,
      NumRunsOutputIteratorT,
      ScanTileStateT,
      EqualityOpT,
      ReductionOpT,
      OffsetT,
      AccumT,
      streaming_context_t>;

    int reduce_by_key_sm_occupancy{};
    if (const auto error =
          CubDebug(MaxSmOccupancy(reduce_by_key_sm_occupancy, reduce_by_key_kernel, threads_per_block)))
    {
      return error;
    }

    int device_ordinal{};
    if (const auto error = CubDebug(cudaGetDevice(&device_ordinal)))
    {
      return error;
    }
    int max_dim_x{};
    if (const auto error = CubDebug(cudaDeviceGetAttribute(&max_dim_x, cudaDevAttrMaxGridDimX, device_ordinal)))
    {
      return error;
    }

    const int scan_grid_size = ::cuda::std::min(num_tiles, max_dim_x);
    for (int start_tile = 0; start_tile < num_tiles; start_tile += scan_grid_size)
    {
#ifdef CUB_DEBUG_LOG
      _CubLog("Invoking %d reduce_by_key_kernel<<<%d, %d, 0, %lld>>>(), %d items per thread, %d SM occupancy\n",
              start_tile,
              scan_grid_size,
              threads_per_block,
              (long long) stream,
              items_per_thread,
              reduce_by_key_sm_occupancy);
#endif
      if (const auto error = CubDebug(
            THRUST_NS_QUALIFIER::cuda_cub::detail::triple_chevron(scan_grid_size, threads_per_block, 0, stream)
              .doit(reduce_by_key_kernel,
                    d_keys_in,
                    d_unique_out,
                    d_values_in,
                    d_aggregates_out,
                    d_num_runs_out,
                    tile_state,
                    start_tile,
                    equality_op,
                    reduction_op,
                    num_items,
                    streaming_context_t{},
                    cub::detail::vsmem_t{allocations[1]})))
      {
        return error;
      }
      if (const auto error = CubDebug(detail::DebugSyncStream(stream)))
      {
        return error;
      }
    }
    return cudaSuccess;
  });
}
} // namespace detail::reduce_by_key

CUB_NAMESPACE_END
