L2 Intermediate · Module 5: Parallel patterns

5.4Prefix sum (scan)

A scan gives every element the sum of everything before it. It looks inherently serial, but it parallelizes in log2(n) steps, and it is the tool that turns "each thread decides how much to write" into "each thread knows where to write". This chapter steps through the two classic algorithms, then measures what really decides a scan's speed on a GPU, the number of passes over memory.

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

By the end you will be able to

  • ✓Define inclusive and exclusive scan, and compute them by hand
  • ✓Trace Hillis–Steele and Blelloch scans, and compare their steps and total work
  • ✓Build a scan of any length from block scans, and count its memory traffic
  • ✓Use scan for stream compaction, and recognize it in top-p sampling, MoE routing and cu_seqlens

A prefix sum, or scan, replaces each element with the sum of all the elements up to it:

input31704
inclusive scan34111115
exclusive scan0341111

The exclusive scan is the inclusive one shifted right by one, starting at 0 (the identity). Any associative operator works, not only +.

On a CPU, a scan is a loop where each step depends on the one before. It looks like the least parallel thing possible. It isn’t.

Why it matters

A scan answers the question “where do I write?”. Suppose each thread produces a variable number of outputs: some keep their element and some drop it, or some request 3 KV blocks and some request 7. An exclusive scan of the counts gives each thread its starting offset in a packed output array, with no atomics and in a deterministic order.

In inference this shows up as:

  • cu_seqlens. Variable-length batches pack sequences end to end; the start of sequence ii is the exclusive scan of the lengths (9.4).
  • Top-p sampling. Sort the probabilities, take the inclusive scan, and keep tokens until it passes pp (11.1).
  • MoE routing. Count the tokens sent to each expert, then scan the counts to get each expert’s slice of a packed buffer (14.5).
  • Stream compaction. Keep only the elements that pass a test, packed together. The lab does this at the end.

Two parallel algorithms

Algorithm
input3170416325041261press next → to run the first parallel step— read — write
parallel steps
0 / 4
additions so far
0
additions, total
49
serial loop
15 steps, 15 adds

Every element adds the one "offset" to its left; the offset doubles each step. Few steps (log₂ n), but n − offset additions in each: about n·log₂ n in total. Good when there are more threads than work, as inside a warp.

fig. 5.4A scan of 16 elements, one parallel step at a time. Amber cells are read, blue cells are written. Compare how many parallel steps and how many additions each algorithm needs, against the 15 of each for a serial loop.

Hillis–Steele (1986) adds, at step kk, the element 2k2^k places to the left. After log⁡2n\log_2 n steps every element has seen everything before it. It uses nlog⁡2nn \log_2 n additions: more total work than the serial loop, but in the fewest parallel steps.

Blelloch (1990) is work-efficient. It runs an up-sweep (a reduction tree that keeps its partial sums), sets the root to zero, then runs a down-sweep that passes prefixes back down the tree. It uses about 2n2n additions in 2log⁡2n2 \log_2 n steps, and produces an exclusive scan.

Inside a warp, Hillis–Steele wins: the 32 lanes exist anyway, so the extra additions are free, and a shuffle does each step in one instruction:

labs/m05/5.4/scan.cu
__device__ int warp_inclusive_scan(int v) {
int lane = threadIdx.x % 32;
for (int off = 1; off < 32; off *= 2) {
int up = __shfl_up_sync(0xffffffff, v, off); // value from lane - off
if (lane >= off) v += up;
}
return v;
}

A block scan is then built the same way as the block reduction in 5.2: scan each warp, scan the warp totals, and add each warp’s offset back.

Scanning 16 million elements

One block can only scan one tile, so a long array is scanned in three phases:

  1. Scan each tile, and write each tile’s total to a small sums array.
  2. Scan sums. It is n/tilen / \text{tile} long, so recurse with the same code.
  3. Add the scanned total of all earlier tiles to every element of each tile.

The lab runs this with four different phase-1 block scans:

output (RTX 3050 6GB Laptop)
Inclusive scan of 16777216 ints (67 MB in, 67 MB out):
phase 1 kernel tile time GB/s
hillis-steele 512 2.371 ms 56.6 PASS
blelloch 512 2.431 ms 55.2 PASS
warp shuffle 512 2.180 ms 61.6 PASS
4 per thread 2048 2.193 ms 61.2 PASS
reduce-then-scan 2048 1.626 ms 82.6 PASS
cudaMemcpy D2D 1.097 ms 122.4 (the floor: read once, write once)

The four block algorithms land within 10% of each other, all at twice the copy time. Counting memory traffic shows why: phase 1 reads the input and writes the output, and phase 3 reads the output and writes it again. That is 4 trips through memory, against 2 for the copy. The block algorithm barely matters, because memory traffic sets the time.

Reduce-then-scan reorganizes the phases. Phase 1 only reads each tile and writes its total. Phase 2 scans the totals. Phase 3 reads the input again, scans the tile, adds the offset and writes the result once. That makes 3 trips instead of 4, and the measured time drops by exactly that ratio, from 2.18 ms to 1.63 ms.

Stream compaction

Keep the elements with x > 2, packed together and in their original order:

flags[i] = x[i] > 2; // 1. 0 or 1 per element
pos = inclusive_scan(flags); // 2. pos[i] = how many kept elements up to and including i
if (flags[i]) out[pos[i] - 1] = x[i]; // 3. scatter each kept element to its slot
output
Compaction (keep x > 2): kept 4195183 of 16777216 in 4.900 ms PASS

At 4.9 ms this is slow: three separate kernels, a full array of flags written and read back, and a scan that makes three trips of its own. A fused version computes the flags while loading the tile and scatters while writing it, which brings it close to the cost of one scan.

Lab: four scans and a compaction 🔴

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

Sources

Check your understanding

0 / 4 answered
  1. 1.What is the exclusive scan of [2, 5, 1, 3]?

  2. 2.Hillis–Steele uses about n log n additions, Blelloch about 2n. Why use Hillis–Steele inside a warp?

  3. 3.The three-phase scan took twice as long as a copy. Why?

  4. 4.Each of 1,000 threads produces between 0 and 5 outputs. How does a thread find where to write them in a packed array?