Skip to content

[EPIC] Optimize thrust::transform for newer architectures #1947

Open

Description

@bernhardmgruber

Motivation
It's increasingly harder to reach SOL on newer GPU architectures, starting with A100 and H100, especially for simple kernels, like:
thrust::transform(..., thrust::plus{}), which basically load a few values and perform little compute. CUB algorithms already counter this by processing several elements per thread, but internal research hints at the necessity to further increase the amount of data in flight.

Use case
thrust::transform is an important primitive for many algorithms and also occurs in BabelStream, i highly relevant HPC benchmark often used to produce representative numbers to compare the performance of hardware architectures. We should therefore dedicate some effort to ensure thrust::transform performs well.

Approach
The main strategy is to have more "bytes in flight" when reading, with the concrete amount depending on the target architecture (tuning parameter). There are multiple ways to generate more loads. Again, internal research points to using either prefetching or the tensor memory accelerator (TMA, e.g. via memcpy_async) on newer architectures. Excessive unrolling and loading to registers works as well, but has the drawback of consuming large amount of registers for architectures requiring a large number of bytes in flight.

Address stability
For the loading strategy we have to consider the address stability of data items as well. Users sometimes rely on the ability to retrieve the index inside an input array from the reference of a loaded element:

transform(par, a, a + n, a, [a,b,c](const T& e) { 
    const auto i = &e – a;     // &e expected to point into global memory
    return e + b[i] + c[i];
});

Such a user-provided function object inhibits any optimization which loads elements from global memory into registers or shared memory before passing them as arguments, thus only allowing prefetching as optimization. Address oblivious function objects can benefit from a larger variety of optimizations (like TMA or pipelined loading to registers.

Further concerns
Furthermore, the computational intensity and shared memory/register consumption of the user provided function object influence the loading strategy. Longer computations seem to require more data in flight. Shared memory is contested by TMA and user-side computation. Register pressure limits unrolling.

Status quo
thrust::transform (CUDA) is currently built on top of cub::DeviceFor::Bulk, which eventually dispatches independently of the uses data types or number of input and output streams. Because cub::DeviceFor::Bulk is index based, the involved input and output data streams are not visible and no tuning based on this information is possible. The situation is similar with cub::DeviceFor::ForEach et al.

Strategy
I propose to add a new CUB algorithm cub::DeviceTransform governing transformations of N input streams into a single output stream (maybe M output streams if use cases arrise) and rebasing thrust::transform on top of it.

Future tasks after merging cub::DeviceTransform

Activity

  1. added
    thrust
    cub
    on Jul 5, 2024
  2. bernhardmgruber commented on Jul 16, 2024

    @bernhardmgruber
    ContributorAuthor

    It turns out the C++ standard does not guarantee address stability of function arguments passed to user-provided callables in the context of parallel algorithms. See:
    * https://eel.is/c++draft/algorithms.parallel#user-1
    * https://eel.is/c++draft/algorithms.parallel#exec-3
    The only exception are for_each and for_each_n:
    * exception for for_each: https://eel.is/c++draft/alg.foreach#9
    * exception for for_each_n: https://eel.is/c++draft/alg.foreach#25
    IIRC from a discussion with @gevtushenko , this is consistent with what Thrust/CUB should promise. However, I could not find any solid hints in our documentation. We may thus break users when changing this behavior who relied on this effect by accident (see also: Hyrum's Law).

  3. moved this from Todo to In Progress in CCCLon Jul 17, 2024
  4. bernhardmgruber commented on Jul 17, 2024

    @bernhardmgruber
    ContributorAuthor

    We discussed address stability again today and concluded the following:

    • Don't break users relying on stable parameter addresses, even if the C++ standard does not give that guarantee.
    • Provide an opt-in in Thrust, so users can communicate they do not require stable addresses
    • On top, try to detect whether users take parameters by value and if they do, allow copying of data.
    • Update our documentation and examples to take parameters by value
    • Provide a dual API in CUB, like cub::DeviceFor, with address-stable and unstable functions.
  5. bernhardmgruber commented on Jul 18, 2024

    @bernhardmgruber
    ContributorAuthor

    Address stability: Because I just encountered it in the tests on my A6000. If we use a kernel serving parameters from shared memory and the user performs pointer arithmetic with a pointer to global memory, the kernel crashes (Release build) and the following error code is reported at the next cudaDeviceSynchronize:

    717 (operation not supported on global/shared address space)
    

    That's at least better than a garbage result and the kernel continuing with wrong data.

  6. ahendriksen commented on Feb 26, 2026

    @ahendriksen
    Contributor

    Sorry for stream-of-consciousness. Have tried a few options to improve code generation.

    It is very difficult to get good code-generation with ublkcp.

    • Using the cp_async_bulk_pred or cp_async_bulk_mask functions below improves
      code generation considerably.
      • Using a branch in C++ using elect_sync is not ideal and results is bad codegen
        • Arithmetic gets moved into the elect_sync branch
        • Therefore ELECT.SYNC must be emitted
        • An extra BRA is emitted
      • Passing in an integer boolean as a predicate results in good codegen
      • Passing a warpmask and puttin the elect_sync + cp.async.bulk in a single assembly code block results in the same codegen.
      • Perhaps we must byte the bullet and provide an overload with a predicate for all uniform instructions in cuda::ptx
      • Getting the LDCUs in the right location is impossible. OCG simply doesn't want to keep the LDCU instructions up and keep the REQs down.
    #include <cstdint> 
    #include <cuda/ptx> 
    
    namespace ptx = cuda::ptx;
    
    template <typename _Tp>
    [[nodiscard]] _CCCL_DEVICE_API static inline _Tp* optimizeSmemPtr(const _Tp* smemGeneric);
    
    template <typename T>
    static inline __device__ T taint(T& val) {
      if constexpr(std::is_same_v<T, float>) {
        asm("" : "+f"(val));
      } else if constexpr(sizeof(val) == 4) {
        asm("" : "+r"(val));
      } else if constexpr(sizeof(val) == 8) {
        asm("" : "+l"(val));
      }
    
      return val;
    }
    
    
    struct Params {
      char* in;
      float* out;
    
      uint32_t tileStrideBytesIn;
      size_t tileStrideOut;
    
      uint32_t tileSizeBytesIn;
    
      bool pFalse;
    };
    
    struct Smem {
      uint64_t bar;
      float     buf[];
    };
    
    __device__ static inline void cp_async_bulk_mask(
      ptx::space_shared_t,
      ptx::space_global_t,
      void* dstMem,
      const void* srcMem,
      const std::uint32_t& size,
      std::uint64_t* smem_bar,
      uint32_t mask)
    {
        asm (
          "{\n"
          ".reg .pred PRED; \n\t"
          // "setp.eq.b32 	PRED, %4, 0;\n"
          "elect.sync _|PRED, %4; \n\t"
          "@PRED cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];\n"
          "}"
          :
          : "r"(ptx::__as_ptr_smem(dstMem)),
            "l"(ptx::__as_ptr_gmem(srcMem)),
            "r"(size),
            "r"(ptx::__as_ptr_smem(smem_bar)),
            "r"(mask)
          : "memory"
        );
    }
    
    __device__ static inline void cp_async_bulk_pred(
      ptx::space_shared_t,
      ptx::space_global_t,
      void* dstMem,
      const void* srcMem,
      const std::uint32_t& size,
      std::uint64_t* smem_bar,
      int pred)
    {
        asm (
          "{\n"
          ".reg .pred PRED; \n\t"
          "setp.eq.b32 	PRED, %4, 1;\n"
          "@PRED cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];\n"
          "}"
          :
          : "r"(ptx::__as_ptr_smem(dstMem)),
            "l"(ptx::__as_ptr_gmem(srcMem)),
            "r"(size),
            "r"(ptx::__as_ptr_smem(smem_bar)),
            "r"(pred)
          : "memory"
        );
    }
    
    template <int strategy>
    __global__ void kernel(const __grid_constant__ Params kp) {
      __shared__ Smem smem_raw;
    
      Smem* smem = optimizeSmemPtr(&smem_raw);
    
      Params p = kp; 
      taint(p.tileSizeBytesIn);
      taint(p.tileStrideBytesIn);
      taint(p.in);
      int tileIdx = taint(blockIdx.x);
      int tid = taint(threadIdx.x);
      int warpIdx = __reduce_min_sync(~0, tid);
    
      // bool isLeaderWarp = __any_sync(~0, threadIdx.x==0);
      bool isLeaderWarp = warpIdx == 0;
    
      if (isLeaderWarp) {
        ptx::mbarrier_init(&smem->bar, 1);
        void * dst = smem->buf;
        void * src = p.in + tileIdx * p.tileStrideBytesIn;
    
        if constexpr(strategy == 0) {
          if (ptx::elect_sync(~0)) {
                ptx::cp_async_bulk(ptx::space_shared, ptx::space_global, dst, src, p.tileSizeBytesIn, &smem->bar);
          }
        } else if constexpr(strategy == 1) {
            int pred = ptx::elect_sync(~0);
            cp_async_bulk_pred(ptx::space_shared, ptx::space_global, dst, src, p.tileSizeBytesIn, &smem->bar, pred);
        } else {
            cp_async_bulk_mask(ptx::space_shared, ptx::space_global, dst, src, p.tileSizeBytesIn, &smem->bar, ~0);
        }
      }
    
      __syncthreads();
      p.out[tileIdx * p.tileStrideOut + tid] = tanh(smem->buf[tid]);
      
    }
    
    // __global__ void kernel_ldg(const Params p) {
    //   int tileIdx = taint(blockIdx.x);
    //   int tid = taint(threadIdx.x);
    //   p.out[tileIdx * p.tileStrideOut + tid] = tanh(*(float*)&p.in[tileIdx * p.tileStrideBytesIn + tid * sizeof(float)]);  
    // }
    
    
    
    template <typename _Tp>
    [[nodiscard]] _CCCL_DEVICE_API static inline _Tp* optimizeSmemPtr(const _Tp* smemGeneric)
    {
      // See https://nvbugspro.nvidia.com/bug/4907996
    
      // 1. Convert to 32-bit shared memory pointer
      uint32_t smem32 = __cvta_generic_to_shared(smemGeneric);
      // 2. Pretend to NVVM that the 32-bit pointer is modified. This is required to avoid NVVM constant
      // propagation from pulling the smem32 definition into loops and branches in subsequent code.
      asm("" : "+r"(smem32));
      // 3. Make a generic pointer to smem that is constructed using `__cvta_shared_to_generic`. This
      // benefits from an
      //    optimization pass in NVVM that performs the following simplification:
      //    __cvta_generic_to_shared(__cvta_shared_to_generic(x))    => x.
      //    In our case, `x` is smem32, which is exactly what we want.
      return reinterpret_cast<_Tp*>(__cvta_shared_to_generic(smem32));
    }
    
    using fn_type = void (*) (const Params kp);
    fn_type global_fn = nullptr;
    
    int main() {
      global_fn = kernel<0>;
      global_fn = kernel<1>;
      global_fn = kernel<2>;
    }
    
  7. ahendriksen commented on Feb 26, 2026

    @ahendriksen
    Contributor

    If we use the __block_size__ attribute on the kernel, we can remove a SHFL.SYNC. Example: https://cuda.godbolt.org/z/6sTP8acKP

    Note: this only works on recent compilers and it appears that not all target architectures are supported.

  8. bernhardmgruber commented on Sep 7, 2026

    @bernhardmgruber
    ContributorAuthor

    I asked claude to try the optimizations proposed by @ahendriksen and it found that the current version of our transform kernel already produces good SASS where the bulk copy is predicated. I didn't dive deep into doing the analysis myself though.

    Adding __block_size__ saved one instruction, a VOTEU.ALL, but it caused a massive regression due to different scheduling of CTAs I believe.

  9. miscco commented on Sep 8, 2026

    @miscco
    Contributor

    Adding __block_size__ saved one instruction, a VOTEU.ALL, but it caused a massive regression due to different scheduling of CTAs I believe.

    Reaching SoL one instruction at a time 🐱

  10. bernhardmgruber commented on Sep 8, 2026

    @bernhardmgruber
    ContributorAuthor

    I moved a few bullet items from this mega issues into independent issues, so we can follow-up later (or never):

    @gonidelis let's finish tuning and then we can complete this effort for now and close the issue.

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

Metadata

Metadata

Labels

cubthrust

Type

No type

Projects

  • Status
    In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions