Skip to content

[spike]: Speed-of-Light Fancy Iterators #11840

Open
1 of 3 issues completed
Open

Description

@gevtushenko

Is this a duplicate?

Area

General CCCL

Is your feature request related to a problem? Please describe.

Many CUB algorithms have fast paths, such as bulk copies into shared memory (DeviceScan, DeviceTransform, DeviceRunLengthEncode) and vectorized loads (DeviceReduce). While the number of algorithms using these optimizations will only grow, these fast paths are only taken when the iterators are contiguous. Fancy iterators are often thin wrappers over contiguous memory, for example transform_iterator<F, T*>, zip_iterator<T*, U*>, or transform_output_iterator<T*, G>. They aren't contiguous themselves, so they fall back to slower generic paths, even though their underlying pointers would qualify.

Users then have to choose between composability of fancy iterators and performance, but I believe that they don't have to.

We already have cases where we try to unpack fancy iterators. In #7442, we try to deliver SOL for thrust::zip_iterator, but these cases are over-specialized and already break on, say, cuda::zip_iterator #8258.

Users ask to improve performance of CCCL parallel algorithms when applied to fancy iterators. One cuOpt case #6143. On cudf side, a couple requested cases are 1, 2, and 3.

Here's a reproducer for the last one:

// Mirrors cudf::io::fst::stack_op_type
enum class stack_op_type : int32_t { READ = 0, PUSH = 1, POP = 2, RESET = 3 };

void reset_segment_scan(nvbench::state& state)
{
  // Types as instantiated in cudf
  using StackSymbolT  = char;     // cudf::io::json::StackSymbolT
  using StackSegmentT = uint8_t;  // logical_stack.cuh: using StackSegmentT = uint8_t;

  // Number of stack operations (brackets/braces/newlines outside of quotes)
  auto const num_symbols_in = static_cast<std::size_t>(state.get_int64("NumSymbols"));
  auto const reset_period   = static_cast<std::size_t>(state.get_int64("ResetPeriod"));

  // Sparse stack-op sequence: balanced '{' / '[' pushes and pops, '\n' every reset_period symbols
  thrust::device_vector<StackSymbolT> stack_ops(num_symbols_in);
  thrust::tabulate(stack_ops.begin(), stack_ops.end(), [reset_period] __device__(std::size_t i) -> StackSymbolT {
    constexpr char pattern[] = {'{', '[', ']', '}'};
    return (i % reset_period == 0) ? '\n' : pattern[i % 4];
  });

  // Mirrors JSONWithRecoveryToStackOp (nested_json_gpu.cu)
  auto symbol_to_stack_op = [] __host__ __device__(StackSymbolT const& stack_symbol) {
    switch (stack_symbol) {
      case '{':
      case '[': return stack_op_type::PUSH;
      case '}':
      case ']': return stack_op_type::POP;
      case '\n': return stack_op_type::RESET;
      default: return stack_op_type::READ;
    }
  };

  // Mirrors detail::NewlineToResetStackSegmentOp<JSONWithRecoveryToStackOp>
  auto newline_to_reset_segment = [symbol_to_stack_op] __host__ __device__(
                                    StackSymbolT const& stack_symbol) -> uint32_t {
    stack_op_type stack_op = symbol_to_stack_op(stack_symbol);
    // Every reset operation marks the beginning of a new segment
    return (stack_op == stack_op_type::RESET) ? 1 : 0;
  };

  // Mirrors detail::ModToTargetTypeOpT<StackSegmentT>, instantiated with T = uint32_t
  [[maybe_unused]] auto mod_to_target_type = [] __host__ __device__(uint32_t const& val) -> StackSegmentT {
    using T = uint32_t;
    return static_cast<StackSegmentT>(
      val % (static_cast<T>(cuda::std::numeric_limits<StackSegmentT>::max()) + static_cast<T>(1)));
  };

  // d_symbols: raw (non-const) char pointer, as stack_ops.data() in cudf
  StackSymbolT* d_symbols = thrust::raw_pointer_cast(stack_ops.data());

  thrust::device_vector<StackSegmentT> key_segments(num_symbols_in);

#ifdef USE_RAW_POINTERS
  thrust::device_vector<uint8_t> reset_flags(num_symbols_in);
  thrust::transform(stack_ops.begin(), stack_ops.end(), reset_flags.begin(), newline_to_reset_segment);
  uint8_t const* reset_segments_it = thrust::raw_pointer_cast(reset_flags.data());
  StackSegmentT* key_segments_out  = thrust::raw_pointer_cast(key_segments.data());
#else
  auto reset_segments_it = cuda::transform_iterator(d_symbols, newline_to_reset_segment);
  auto key_segments_out =
    cuda::make_transform_output_iterator(thrust::raw_pointer_cast(key_segments.data()), mod_to_target_type);
#endif

  std::size_t temp_storage_bytes = 0;
  cub::DeviceScan::InclusiveSum(
    nullptr, temp_storage_bytes, reset_segments_it, key_segments_out, num_symbols_in);
  thrust::device_vector<std::byte> temp_storage(temp_storage_bytes);
  void* d_temp_storage = thrust::raw_pointer_cast(temp_storage.data());

  cub::DeviceScan::InclusiveSum(
    d_temp_storage, temp_storage_bytes, reset_segments_it, key_segments_out, num_symbols_in);
  auto const mismatches = thrust::count_if(
    thrust::counting_iterator<std::size_t>{0},
    thrust::counting_iterator<std::size_t>{num_symbols_in},
    [segments = thrust::raw_pointer_cast(key_segments.data()), reset_period] __device__(std::size_t i) {
      return segments[i] != static_cast<StackSegmentT>((i / reset_period + 1) % 256);
    });
  if (mismatches != 0) {
    state.skip("Verification failed: " + std::to_string(mismatches) + " mismatches");
    return;
  }

  state.add_element_count(num_symbols_in);
  state.add_global_memory_reads<StackSymbolT>(num_symbols_in);
  state.add_global_memory_writes<StackSegmentT>(num_symbols_in);

  state.exec(nvbench::exec_tag::gpu | nvbench::exec_tag::no_batch, [&](nvbench::launch& launch) {
    cub::DeviceScan::InclusiveSum(d_temp_storage,
                                  temp_storage_bytes,
                                  reset_segments_it,
                                  key_segments_out,
                                  num_symbols_in,
                                  launch.get_stream());
  });
}

NVBENCH_BENCH(reset_segment_scan)
  .set_name("reset_segment_scan")
  .add_int64_power_of_two_axis("NumSymbols", {20, 24, 28, 31})
  .add_int64_axis("ResetPeriod", {1024});

On B200, the performance evaluation shows up to 60% performance difference between raw pointer and fancy iterator.

NumSymbols ResetPeriod Ref Time Ref Noise Cmp Time Cmp Noise Diff %Diff Status
2^16 1024 10.962 us 6.48% 11.262 us 0.40% 0.300 us 2.74% SLOW
2^20 1024 14.706 us 7.27% 12.689 us 7.14% -2.017 us -13.71% FAST
2^24 1024 41.294 us 2.86% 27.986 us 2.74% -13.308 us -32.23% FAST
2^28 1024 494.272 us 0.54% 212.613 us 0.49% -281.659 us -56.98% FAST
2^31 1024 3.866 ms 0.20% 1.622 ms 0.07% -2243.509 us -58.04% FAST

On A6000, lookahead is not available, so both paths go through the same look-back implementation, which currently doesn't have vectorization. Data below shows that adding iterator logic in the kernel doesn't lead to severe perf regression:

NumSymbols ResetPeriod Ref Time Ref Noise Cmp Time Cmp Noise Diff %Diff Status
2^20 1024 10.651 us 5.13% 9.189 us 5.83% -1.462 us -13.73% FAST
2^24 1024 55.719 us 1.93% 56.708 us 2.70% 0.989 us 1.77% SAME
2^28 1024 692.782 us 0.65% 690.584 us 0.66% -2.197 us -0.32% SAME
2^31 1024 5.409 ms 0.32% 5.406 ms 0.32% -3.431 us -0.06% SAME

On 6000 Pro, look-ahead is used for raw pointers, but perf difference is not as pronounced:

NumSymbols ResetPeriod Ref Time Ref Noise Cmp Time Cmp Noise Diff %Diff Status
2^20 1024 8.180 us 0.24% 6.120 us 0.25% -2.060 us -25.18% FAST
2^24 1024 32.361 us 2.51% 24.081 us 3.77% -8.280 us -25.59% FAST
2^28 1024 392.178 us 0.31% 363.228 us 0.57% -28.950 us -7.38% FAST
2^31 1024 2.996 ms 0.17% 2.897 ms 0.11% -98.766 us -3.30% FAST

We put a lot of effort into optimizing memory movement for modern architectures in increasing number of kernels. We should be able to deliver these optimizations to the users of fancy iterators.

Describe the solution you'd like

This is a spike on investigating iterator abstraction that'd allow us to:

  • unpack iterator into a tuple of raw pointers and transformation object
  • load from underlying raw pointers into shared memory (ublkcp) or registers (vectorized)
  • re-pack loaded data and transformation object into on-chip iterator

This should allow kernels to preserve SOL code path for loading data while preserving functionality of fancy iterators.

This issue can be closed by:

  • comment on the issue with any additional use cases where unpacking fancy iterators is performance critical
  • comment on the issue with a list of iterators for which we can do unpacking automatically without breaking functionality and a list of iterators for which we need user to proclaim it's safe to do
  • link to a branch with PoC that adds implementation-detail abstractions:
    • unpack(it) -> pair<tuple<Ts*>, F>
    • repack(tuple<Ts*>, F) -> rit
    • trait to be used instead of is_contiguous_iterator that says when iterator can be unpacked into underlying raw pointers

Describe alternatives you've considered

No response

Additional context

No response

Sub-issues

Sub-issues

1 of 3 Issues completed
Loading 3 sub-issues

Activity

  1. miscco commented on Nov 4, 2026

    @miscco
    Contributor

    Having investigated this I believe we need to split this up into different workstreams, because there are different applications that require different solutions and have varying impact on the implementation of the actual algorithm

    1. Loading memory into registers

    For this we can do vectorized loads of the underlying contiguous storage and then rebase the fancy iterator on top of the vectorized load.

    BaseIter* -> BaseIterValueType[ItemsPerThread] -> rewrap -> T[ItempsPerThread]

    This has the advantage that the unwrapping is purely internal to the load algorithms. There are no changes necessary on the algorithm side (besides tuning). The main issue that can arise is increased register pressure or spills.

    1. Loading memory into other memory

    The main use case here is loading from global memory into shared memory. The issue here is that the unwrapping is externall to the load algorithm, so we need to actually change the algorithm that previously assumed a T* to suddenly work with fancy iterators.

    It is also not clear whether this is an improvement. Consider an algorithm like partition_flagged where we represent the flagged array through a transform iterator. Storing BaseType rather than bool can greatly increase shared memory requirements which could adversely affect performance

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
    Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions