Chip Foundry Services Request Assessment

Cooperative Groups CUDA

Cooperative Groups is a CUDA C++ programming model that makes thread groups explicit objects. A group knows its size and each member's rank, and it provides collective operations such as `sync()`, shuffles, ballots, reductions, and scans. The same code can then synchronize and communicate across a warp, a tile of a warp, a thread block, or (with a cooperative launch) the whole grid, instead of being tied to `__syncthreads()` at block scope.

Cooperative Groups: Nested Thread Scopes Each box is a group object with its own sync() and collectives grid group: this_grid() (cooperative launch, all blocks resident) thread block: this_thread_block() warp (32) tile of 16 shfl, reduce tile of 16 shfl, reduce warp (32) tile of 16 shfl, reduce tile of 16 shfl, reduce thread block: this_thread_block() warp (32) tile of 16 shfl, reduce tile of 16 shfl, reduce warp (32) tile of 16 shfl, reduce tile of 16 shfl, reduce

1. The Group Hierarchy

GroupObtained withSynchronizesNotes
Thread block`cg::this_thread_block()`all threads of one blocksame scope as `__syncthreads()`
Tile (static)`cg::tiled_partition<N>(parent)`N threads, N a power of two up to 32 for warp collectivessize known at compile time, so the compiler can specialize it
Tile (dynamic)`cg::tiled_partition(parent, n)`n threads chosen at run timea generic `thread_group`, with fewer features and less specialization
Coalesced`cg::coalesced_threads()`the threads currently active at that pointuseful inside divergent branches
Grid`cg::this_grid()`every thread of every blockneeds a cooperative launch
Cluster`cg::this_cluster()`blocks of one thread block clusterCUDA 12 and compute capability 9.0 (Hopper) or later

Groups are lightweight values and are passed by reference or by value into device functions. A function that takes a `cg::thread_group` works for any group, and a function templated on a tile type can be specialized for its size. The multi-grid group (several GPUs) is deprecated and should not be used in new code.

The common calls are `size()`, `thread_rank()`, `sync()`, and, for tiles, `meta_group_size()` and `meta_group_rank()` (the number and index of tiles within the parent). Tiles up to 32 also provide `shfl`, `shfl_up`, `shfl_down`, `shfl_xor`, `ballot`, `any`, `all`, and `match_any` and `match_all` (compute capability 7.0 and later). The header `<cooperative_groups/reduce.h>` adds `cg::reduce(group, value, op)` with operators such as `cg::plus<T>` and `cg::greater<T>`, and `<cooperative_groups/scan.h>` adds inclusive and exclusive scans. Newer toolkits also provide `cg::memcpy_async` for asynchronous copies into shared memory.

2. Synchronization Semantics

  • Every member must reach the call. `sync()` on a group is a barrier for all of its members, and a group collective called by only part of the group is a bug. A `block.sync()` inside a divergent branch can hang or produce wrong results.
  • Warp synchronization is not implicit. Since Volta, independent thread scheduling means threads of a warp are not guaranteed to run in lockstep. Code that relied on implicit warp synchronization must use `__syncwarp()` or a tile's `sync()`. The tile shuffle and ballot calls take care of the participation mask, which is one reason to prefer them to raw `__shfl_sync` with hand-built masks.
  • Memory ordering. `sync()` orders memory operations among the participating threads at the scope of the group. A block's `sync()` gives the same guarantees as `__syncthreads()`. A grid's `sync()` makes writes by all blocks before the barrier visible to all blocks after it.
  • Coalesced groups. `coalesced_threads()` captures whichever threads are active at that point, so its size and ranks depend on the branch taken. The group is valid only inside that control flow.

3. Grid-Wide Synchronization

`grid.sync()` lets one kernel contain several phases separated by a global barrier, for example a reduction followed by a normalization. The conditions are strict:
- The kernel must be launched with `cudaLaunchCooperativeKernel` (or the extensible launch API with the cooperative attribute). A normal `<<<>>>` launch with `grid.sync()` is invalid.
- All blocks must be resident on the GPU at once, so the grid size is bounded by the number of blocks per SM (from `cudaOccupancyMaxActiveBlocksPerMultiprocessor`) times the number of SMs. The kernel needs a grid-stride loop, because the grid cannot grow with the data.
- The device must report `cudaDevAttrCooperativeLaunch`. Grid synchronization needs compute capability 6.0 or later. Older toolkits also required relocatable device code (`-rdc=true`) and device linking. Current toolkits do not.
- Other work that occupies SMs (other kernels, MPS partitions) can make a cooperative launch fail or wait.

Lab 2 shows the pattern and the failure mode.

4. Labs

The labs ran on an NVIDIA GeForce RTX 5060 (compute capability 12.0, 30 SMs). The installed `nvcc` (12.4) does not know that architecture, so they were compiled to PTX for `compute_90` with `-gencode arch=compute_90,code=compute_90 -std=c++17` and just-in-time compiled by the driver. Timings are best of 20 runs and indicate order of magnitude on this one device. They are not benchmark results.

Lab 1 compares three block-level sum reductions of 4,194,304 floats: warp shuffle on a tile, the library `cg::reduce`, and a classic shared-memory tree with `__syncthreads()`. The input holds small integers, so float sums are exact.

// Lab 1: block-level reductions with Cooperative Groups, compared with a classic shared-memory tree.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cooperative_groups.h>
#include <cooperative_groups/reduce.h>
namespace cg = cooperative_groups;
#define CK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { printf("CUDA error %s (line %d)
", cudaGetErrorString(e), __LINE__); exit(1); } } while (0)

template <typename Tile>
__device__ float tile_sum(Tile tile, float v) {
  for (int off = tile.size() / 2; off > 0; off /= 2) v += tile.shfl_down(v, off);
  return v;                                              // the full sum is valid in lane 0
}

// (a) warp shuffle + one shared-memory slot per warp
__global__ void reduce_shfl(const float* in, float* out, int n) {
  auto block = cg::this_thread_block();
  auto warp = cg::tiled_partition<32>(block);
  __shared__ float partial[32];
  float v = 0.f;
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) v += in[i];
  v = tile_sum(warp, v);
  if (warp.thread_rank() == 0) partial[warp.meta_group_rank()] = v;
  block.sync();
  if (warp.meta_group_rank() == 0) {
    v = (warp.thread_rank() < warp.meta_group_size()) ? partial[warp.thread_rank()] : 0.f;
    v = tile_sum(warp, v);
    if (warp.thread_rank() == 0) atomicAdd(out, v);
  }
}

// (b) the same with the library collective cg::reduce
__global__ void reduce_cgreduce(const float* in, float* out, int n) {
  auto block = cg::this_thread_block();
  auto warp = cg::tiled_partition<32>(block);
  __shared__ float partial[32];
  float v = 0.f;
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) v += in[i];
  v = cg::reduce(warp, v, cg::plus<float>());
  if (warp.thread_rank() == 0) partial[warp.meta_group_rank()] = v;
  block.sync();
  if (warp.meta_group_rank() == 0) {
    v = (warp.thread_rank() < warp.meta_group_size()) ? partial[warp.thread_rank()] : 0.f;
    v = cg::reduce(warp, v, cg::plus<float>());
    if (warp.thread_rank() == 0) atomicAdd(out, v);
  }
}

// (c) classic shared-memory tree with __syncthreads
__global__ void reduce_smem(const float* in, float* out, int n) {
  extern __shared__ float s[];
  float v = 0.f;
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) v += in[i];
  s[threadIdx.x] = v;
  __syncthreads();
  for (int off = blockDim.x / 2; off > 0; off >>= 1) {
    if (threadIdx.x < off) s[threadIdx.x] += s[threadIdx.x + off];
    __syncthreads();
  }
  if (threadIdx.x == 0) atomicAdd(out, s[0]);
}

int main() {
  const int n = 1 << 22, threads = 256;
  std::vector<float> h(n); double ref = 0;
  for (int i = 0; i < n; i++) { h[i] = 1.f + (i % 3); ref += h[i]; }   // small integers: float sums stay exact below 2^24
  float *d_in, *d_out; CK(cudaMalloc(&d_in, n * sizeof(float))); CK(cudaMalloc(&d_out, sizeof(float)));
  CK(cudaMemcpy(d_in, h.data(), n * sizeof(float), cudaMemcpyHostToDevice));
  int dev; CK(cudaGetDevice(&dev)); cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, dev));
  int blocks = p.multiProcessorCount * 8;
  printf("device %s, compute capability %d.%d, %d SMs; n = %d, reference sum = %.0f
", p.name, p.major, p.minor, p.multiProcessorCount, n, ref);
  cudaEvent_t a, b; cudaEventCreate(&a); cudaEventCreate(&b);
  auto run = [&](const char* name, auto kernel, size_t smem) {
    float res = 0; double best = 1e9;
    for (int rep = 0; rep < 20; rep++) {
      CK(cudaMemset(d_out, 0, sizeof(float)));
      cudaEventRecord(a); kernel<<<blocks, threads, smem>>>(d_in, d_out, n); cudaEventRecord(b);
      CK(cudaEventSynchronize(b)); float ms; cudaEventElapsedTime(&ms, a, b); if (ms < best) best = ms;
    }
    CK(cudaMemcpy(&res, d_out, sizeof(float), cudaMemcpyDeviceToHost));
    printf("%-22s result %.0f  %s   best of 20: %.3f ms (%.0f GB/s)
", name, res, res == (float)ref ? "OK " : "BAD", best, n * 4.0 / (best * 1e6));
  };
  run("warp shfl + smem slot", reduce_shfl, 0);
  run("cg::reduce + smem slot", reduce_cgreduce, 0);
  run("shared-memory tree", reduce_smem, threads * sizeof(float));
  return 0;
}

All three give the exact sum 8,388,607. The best times are 0.019 ms (877 GB/s), 0.020 ms (858 GB/s), and 0.020 ms (838 GB/s). The differences are within noise. At this size the kernel is limited by memory traffic, and the 16 MB input fits in the GPU's L2 cache, which is why the computed bandwidth is above what DRAM alone could supply. A speedup from shuffles over shared memory shows up when the reduction itself dominates, for example for many small independent reductions per warp. It does not appear in a large streaming sum.

Lab 2 normalizes an array in one cooperative kernel: each block adds its partial sum with an atomic, `grid.sync()` waits for all blocks, and then every thread divides by the total.

// Lab 2: a grid-wide barrier. Sum all elements, then divide every element by the sum, in ONE kernel.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cooperative_groups.h>
namespace cg = cooperative_groups;
#define CK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { printf("CUDA error %s (line %d)
", cudaGetErrorString(e), __LINE__); exit(1); } } while (0)

__global__ void normalize_in_one_kernel(float* x, float* sum, int n) {
  auto grid = cg::this_grid();
  auto block = cg::this_thread_block();
  auto warp = cg::tiled_partition<32>(block);
  float v = 0.f;
  for (size_t i = grid.thread_rank(); i < n; i += grid.size()) v += x[i];
  for (int off = 16; off > 0; off /= 2) v += warp.shfl_down(v, off);
  if (warp.thread_rank() == 0) atomicAdd(sum, v);
  grid.sync();                                            // every block has contributed before anyone reads *sum
  float inv = 1.f / *sum;
  for (size_t i = grid.thread_rank(); i < n; i += grid.size()) x[i] *= inv;
}

__global__ void partial_sum(const float* x, float* sum, int n) {
  auto grid = cg::this_grid(); auto warp = cg::tiled_partition<32>(cg::this_thread_block());
  float v = 0.f;
  for (size_t i = grid.thread_rank(); i < n; i += grid.size()) v += x[i];
  for (int off = 16; off > 0; off /= 2) v += warp.shfl_down(v, off);
  if (warp.thread_rank() == 0) atomicAdd(sum, v);
}
__global__ void scale(float* x, const float* sum, int n) {
  float inv = 1.f / *sum;
  for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) x[i] *= inv;
}

int main() {
  int dev = 0; CK(cudaGetDevice(&dev));
  int coop = 0; CK(cudaDeviceGetAttribute(&coop, cudaDevAttrCooperativeLaunch, dev));
  cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, dev));
  printf("cooperative launch supported: %d
", coop);
  const int n = 1 << 22, threads = 256;
  int perSM = 0; CK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&perSM, normalize_in_one_kernel, threads, 0));
  int blocks = perSM * p.multiProcessorCount;
  printf("occupancy: %d blocks/SM x %d SMs = %d blocks (the grid must not exceed this)
", perSM, p.multiProcessorCount, blocks);
  std::vector<float> h(n); double ref = 0;
  for (int i = 0; i < n; i++) { h[i] = 1.f + (i % 3); ref += h[i]; }
  float *d_x, *d_s; CK(cudaMalloc(&d_x, n * 4)); CK(cudaMalloc(&d_s, 4));
  CK(cudaMemcpy(d_x, h.data(), n * 4, cudaMemcpyHostToDevice)); CK(cudaMemset(d_s, 0, 4));
  void* args[] = {&d_x, &d_s, (void*)&n};
  CK(cudaLaunchCooperativeKernel((void*)normalize_in_one_kernel, blocks, threads, args, 0, 0));
  CK(cudaDeviceSynchronize());
  std::vector<float> out(n); CK(cudaMemcpy(out.data(), d_x, n * 4, cudaMemcpyDeviceToHost));
  double s = 0, maxerr = 0;
  for (int i = 0; i < n; i++) { s += out[i]; double e = fabs(out[i] - h[i] / ref); if (e > maxerr) maxerr = e; }
  printf("single cooperative kernel: sum of normalized values = %.6f, max |x_i/sum - reference| = %.2e
", s, maxerr);

  // too-large cooperative grid is rejected instead of deadlocking
  cudaError_t e = cudaLaunchCooperativeKernel((void*)normalize_in_one_kernel, blocks * 4, threads, args, 0, 0);
  printf("launch with 4x too many blocks: %s
", cudaGetErrorString(e)); cudaGetLastError();

  // two-kernel version for comparison
  cudaEvent_t a, b; cudaEventCreate(&a); cudaEventCreate(&b); float ms1 = 1e9, ms2 = 1e9;
  for (int rep = 0; rep < 20; rep++) {
    CK(cudaMemcpy(d_x, h.data(), n * 4, cudaMemcpyHostToDevice)); CK(cudaMemset(d_s, 0, 4));
    cudaEventRecord(a); CK(cudaLaunchCooperativeKernel((void*)normalize_in_one_kernel, blocks, threads, args, 0, 0)); cudaEventRecord(b);
    cudaEventSynchronize(b); float ms; cudaEventElapsedTime(&ms, a, b); if (ms < ms1) ms1 = ms;
    CK(cudaMemcpy(d_x, h.data(), n * 4, cudaMemcpyHostToDevice)); CK(cudaMemset(d_s, 0, 4));
    cudaEventRecord(a); partial_sum<<<blocks, threads>>>(d_x, d_s, n); scale<<<blocks, threads>>>(d_x, d_s, n); cudaEventRecord(b);
    cudaEventSynchronize(b); cudaEventElapsedTime(&ms, a, b); if (ms < ms2) ms2 = ms;
  }
  printf("best of 20: one cooperative kernel %.3f ms, two ordinary kernels %.3f ms
", ms1, ms2);
  return 0;
}

The device supports cooperative launch. The occupancy query gives 6 blocks per SM, so the grid is 180 blocks. The normalized values sum to 1.000000 and the maximum difference from the reference is 1.4×10⁻¹⁴. A launch with four times as many blocks is rejected with "too many blocks in cooperative launch" instead of deadlocking. The single cooperative kernel took 0.041 to 0.042 ms and the two ordinary kernels took 0.040 to 0.041 ms. A global barrier is not faster than a kernel boundary here. Its value is that the phases share registers and shared memory, and that an iterative algorithm can keep its state on the device without relaunching.

Lab 3 uses `coalesced_threads()` for warp-aggregated atomics. Each warp reserves output space with one atomic for all of its threads that take the branch, and it distributes the base address with a shuffle.

// Lab 3: coalesced_threads for warp-aggregated atomics (stream compaction of positive values).
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cooperative_groups.h>
namespace cg = cooperative_groups;
#define CK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { printf("CUDA error %s (line %d)
", cudaGetErrorString(e), __LINE__); exit(1); } } while (0)

__global__ void compact_aggregated(const int* in, int* out, int* counter, int n) {
  int i = blockIdx.x * blockDim.x + threadIdx.x;
  if (i < n && in[i] > 0) {                               // only the threads that take this branch are in the group
    auto g = cg::coalesced_threads();
    int base = 0;
    if (g.thread_rank() == 0) base = atomicAdd(counter, g.size());   // one atomic per warp instead of one per thread
    base = g.shfl(base, 0);
    out[base + g.thread_rank()] = in[i];
  }
}
__global__ void compact_naive(const int* in, int* out, int* counter, int n) {
  int i = blockIdx.x * blockDim.x + threadIdx.x;
  if (i < n && in[i] > 0) out[atomicAdd(counter, 1)] = in[i];
}

int main() {
  const int n = 1 << 24, threads = 256, blocks = (n + threads - 1) / threads;
  std::vector<int> h(n); unsigned s = 12345; long expect = 0;
  for (int i = 0; i < n; i++) { s = s * 1664525u + 1013904223u; h[i] = (int)(s >> 8) % 7 - 3; if (h[i] > 0) expect++; }
  int *d_in, *d_out, *d_cnt; CK(cudaMalloc(&d_in, n * 4)); CK(cudaMalloc(&d_out, n * 4)); CK(cudaMalloc(&d_cnt, 4));
  CK(cudaMemcpy(d_in, h.data(), n * 4, cudaMemcpyHostToDevice));
  cudaEvent_t a, b; cudaEventCreate(&a); cudaEventCreate(&b);
  auto run = [&](const char* name, auto kernel) {
    double best = 1e9; int cnt = 0;
    for (int rep = 0; rep < 20; rep++) {
      CK(cudaMemset(d_cnt, 0, 4)); cudaEventRecord(a); kernel<<<blocks, threads>>>(d_in, d_out, d_cnt, n); cudaEventRecord(b);
      CK(cudaEventSynchronize(b)); float ms; cudaEventElapsedTime(&ms, a, b); if (ms < best) best = ms;
    }
    CK(cudaMemcpy(&cnt, d_cnt, 4, cudaMemcpyDeviceToHost));
    std::vector<int> out(cnt); CK(cudaMemcpy(out.data(), d_out, cnt * 4, cudaMemcpyDeviceToHost));
    std::vector<int> ref; for (int v : h) if (v > 0) ref.push_back(v);
    std::sort(out.begin(), out.end()); std::sort(ref.begin(), ref.end());
    printf("%-22s count %d (expected %ld), same multiset: %s, best of 20: %.3f ms
", name, cnt, expect, out == ref ? "yes" : "NO", best);
  };
  run("coalesced_threads", compact_aggregated);
  run("one atomic per element", compact_naive);
  printf("note: output order within a warp follows lane order; across warps the order is not deterministic
");
  return 0;
}

Both versions compact the 7,187,569 positive values out of 16,777,216 and produce the same set of values. The aggregated version took 0.324 ms and the one-atomic-per-element version took 0.308 ms. Modern compilers already aggregate atomics of this kind, so the explicit version gives no gain on this device with this toolkit. The group version is still useful when the code needs the rank of each active thread, for example to write results in lane order.

Identify the cooperating threads
warp, tile, block, active subset, or whole grid
Pick the group
tiled_partition
static tile size for warp collectives
coalesced_threads
the threads active in a divergent branch
this_thread_block
block barrier and shared memory phases
this_grid
global barrier, needs a cooperative launch
Use group collectives
sync, shfl, ballot, cg::reduce, scan; every member makes the call
If grid sync is used
check cudaDevAttrCooperativeLaunch, size grid from occupancy, grid-stride loops
Measure on the target GPU
compare with __syncthreads or plain kernels, then profile

5. Practical Guidance

  • Start with tiles. Use `tiled_partition<32>` or smaller static tiles for warp collectives, and use `cg::reduce` and the scan functions before writing a hand-rolled shuffle loop.
  • Use grid sync only when the algorithm needs it. Check `cudaDevAttrCooperativeLaunch`, size the grid from the occupancy query, and use grid-stride loops. A kernel boundary is the portable alternative.
  • Keep group arguments uniform. Every member must call the same collectives in the same order.
  • Do not assume a warp size. Take it from `warpSize` or from the tile's `size()`.
  • Measure. Compare against the plain `__syncthreads()` or shuffle version on the target GPU and data size. The labs above show that the benefit depends on what limits the kernel.
  • Profile. Nsight Compute shows warp state, divergence, and barrier stalls.

Key Takeaways

  • Cooperative Groups turns thread groups into objects with `sync()`, shuffles, ballots, reductions, and scans, at warp, tile, block, cluster, or grid scope.
  • Warp threads are not implicitly synchronized on current GPUs. Use a tile's `sync()` or the group collectives.
  • `grid.sync()` needs a cooperative launch with all blocks resident, so size the grid from the occupancy query.
  • On the test GPU all three block reductions matched the exact sum at about 0.02 ms, a single cooperative kernel matched two kernels, and explicit warp-aggregated atomics did not beat the compiler's own aggregation. Measure before expecting a speedup.

References

NVIDIA. CUDA C++ Programming Guide, chapter "Cooperative Groups". https://docs.nvidia.com/cuda/cuda-c-programming-guide/
NVIDIA. CUDA Runtime API: cudaLaunchCooperativeKernel and cudaOccupancyMaxActiveBlocksPerMultiprocessor.
Harris, M., and Perelygin, K. Cooperative Groups: Flexible CUDA Thread Programming. NVIDIA Technical Blog, 2017.
Adinets, A. CUDA Pro Tip: Optimized Filtering with Warp-Aggregated Atomics. NVIDIA Technical Blog, 2014.