672. 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.
def tree_reduce(values)Example 1
Input: values = [1, 2, 3, 4, 5, 6, 7, 8]
Output: (36.0, [[6.0, 8.0, 10.0, 12.0, 5.0, 6.0, 7.0, 8.0], [16.0, 20.0, 10.0, 12.0, 5.0, 6.0, 7.0, 8.0], [36.0, 20.0, 10.0, 12.0, 5.0, 6.0, 7.0, 8.0]])
Example 2
Input: values = [5, -2]
Output: (3.0, [[3.0, -2.0]])
Example 3
Input: tree_reduce(list(range(16)))[0]
Output: 120.0
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Copy the array.
Hint 2
While s >= 1: a[:s] = a[:s] + a[s:2s]; record a copy; s //= 2.
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.
[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.
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.
Topics
Companies1
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
From public interview reports and guides. Not affiliated with or endorsed by these companies.