682. Reduce a warp with butterfly XOR shuffles
Why it matters Warp shuffle reductions are inside every softmax, layernorm and attention kernel because they avoid shared memory entirely.
Inside a warp, threads can read each other's registers with shuffles. In a butterfly (XOR) reduction, at each step every lane l reads the value of lane l ^ offset and combines it with its own, for offset = w/2, w/4, ..., 1. After log2(w) steps every lane holds the full result.
Write butterfly_reduce(vals, op="sum"). vals has length w, a power of two. All lanes update at the same time each step: new[l] = combine(old[l], old[l ^ offset]) where combine is + for "sum" and max for "max". Return (final values as a float array, number of steps).
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def butterfly_reduce(vals, op="sum")Example 1
Input: butterfly_reduce([1, 2, 3, 4])
Output: ([10, 10, 10, 10], 2)
Example 2
Input: vals = [3, -1, 7, 2, 0, 7, 5, 1], op = 'max'
Output: ([7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0], 3)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Read the whole old array before writing any new value in a step.
Hint 2
Use lanes ^ offset to get partner indices for all lanes at once.
Hint 3
Gather the partners before combining.
Hint 4
Halve the offset each step and count the steps.
Common mistakes
- Updating in place so partners see new values.
- Using shift-down instead of XOR and expecting every lane to have the result.
- Forgetting that w must be a power of two.
Understand the idea
A butterfly reduction is like a phone tree where, in every round, each person calls exactly one partner and they both add up what they know. In round one, partners are 2 apart in a group of 4; in round two, 1 apart. After two rounds everyone knows the total.
lanes hold [1, 2, 3, 4]. Offset 2: lane 0 pairs with 2 (1 + 3 = 4), lane 1 with 3 (6), lane 2 with 0 (4), lane 3 with 1 (6), giving [4, 6, 4, 6]. Offset 1: [10, 10, 10, 10].
new[l] = old[l] + old[l XOR offset], offset = w/2 down to 1, all lanes at once
Because every lane ends with the answer, no broadcast is needed afterwards, which is why softmax kernels use it for row max and row sum.
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.