5 The Reduction pattern
Reduction is the pattern for turning many values into one, and the chapter introduces it through a simple class-average story before generalizing to sums, maxima, minima, products, and counts. The key requirement is associativity, which lets the work be regrouped into a tree rather than forced into a single serial chain, and each operation also needs an identity element so extra threads can safely contribute padding when there is no real data left. This makes reduction a foundational building block in GPU code and in broader data-processing systems.
The chapter then shows why the obvious parallel approach fails: if every thread updates the same accumulator directly, the code suffers from race conditions because read-modify-write is not automatically safe. Using an atomic operation fixes correctness, but it serializes all updates through one shared location, which destroys most of the benefit of parallelism. The performance lesson is that correctness alone is not enough; the algorithm must also avoid funneling all work through a single counter.
The solution is tree reduction inside each block, using shared memory as a fast on-chip workspace and __syncthreads() as the barrier that keeps rounds in lockstep. Threads first load data into shared memory, then repeatedly combine pairs at shrinking strides until one subtotal remains, and finally one thread per block uses an atomic update to merge that subtotal into global memory. The chapter closes by showing how the same structure applies to other operations, how floating-point reductions can vary slightly because order matters numerically, and how common mistakes usually trace back to missing synchronization, uninitialized results, mismatched shared-memory size, or forgetting to use an atomic across blocks.
A knockout tournament halves the number of teams every round until one champion remains; tree reduction does the same with numbers, halving the active elements each round (stride 4 → 2 → 1) until a single sum is left. Eight numbers collapse to one in just three rounds, instead of the seven steps a sequential sum would take.
The GPU memory hierarchy. Registers are the fastest; each thread has its own dedicated registers. All the threads in one block can read and write to the same shared memory. Global memory is reachable by every thread across all blocks, but it lives off-chip, which makes it by far the slowest.
The tree reduction kernel in three acts: load, reduce, write back. Act 1 copies global memory into shared memory so the fast reduction can happen on-chip. Act 2 runs three rounds of stride-based addition (stride 4, 2, then 1), collapsing eight values down to one. Act 3 uses atomicAdd to safely write the block's result (36) back to global memory.
Act 1 (Load): staging data in shared memory for fast access. Each thread reads one value from slow global memory into its private register, then writes it to shared memory, a two-step relay that happens in parallel across all eight threads simultaneously. Once sdata is populated, the reduction can run entirely on-chip without touching global memory again.
Act 2 (Reduce): three rounds of pairwise addition in shared memory. Each round, active threads read two values from sdata into registers, add them, and write the result back, halving the number of active threads each time (4 → 2 → 1). By the end of Round 3, the block's total sum (36) sits in sdata[0], ready to be written back to global memory.
Act 3 (Write back): one thread per block delivers the result. Thread 0 reads the block's sum from sdata[0] into a register, while T1–T7 sit idle. It then uses atomicAdd to safely add that value to the global result, necessary because multiple blocks may be writing to the same location simultaneously.
atomicAdd guarantees the right answer, regardless of which block goes first. Block 0 and Block 1 both race to update the same result in global memory with their partial sums (36 and 24). Whether Block 0 arrives first (0 → 36 → 60) or Block 1 does (0 → 24 → 60), the final sum lands on 60; atomicAdd serializes the updates so no contribution is ever lost.
Why atomicAdd is safe: read-modify-write as one indivisible step. When two blocks target the same address, the hardware serializes their requests: while one block's three steps (read → modify → write) run, the others wait, and the next one begins by reading the updated value, so no update is lost. When blocks target different addresses, their read-modify-writes run fully in parallel. The order in which same-address requests are served is unpredictable, but the final sum is always correct.
End-to-end reduction of 16M floats on a Tesla T4 (transfers included). CPU 52.1 ms; GPU-atomic 47.5 ms (1.10× over CPU); GPU-tree 14.8 ms (3.52×). The timings are end-to-end on purpose; the comparison to watch is the atomic bar sitting almost level with the CPU bar. A direct GPU port of the sequential loop barely beats the CPU. Measured on a Google Colab Tesla T4 with CUDA 12.8 (nvcc -O3), 2²⁴ single-precision values, 256 threads per block; the text explains what each timing covers. Other hardware will give different numbers.
Summary
- The Reduction pattern combines many values into one using an associative operation.
- Naive parallel reduction creates race conditions and gives unpredictable, wrong results.
- Tree-based reduction takes O(log n) rounds instead of the O(n) steps of a sequential sum, enabling large speedups when enough threads are available.
- Shared memory is a fast, per-block scratch space for thread communication.
- Padding out-of-bounds threads with the identity element keeps partial blocks correct, and the halving stride needs a power-of-2 block size.
- __syncthreads() is a barrier that synchronizes all threads in a block; skipping one is the most common reduction bug.
- Atomic operations prevent race conditions when combining results across blocks.
- Structure matters more than hardware: on 16M floats the atomic-per-element version only ties the CPU, while the tree reduction runs 3.52× faster.
- The same tree code works for other associative, commutative operations: swap the operator and its identity element to get max, min, product, or count, provided the type and the final atomic (or a second pass) support that operation.
- NumPy’s sum(), PyTorch’s max(), and SQL’s SUM() are all examples of the Reduction pattern at work.
- The same idea shows up across the parallel family: MPI_Allreduce combines partial sums across a cluster, and OpenMP’s reduction clause does it on a multicore CPU.
Grokking GPU Programming ebook for free