Simulate a work-efficient parallel prefix sum
Why it matters Scans are the building block of GPU top-p sampling, radix sort and Mamba's parallel recurrence.
GPUs compute prefix sums with the Blelloch scan: an up-sweep that builds partial sums in a tree, then a down-sweep that distributes them.
Write blelloch_scan(x). len(x) is a power of 2. Up-sweep: for d = 1, 2, 4, ...: for i in range(2d - 1, n, 2d): a[i] += a[i - d]. Set a[n - 1] = 0. Down-sweep: for d = n/2, ..., 1: for i in range(2d - 1, n, 2d): t = a[i - d]; a[i - d] = a[i]; a[i] += t. Return (exclusive_scan, steps) where steps is the number of level loops executed (up plus down).
def blelloch_scan(x)Example
blelloch_scan([3, 1, 7, 0]) is ([0, 3, 4, 11], 4).
Understand the idea
An exclusive prefix sum gives, at each position, the sum of everything before it. The Blelloch scan does it in two tree passes: an up-sweep builds partial sums so the last slot holds the total; then that slot is set to 0 and a down-sweep pushes sums back down, swapping and adding. Worked example: x = [2, 5, 1, 4]. Up-sweep d = 1: a[1] = 7, a[3] = 5, giving [2, 7, 1, 5]; d = 2: a[3] = 12, giving [2, 7, 1, 12]. Set a[3] = 0. Down-sweep d = 2: t = a[1] = 7, a[1] = 0, a[3] = 0 + 7 = 7, giving [2, 0, 1, 7]. d = 1: at i = 1, t = 2, a[0] = 0, a[1] = 2; at i = 3, t = 1, a[2] = 7, a[3] = 8. Result [0, 2, 7, 8], 4 level loops. Rule: up-sweep for d = 1, 2, 4 while d < n, a[i] += a[i - d] at i = 2d - 1 stepping by 2d; zero a[n - 1]; down-sweep d from n/2 to 1. Each level loop is one step. Used in: stream compaction and radix sort.
Shapes and data flow
n = 8: up-sweep levels d = 1, 2, 4 (tree of partial sums) set root to 0 down-sweep d = 4, 2, 1 -> exclusive prefix sums