Sum reduction

Turning a whole array into one number — and four rounds of fixing the ways that goes wrong.

What you'll learn
  • How a tree reduction turns a serial sum into a logarithmic one
  • What warp divergence and shared-memory bank conflicts actually cost
  • Why having threads do more work each can make a kernel faster

Summing an array feels sequential: each step needs the running total from the one before. Parallelising it needs a different shape — a tree. Pair up the elements and add them, then pair up the results, and keep halving until one value remains. That is \(\log_2 n\) rounds instead of \(n\).

This lesson is the most instructive in the course, because the first working version is also the slowest, and each fix targets a different hardware behaviour.

Round 1: the obvious tree, and warp divergence

__global__ void sum_reduction(int *v, int *v_r) {
    __shared__ int partial_sum[SHMEM_SIZE];

    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    partial_sum[threadIdx.x] = v[tid];
    __syncthreads();

    for (int s = 1; s < blockDim.x; s *= 2) {
        if (threadIdx.x % (s * 2) == 0) {       // PROBLEM: half the threads idle
            partial_sum[threadIdx.x] += partial_sum[threadIdx.x + s];
        }
        __syncthreads();
    }

    if (threadIdx.x == 0) v_r[blockIdx.x] = partial_sum[0];
}

This is correct, and it is slow for a reason that is invisible in the source.

GPU threads execute in groups of 32 called warps, and a warp has one shared program counter: all 32 threads run the same instruction at the same time. When threadIdx.x % (s * 2) == 0 is true for only some threads in a warp, the hardware cannot run two paths at once — it runs the if body with the other threads disabled, then carries on. This is warp divergence, and it means a warp where only one thread is active costs the same as one where all 32 are.

In the very first iteration, only even-numbered threads work. Half of every warp is switched off, and it gets worse each round.

Round 2 and 3: keep the active threads together

The fix is to stop asking “is my index a multiple of 2s?” and instead have the first s threads do the work, reading from a partner s positions away. Then active threads are contiguous, so whole warps retire cleanly instead of every warp running at half strength.

That change alone introduces a second, subtler problem. Shared memory is divided into 32 banks, and two threads in a warp touching different addresses in the same bank are serialised — a bank conflict. Choosing a stride that walks threads across banks rather than down one removes it.

Round 4: stop launching idle threads at all

Look again at the first iteration of any of these kernels: every thread loads one element, then immediately half of them have nothing to do. So let each thread load two elements and add them before the loop even starts.

__global__ void sum_reduction(int *v, int *v_r) {
    __shared__ int partial_sum[SHMEM_SIZE];
    int tid = blockIdx.x * blockDim.x + threadIdx.x;

    // Each block now covers twice as much data
    int i = blockIdx.x * (blockDim.x * 2) + threadIdx.x;

    // Do the first add while loading, instead of storing raw elements
    partial_sum[threadIdx.x] = v[tid] + v[i + blockDim.x];
    __syncthreads();

    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (threadIdx.x < s) {                  // active threads stay contiguous
            partial_sum[threadIdx.x] += partial_sum[threadIdx.x + s];
        }
        __syncthreads();
    }

    if (threadIdx.x == 0) v_r[blockIdx.x] = partial_sum[0];
}

Two things changed. The loop now counts down (s = blockDim.x / 2; s >>= 1) with the condition threadIdx.x < s, which keeps the working threads packed at the start of the block. And the whole first round of the tree happens during the load, so the kernel needs half as many blocks for the same array.

Switch between the two kernels. Both take four rounds, but watch the orange warp bands: the diverged version keeps every warp busy with almost no useful work.
Both kernels do eight rounds, but the diverged one keeps all eight warps busy for five of them: 47 warp-rounds against 12.

The full progression

Version What it fixes
01sum_reduction_diverged.cu baseline — correct, badly divergent
02sum_reduction_bank_conflicts.cu removes divergence, still conflicts on banks
03sum_reduction_no_conflicts.cu fixes the bank conflicts
04sum_reduction_reduce_idle_threads.cu each thread loads and adds two elements
05sum_reduction_device_function.cu warp-level warpReduce, no syncing in the last warp
06sum_reduction_coperative_groups.cu modern cooperative-groups API, vectorised int4 loads

The last warp is a special case worth knowing: once only 32 threads remain, they are inside a single warp and therefore already synchronised by the hardware, so __syncthreads() becomes pure overhead. That is what the warpReduce device function in version 5 exploits, and it is the fastest of the set.

Version 6 is slightly slower than version 5 but much easier to read — and in production you would reach for CUB or Thrust, which ship tuned reductions with the toolkit.

Run it

cd cuda_from_scratch/03sum_reduction
nvcc -o reduce_diverged 01sum_reduction_diverged.cu && ./reduce_diverged
nvcc -o reduce_fast 05sum_reduction_device_function.cu && ./reduce_fast

Try it yourself. Profile versions 1 and 4 with nsys profile --stats=true ./reduce and compare the achieved occupancy and kernel duration. Then work out why version 4 needs its grid launched with half as many blocks — and what happens to the answer if you forget to halve it.

View source on GitHub →