Skip to content

thrust::tabulate is much slower than equivalent transform/for_each for wide row functor #9070

Open

Description

@bdice

Summary

thrust::tabulate is significantly slower than equivalent thrust::transform, thrust::for_each_n, cub::DeviceFor::ForEach, and a direct CUDA kernel for a row-wise functor that reads a wide row and writes one output value.

This came up while investigating libcudf row hashing performance. I minimized it to a standalone CCCL + NVBench reproducer that does not depend on cuDF or RMM.

Reproducer

I have a self-contained reproducer with these files:

  • tabulate_reproducer.cu
  • nvbench_main.cu
  • CMakeLists.txt
  • README.md

The benchmark compares these variants over the same synthetic row-hash functor and data:

  • thrust::tabulate(output.begin(), output.end(), row_hasher)
  • thrust::transform(counting_iterator, output.begin(), row_hasher)
  • thrust::for_each_n(counting_iterator, lambda writes output[row])
  • cub::DeviceFor::ForEach(counting_iterator range, lambda writes output[row])
  • direct CUDA grid-stride kernel

The core functor is:

struct row_hasher {
  cuda::std::uint64_t const* columns{};
  int num_rows{};
  int num_cols{};
  hash_type seed{};

  __device__ hash_type operator()(int row_index) const
  {
    auto hash = mix64_to_32(columns[row_index], seed);
    for (int column_index = 1; column_index < num_cols; ++column_index) {
      auto const value = columns[static_cast<std::size_t>(column_index) * num_rows + row_index];
      hash             = hash_combine(hash, mix64_to_32(value, seed));
    }
    return hash;
  }
};

Full reproducer source:

// tabulate_reproducer.cu
#include <nvbench/nvbench.cuh>

#include <cub/device/device_for.cuh>
#include <cuda/std/cstdint>
#include <cuda/std/limits>
#include <cuda_runtime_api.h>
#include <thrust/count.h>
#include <thrust/device_vector.h>
#include <thrust/execution_policy.h>
#include <thrust/for_each.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/tabulate.h>
#include <thrust/transform.h>

#include <string>

namespace {

using hash_type = cuda::std::uint32_t;

__host__ __device__ hash_type hash_combine(hash_type lhs, hash_type rhs)
{
  return lhs ^ (rhs + 0x9e37'79b9u + (lhs << 6) + (lhs >> 2));
}

__host__ __device__ hash_type mix64_to_32(cuda::std::uint64_t key, hash_type seed)
{
  key ^= static_cast<cuda::std::uint64_t>(seed) + 0x9e37'79b9'7f4a'7c15ull;
  key ^= key >> 33;
  key *= 0xff51afd7ed558ccdull;
  key ^= key >> 33;
  key *= 0xc4ceb9fe1a85ec53ull;
  key ^= key >> 33;
  return static_cast<hash_type>(key ^ (key >> 32));
}

struct row_hasher {
  cuda::std::uint64_t const* columns{};
  int num_rows{};
  int num_cols{};
  hash_type seed{};

  __device__ hash_type operator()(int row_index) const
  {
    auto hash = mix64_to_32(columns[row_index], seed);
    for (int column_index = 1; column_index < num_cols; ++column_index) {
      auto const value = columns[static_cast<std::size_t>(column_index) * num_rows + row_index];
      hash             = hash_combine(hash, mix64_to_32(value, seed));
    }
    return hash;
  }
};

__global__ void direct_kernel(row_hasher hasher, hash_type* output)
{
  auto row_index = static_cast<int>(threadIdx.x + blockIdx.x * blockDim.x);
  auto const stride = static_cast<int>(blockDim.x * gridDim.x);
  for (; row_index < hasher.num_rows; row_index += stride) {
    output[row_index] = hasher(row_index);
  }
}

void check_cuda(cudaError_t status)
{
  if (status != cudaSuccess) { throw std::runtime_error(cudaGetErrorString(status)); }
}

void bench_row_hash(nvbench::state& state)
{
  auto const num_rows = static_cast<int>(state.get_int64("num_rows"));
  auto const num_cols = static_cast<int>(state.get_int64("num_cols"));
  auto const variant  = state.get_string("variant");

  thrust::device_vector<cuda::std::uint64_t> columns(
    static_cast<std::size_t>(num_rows) * num_cols);
  thrust::device_vector<hash_type> output(num_rows);

  auto const init_hasher = [data = thrust::raw_pointer_cast(columns.data()),
                            num_rows,
                            num_cols] __device__(int index) {
    auto const row = index % num_rows;
    auto const col = index / num_rows;
    data[index] = (static_cast<cuda::std::uint64_t>(col) << 32) ^
                  static_cast<cuda::std::uint64_t>(row * 1315423911u + col);
  };
  thrust::for_each_n(thrust::device,
                     thrust::make_counting_iterator<int>(0),
                     static_cast<int>(columns.size()),
                     init_hasher);

  row_hasher const hasher{thrust::raw_pointer_cast(columns.data()), num_rows, num_cols, 0};
  auto* output_ptr = thrust::raw_pointer_cast(output.data());

  state.add_global_memory_reads<nvbench::int64_t>(static_cast<int64_t>(num_rows) * num_cols);
  state.add_global_memory_writes<nvbench::uint32_t>(num_rows);

  state.exec(nvbench::exec_tag::sync, [&](nvbench::launch& launch) {
    auto const stream = launch.get_stream().get_stream();
    if (variant == "tabulate") {
      thrust::tabulate(thrust::cuda::par.on(stream), output.begin(), output.end(), hasher);
    } else if (variant == "transform") {
      thrust::transform(thrust::cuda::par.on(stream),
                        thrust::make_counting_iterator<int>(0),
                        thrust::make_counting_iterator(num_rows),
                        output.begin(),
                        hasher);
    } else if (variant == "for_each") {
      thrust::for_each_n(thrust::cuda::par.on(stream),
                         thrust::make_counting_iterator<int>(0),
                         num_rows,
                         [hasher, output_ptr] __device__(int row_index) {
                           output_ptr[row_index] = hasher(row_index);
                         });
    } else if (variant == "cub_for") {
      check_cuda(cub::DeviceFor::ForEach(
        thrust::make_counting_iterator<int>(0),
        thrust::make_counting_iterator(num_rows),
        [hasher, output_ptr] __device__(int row_index) { output_ptr[row_index] = hasher(row_index); },
        stream));
    } else if (variant == "direct_kernel") {
      auto constexpr block_size = 256;
      auto const grid_size      = (num_rows + block_size - 1) / block_size;
      direct_kernel<<<grid_size, block_size, 0, stream>>>(hasher, output_ptr);
      check_cuda(cudaPeekAtLastError());
    } else {
      state.skip("unknown variant");
    }
  });
}

NVBENCH_BENCH(bench_row_hash)
  .set_name("row_hash")
  .add_int64_axis("num_rows", {1048576, 16777216})
  .add_int64_axis("num_cols", {8, 32, 128, 256})
  .add_string_axis("variant", {"tabulate", "transform", "for_each", "cub_for", "direct_kernel"});

}  // namespace
// nvbench_main.cu
#include <nvbench/main.cuh>

NVBENCH_MAIN

Observed results

Hardware: NVIDIA GB10
CUDA: 13.2
CCCL: from current RAPIDS/cuDF build dependency checkout
NVBench: v0.1.0 main:v26.02.00a-1118-gf239649f8d-dirty

Command:

./build/tabulate_reproducer \
  --benchmark row_hash \
  --axis num_rows=1048576 \
  --axis num_cols=[32,128,256] \
  --axis variant=[tabulate,transform,for_each,cub_for,direct_kernel] \
  --min-samples 5 \
  --min-time 0.05 \
  --timeout 20 \
  --devices 0

Results:

rows cols tabulate transform for_each cub_for direct_kernel
1,048,576 32 4.188 ms 1.264 ms 1.165 ms 1.201 ms 1.209 ms
1,048,576 128 17.430 ms 4.411 ms 4.510 ms 4.507 ms 4.502 ms
1,048,576 256 36.005 ms 9.255 ms 9.042 ms 9.061 ms 8.960 ms

thrust::tabulate is consistently about 3.5-4x slower than the equivalent variants.

Expected behavior

I would expect thrust::tabulate(output.begin(), output.end(), f) to be in the same performance family as thrust::transform(counting_iterator, output.begin(), f), thrust::for_each_n(counting_iterator, ...), and cub::DeviceFor::ForEach for this workload.

Activity

  1. bdice commented on May 19, 2026

    @bdice
    ContributorAuthor

    I dug into this further and isolated the cause.

    CUDA thrust::tabulate currently does this in thrust/thrust/system/cuda/detail/tabulate.h:

    cuda_cub::transform_n(
      policy, ::cuda::counting_iterator<size_type>{}, count, first, ::cuda::proclaim_copyable_arguments(tabulate_op));

    The slowdown is caused by cuda::proclaim_copyable_arguments(tabulate_op), not by transform_n itself or by cuda::counting_iterator.

    I added these variants to the standalone reproducer:

    • transform_n_ptrdiff: thrust::transform_n with thrust::counting_iterator<output_difference_type>
    • transform_n_cuda_counting: thrust::transform_n with cuda::counting_iterator<output_difference_type>
    • transform_n_proclaim: same as transform_n_ptrdiff, but wraps the functor in cuda::proclaim_copyable_arguments
    • transform_n_cuda_proclaim: same as transform_n_cuda_counting, but wraps the functor in cuda::proclaim_copyable_arguments

    On current main at fcd4ff4ea1:

    rows cols tabulate transform_n_ptrdiff transform_n_cuda_counting transform_n_proclaim transform_n_cuda_proclaim
    1,048,576 32 4.197 ms 1.185 ms 1.181 ms 4.277 ms 4.286 ms
    1,048,576 128 18.337 ms 4.679 ms 4.709 ms 18.361 ms 18.371 ms

    So adding proclaim_copyable_arguments to otherwise-fast transform_n reproduces the slow tabulate behavior exactly.

    I also tested this minimal local patch:

    diff --git a/thrust/thrust/system/cuda/detail/tabulate.h b/thrust/thrust/system/cuda/detail/tabulate.h
    index 7fd9ba2609..342e72d463 100644
    --- a/thrust/thrust/system/cuda/detail/tabulate.h
    +++ b/thrust/thrust/system/cuda/detail/tabulate.h
    @@ -32,8 +32,7 @@ void _CCCL_HOST_DEVICE tabulate(execution_policy<Derived>& policy, Iterator firs
     {
       using size_type  = ::cuda::std::iter_difference_t<Iterator>;
       const auto count = ::cuda::std::distance(first, last);
    -  cuda_cub::transform_n(
    -    policy, ::cuda::counting_iterator<size_type>{}, count, first, ::cuda::proclaim_copyable_arguments(tabulate_op));
    +  cuda_cub::transform_n(policy, ::cuda::counting_iterator<size_type>{}, count, first, tabulate_op);
     }

    With that patch, tabulate is back in the same performance family as the other variants:

    rows cols patched tabulate transform_n_ptrdiff for_each cub_for direct_kernel
    1,048,576 32 1.199 ms 1.182 ms 1.172 ms 1.191 ms 1.198 ms
    1,048,576 128 4.733 ms 4.657 ms 4.558 ms 4.641 ms 4.573 ms
    1,048,576 256 9.249 ms 9.312 ms 9.192 ms 9.148 ms 9.198 ms

    It seems like proclaim_copyable_arguments is used in tabulate because generated counting values do not need stable source addresses. However, the CUB non-stable-address transform path selected by proclaim_copyable_arguments is the slow path for this functor, so this regresses performance substantially.

  2. bdice commented on May 19, 2026

    @bdice
    ContributorAuthor

    It seems the implementation of thrust::tabulate changed in #6012.

  3. bernhardmgruber commented on May 19, 2026

    @bernhardmgruber
    Contributor

    Thx for reporting this. My guess is that thrust::tabulate will try hard to use the vectorized transform kernel, which uses aggressive unrolling. That's usually beneficial for the workloads we benchmark. It seems this is not the case for your functor.

    I can look into this in a few weeks. My best guess is that you will be very happy when we release the tuning API for DeviceTransform, so you can configure the backend implementation ;)

  4. moved this from Todo to In Progress in CCCLon May 19, 2026
  5. moved this from In Progress to In Review in CCCLon May 19, 2026
  6. bernhardmgruber commented on May 19, 2026

    @bernhardmgruber
    Contributor

    I would like to extract the provided benchmark and add it as a new thrust benchmark for tabulate.

  7. bdice commented on May 19, 2026

    @bdice
    ContributorAuthor

    Here are some additional benchmarks I ran on DGX Spark, trying to model cudf's usages of thrust::tabulate. For now I will implement cudf::detail::tabulate that mirrors the thrust::tabulate API but with a CUB for-each implementation.

    cuDF-style shape Representative feature items tabulate for_each_n speedup (tabulate / for_each_n)
    row_hash Murmur/xxhash row hashing 1,048,576 × 32 cols 4.204 ms 1.218 ms 3.45x
    row_hash Murmur/xxhash row hashing 1,048,576 × 128 cols 17.407 ms 4.414 ms 3.94x
    row_hash Murmur/xxhash row hashing 1,048,576 × 256 cols 36.398 ms 9.048 ms 4.02x
    scalar_sequence filling/sequence.cu 16,777,216 687.924 us 684.413 us 1.01x
    m2 groupby/common/m2_var_std.cu M2 16,777,216 2.053 ms 1.976 ms 1.04x
    variance_zip variance/std zipped output + validity 16,777,216 1.553 ms 1.490 ms 1.04x
    masked_hash groupby cached hash with bitmask 16,777,216 904.592 us 866.572 us 1.04x
    segmented_sequence lists/sequences.cu-style segmented lookup 1,048,576 73.230 us 75.209 us 0.97x
    segmented_sequence lists/sequences.cu-style segmented lookup 16,777,216 760.251 us 883.717 us 0.86x

    I also ran a basic segment size benchmark:

    template <class T>
    struct seg_size_t {
      T* d_offsets{};
    
      template <class OffsetT>
      __device__ T operator()(OffsetT i)
      {
        return static_cast<T>(d_offsets[i + 1] - d_offsets[i]);
      }
    };

    Results on current CCCL main:

    shape items tabulate for_each_n speedup (tabulate / for_each_n)
    segment_size 1,048,576 69.314 us 62.453 us 1.11x
    segment_size 16,777,216 593.662 us 582.446 us 1.02x

    for_each_n is faster here, modestly.

  8. bdice commented on May 26, 2026

    @bdice
    ContributorAuthor

    We're avoiding thrust::tabulate for now in NVIDIA/cudf#22632. I did not see significant slowdown in other instances of thrust::tabulate, the row hasher is the main culprit.

  9. added a commit that references this issue on May 28, 2026
  10. lrpierce commented on Aug 20, 2026

    @lrpierce

    I have also seen a similar issue with tabulate performance compared to thrust::transform in our library code requiring us to remove usage of tabulate. We have found that as the output data width increases the relative performance between the two deteriorates.

    Benchmark data using an A100

    elem CCCL 2.8.2 tabulate 2.8.2 transform CCCL 3.2.1 tabulate 3.2.1 transform ratio
    4 B 0.094 / 1431 0.099 / 1354 0.092 / 1456 0.100 / 1348 0.9x
    8 B 0.179 / 1503 0.173 / 1549 0.201 / 1337 0.174 / 1544 1.2x
    16 B 0.346 / 1551 0.340 / 1578 1.390 / 386 0.329 / 1632 4.2x
    32 B 0.755 / 1422 0.713 / 1505 4.243 / 253 0.691 / 1553 6.1x
    64 B 1.912 / 1123 1.686 / 1274 9.132 / 235 1.646 / 1305 5.5x

    Benchmark Reproducer:

    #include <thrust/device_vector.h>
    #include <thrust/execution_policy.h>
    #include <thrust/iterator/counting_iterator.h>
    #include <thrust/tabulate.h>
    #include <thrust/transform.h>
    
    #include <cuda/__functional/address_stability.h>
    
    #include <cstdio>
    
    template <int Bytes>
    struct alignas(Bytes < 16 ? Bytes : 16) Element
    {
        int v[Bytes / sizeof(int)];
    };
    
    template <int Bytes>
    struct Op
    {
        const Element<Bytes>* in;
    
        __device__ Element<Bytes> operator()(long long i) const
        {
            Element<Bytes> e = in[i];
            e.v[0] += 1;
            return e;
        }
    };
    
    template <typename F>
    float timeMs(F&& f, int reps = 5)
    {
        cudaEvent_t a, b;
        cudaEventCreate(&a);
        cudaEventCreate(&b);
        f();                       // warm up: the GPU idles at a low clock
        cudaDeviceSynchronize();
        cudaEventRecord(a);
        for (int r = 0; r < reps; ++r)
        {
            f();
        }
        cudaEventRecord(b);
        cudaDeviceSynchronize();
        float ms = 0.f;
        cudaEventElapsedTime(&ms, a, b);
        cudaEventDestroy(a);
        cudaEventDestroy(b);
        return ms / reps;
    }
    
    template <int Bytes>
    void run(int n)
    {
        using E = Element<Bytes>;
        thrust::device_vector<E> in(n), out(n);
        const Op<Bytes> op{thrust::raw_pointer_cast(in.data())};
        E* o = thrust::raw_pointer_cast(out.data());
    
        const double gb = 2.0 * double(n) * double(Bytes) / 1e9; // one read + one write per element
    
        const float tTab = timeMs([&] { thrust::tabulate(thrust::device, o, o + n, op); });
        const float tTra = timeMs([&] {
            thrust::transform(
                thrust::device, thrust::counting_iterator<long long>(0), thrust::counting_iterator<long long>(n), o, op);
        });
        const float tPcl = timeMs([&] {
            thrust::transform(thrust::device,
                              thrust::counting_iterator<long long>(0),
                              thrust::counting_iterator<long long>(n),
                              o,
                              ::cuda::proclaim_copyable_arguments(op));
        });
    
        std::printf("  %3d B  | %8.3f %7.0f | %8.3f %7.0f | %8.3f %7.0f |  %.1fx\n",
                    Bytes,
                    tTab, gb / (tTab / 1e3),
                    tTra, gb / (tTra / 1e3),
                    tPcl, gb / (tPcl / 1e3),
                    tTab / tTra);
    }
    
    int main()
    {
        const int n = 1 << 24; // 16.8M elements
    
        cudaDeviceProp prop{};
        cudaGetDeviceProperties(&prop, 0);
        const double peak = 2.0 * prop.memoryClockRate * 1e3 * (prop.memoryBusWidth / 8) / 1e9;
        std::printf("device: %s, sm_%d%d, HBM peak ~%.0f GB/s, CCCL %d\n",
                    prop.name, prop.major, prop.minor, peak, CCCL_VERSION);
        std::printf("n = %d elements, timings are ms / achieved GB/s\n\n", n);
        std::printf("  elem   |     tabulate    |    transform    | transform+pcl   | tab/tra\n");
        std::printf("  -------|-----------------|-----------------|-----------------|--------\n");
    
        run<4>(n);
        run<8>(n);
        run<16>(n);
        run<32>(n);
        run<64>(n);
        return 0;
    }
  11. bernhardmgruber commented on Sep 21, 2026

    @bernhardmgruber
    Contributor

    The current implementation of thrust::tabulate should use the filling code path in the vectorized kernel. For sm80, it tries to fill 8 items per thread, for sm90+ it tries 16 items per thread. in both cases, it tries to vectorize using 8-byte stores.

    If the elements get big, that's a lot of stores per single thread. thrust::transform falls back to a default code path where we use 2 items per thread. I assume that's the cause of the difference we are seeing here.

    Going forward, we would like to expose a tuning API for Thrust as well, so you will be able to customize this in the future.

  12. moved this from In Review to In Progress in CCCLon Sep 21, 2026
  13. moved this from In Progress to In Review in CCCLon Sep 21, 2026
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 Review

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions