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).
def butterfly_reduce(vals, op="sum")Example
butterfly_reduce([1, 2, 3, 4]) gives ([10, 10, 10, 10], 2).
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. Worked example: 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]. Rule: 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.