Simulate a parallel tree reduction

This is a NumPy simulation of how a CUDA block sums an array, not real GPU code.

A block sums n values in log2(n) rounds. In each round with stride s (starting at n / 2 and halving), thread i < s does a[i] += a[i + s]. After the last round a[0] holds the sum.

Write tree_reduce(values) for a length that is a power of 2. Return (total, rounds) where rounds is a list of the array state after each round (as lists of floats). Each round must read only values from the previous round, as real threads do between barriers.

Signaturedef tree_reduce(values)

Understand the idea

A GPU block sums an array in parallel by pairing values up in rounds. In each round with stride s, thread i (for i < s) adds a[i + s] into a[i]. The stride halves each round, so n values need only log2(n) rounds. Each round must read only the values from the previous round, as real threads wait at a barrier. Like a knockout tournament where pairs merge until one winner holds the total. Worked example: [1, 2, 3, 4, 5, 6, 7, 8]. Round s = 4: a[0..3] become 1+5, 2+6, 3+7, 4+8 = [6, 8, 10, 12], rest unchanged, giving [6, 8, 10, 12, 5, 6, 7, 8]. Round s = 2: [16, 20, 10, 12, 5, 6, 7, 8]. Round s = 1: a[0] = 36. Total 36 after 3 rounds. Rule: for s = n/2, n/4, ..., 1: new[i] = old[i] + old[i + s] for i < s, others copied; record each state. Keeping active threads contiguous (0 to s - 1) avoids warp divergence. Sum, max and softmax kernels use this pattern.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: 8 valuestree_reduce([1, 2, 3, 4, 5, 6, 7, 8])
  • Sample 2: 2 valuestree_reduce([5, -2])
  • Test 3: 16 values totaltree_reduce(list(range(16)))[0]