Overview

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.
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 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.
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 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 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.
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.
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.
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.
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.

FAQ

What is the reduction pattern in GPU programming?Reduction is a parallel pattern that combines many input values into one output value, such as a sum, maximum, minimum, product, or count. It works only when the combine operation is associative, so the values can be regrouped safely into a tree of partial results.
Why does the naive approach of having every thread add to one shared variable fail?It fails because multiple threads can read, modify, and write the same result at the same time. This creates a race condition, so some updates get overwritten and the final answer becomes incorrect or inconsistent.
What is a race condition in the context of reduction?A race condition happens when two or more threads access and update the same memory location without proper synchronization. In reduction, this usually means one thread’s update can overwrite another thread’s update, causing lost contributions.
Why is tree reduction faster than a sequential loop?Tree reduction combines values in rounds, halving the number of active elements each round. That reduces the number of sequential steps from n to about log2(n), allowing many additions to happen in parallel.
What role does shared memory play in tree reduction?Shared memory lets threads in the same block quickly exchange intermediate values. It is much faster than global memory and is used as the workspace where the block-level reduction happens.
Why do we need __syncthreads() inside a reduction kernel?__syncthreads() makes all threads in a block wait until everyone has finished the current round before starting the next one. Without it, some threads may read values that other threads have not written yet, producing wrong results.
Why is atomicAdd used at the end of the reduction kernel?Each block computes a partial sum independently, but all blocks must add their partial sums to the same global result. atomicAdd makes that final update indivisible, preventing blocks from overwriting each other’s contributions.
Why must the identity element be used for out-of-bounds threads?The identity element is a safe placeholder that does not change the result. For sum it is 0, for max it is INT_MIN, and for min it is INT_MAX, so extra threads can load a neutral value without affecting the reduction.
What changes are needed to turn a sum reduction into a max reduction?Inside the block-level tree, replace addition with max(), and initialize padded or empty values with INT_MIN. For the final global combine, use atomicMax instead of atomicAdd.
What are the most common mistakes in reduction kernels?The main mistakes are forgetting __syncthreads(), forgetting to initialize the result, using a regular add instead of an atomic for cross-block updates, and making the shared memory size disagree with the block size. Any of these can produce wrong answers, sometimes only on some runs.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Grokking GPU Programming Grokking GPU Programming ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Grokking GPU Programming Grokking GPU Programming ebook for free