L2 Intermediate · Module 5: Parallel patterns

5.1Reduction trees

A reduction turns many values into one. On a GPU it becomes a tree of pairwise combines, and the details of that tree decide which threads idle and how much memory traffic is in flight. This chapter walks through five versions of a sum and measures each one, including the textbook optimizations that no longer matter on modern hardware.

GPU required (Colab or a rented GPU)✦ Interactive~25 min

By the end you will be able to

  • ✓Explain why a parallel reduction takes log2(n) steps, and what it needs from the operator
  • ✓Compare interleaved and sequential addressing, and say what each costs
  • ✓Explain why giving each thread more elements matters more than polishing the tree
  • ✓Recognize reductions inside LLM kernels: softmax, norms, attention and sampling

A reduction combines many values into one: a sum, a max, a count. It shows up constantly in LLM inference. Every softmax needs the max and the sum of a row. Every RMSNorm needs a sum of squares. Every attention score is a dot product, which is a sum. And sampling has to find the largest logit, or the top k of them.

A CPU does it with a loop: for (i...) s += x[i]. That is nn steps, each depending on the last. A GPU needs a different shape.

The tree

Add pairs, then pairs of pairs. 256 values become 128 partial sums, then 64, and so on: one value after log⁡2256=8\log_2 256 = 8 steps. The total number of additions is still n−1n - 1, the same as the loop, so no extra work is done. The work just runs side by side.

The tree changes the order of operations, so it needs an associative operator: (a⊕b)⊕c=a⊕(b⊕c)(a \oplus b) \oplus c = a \oplus (b \oplus c). Sum, max, min, AND and OR all are. Floating-point addition only nearly is, so a tree sum can differ from a loop sum in the last bits (see 4.5).

A large array has many blocks, and __syncthreads only works within one block (4.4). So the usual plan has two passes: each block reduces its slice to one partial sum, then a second launch reduces the partials.

Three ways to lay out the tree

The tree can be mapped onto threads in more than one way. Step through each layout below and watch which threads and warps do the work.

Kernel

if (tid % (2*s) == 0) s[tid] += s[tid + s];

step 1 of 5 · s = 1
shared memory before this step314159265358979323846264338327954151149868313816712353124821046311397145afterthreads 0–31, drawn as 4 warps of 8warp 0: issueswarp 1: issueswarp 2: issueswarp 3: issues
threads adding
16 / 32
warps issuing
4 / 4
lanes used in busy warps
50%
warp-steps, whole sum
15

Working threads are scattered: every warp keeps a few busy lanes, so every warp has to issue the instruction while most of its lanes sit idle.

fig. 5.1One step of a 32-element block reduction. Amber cells are read, blue cells are written. Below: which threads add at this step, grouped into warps (drawn with 8 lanes so they fit; real warps have 32). A warp with even one busy lane has to issue the instruction.
  • v1, interleaved and divergent. Thread tid works only if tid % (2*s) == 0. Busy threads end up scattered through every warp, so all warps keep issuing while most of their lanes sit idle (2.4). The % is also slow.
  • v2, interleaved and compact. Pair number tid is handled by thread tid, so busy threads are packed together and whole warps retire. But thread tid now touches address 2*s*tid, and neighbouring lanes hit the same shared-memory banks: the cost moves from divergence to bank conflicts (6.4).
  • v3, sequential addressing. Fold the top half onto the bottom: if (tid < s) s[tid] += s[tid + s]. Busy threads are contiguous and so are their addresses. This is the kernel from 4.4.

Then: stop wasting the threads

Even v3 wastes threads. Half of them are idle from the very first step, and each thread loads only one element. Two more changes:

  • v4, add during the load. Each thread loads two elements and adds them before the tree starts. That needs half as many blocks to cover the array.
  • v5, grid-stride + float4. Launch only enough blocks to fill the GPU (here 8 per SM) and let each thread walk the array with a grid-stride loop (4.2), reading 16 bytes at a time and keeping a running sum in a register. The tree then runs once per block at the very end, instead of once every 256 elements.
// labs/m05/5.1/reduction.cu, v5
float v = 0.0f;
const float4* in4 = reinterpret_cast<const float4*>(in);
for (int i = blockIdx.x * BLOCK + tid; i < n / 4; i += gridDim.x * BLOCK) {
float4 q = in4[i];
v += (q.x + q.y) + (q.z + q.w); // most of the work: a private, serial sum
}
s[tid] = v; // then one shared-memory tree, as in v3
__syncthreads();
for (int stride = BLOCK / 2; stride > 0; stride /= 2) {
if (tid < stride) s[tid] += s[tid + stride];
__syncthreads();
}

This mixes the two shapes: a serial loop inside each thread, where it is cheapest, and a parallel tree only across threads. Almost every fast reduction kernel works this way.

Measured

A sum reads each byte once and does one addition per 4 bytes, an intensity of 0.25 FLOP/byte. It is completely memory-bound (3.2), so the goal is to read memory as fast as the GPU can.

output (RTX 3050 6GB Laptop)
Sum of 33554432 floats (134 MB), two passes:
kernel time GB/s result
v1 interleaved, divergent 2.168 ms 61.9 33554430 PASS
v2 interleaved, compact 2.135 ms 62.9 33554430 PASS
v3 sequential addressing 2.136 ms 62.8 33554430 PASS
v4 add during load 1.080 ms 124.2 33554430 PASS
v5 grid-stride + float4 1.053 ms 127.5 33554430 PASS
CPU (double) 33554430
cudaMemcpy D2D of the same array: 122.7 GB/s (read + write)

This is not the textbook result. In the classic version of this exercise (Mark Harris’s 2007 slides, on a G80 GPU), each change to the tree gave a large speedup. Here v1, v2 and v3 run at the same speed: across repeated runs they trade places between 60 and 80 GB/s. On a modern GPU the warp scheduler hides divergence and bank conflicts in such a short tree, as long as other warps have loads to issue.

What does matter is bytes in flight. In v1–v3 every block loads 1 KB and then spends 8 barrier-separated steps in the tree, issuing no loads at all. Giving each thread a second element (v4) doubles the rate at once, and v5 reaches 127 GB/s, as fast as a device-to-device copy in the same run (123 GB/s, counting its read and its write). That was the ceiling for this run. The laptop’s memory was below its top clock, as often happens on battery or when hot. Rerun later with the memory at full clock, the unchanged v5 kernel reached 162 GB/s, close to the 168 GB/s peak.

Where reductions hide in an LLM

KernelReductionOver
Softmax (5.7)max, then sum of expeach row of scores or logits
RMSNorm / LayerNorm (8.1)sum of squares (and mean)each token’s hidden vector
Attention (8.4)dot products, then the softmax reductionseach query against all keys
Greedy and top-k sampling (11.1)argmax, top-keach row of logits, over ~128 K vocabulary entries
Split-K / FlashDecoding (9.5)combine partial results from several blocksone row split across blocks

Their rows are short (a few thousand elements) and there are many of them, so the usual layout is one block, or one warp, per row. The tree inside that block then runs very often, and making it cheap is the subject of the next chapter.

Lab: five reductions 🔴

Terminal window
cd labs/m05/5.1 && nvcc -O2 -arch=native reduction.cu -o reduction && ./reduction

Sources

Check your understanding

0 / 4 answered
  1. 1.A block reduces 1,024 values with a tree. How many parallel steps does that take?

  2. 2.Why can a tree reduction compute a max but not, in general, a mean of means?

  3. 3.In the lab, v1, v2 and v3 ran at about the same speed, and v4 was twice as fast. What does that say?

  4. 4.v5 launches only ~8 blocks per SM, however large the array. How does it cover all the data?