Find the argmax with a parallel tree reduction and lowest-index ties

Why it matters Greedy decoding and top-1 sampling kernels must match the CPU rule of lowest index on ties, or outputs differ between devices.

Greedy decoding needs the argmax over the vocabulary, and a GPU computes it with a tree reduction over (value, index) pairs. With a strided tree, the slot on the left does not always hold the lower index, so ties must compare indices explicitly.

Write tree_argmax(vals). Pad vals to the next power of two with (-inf, index n + k) pairs. Then for stride = size/2, size/4, ..., 1: for every i < stride, slot i becomes the better of slot i and slot i + stride, where better means the larger value, or the lower index if the values are equal. Return (best value, best index, number of steps). For an empty input raise ValueError.

Signaturedef tree_argmax(vals)

Example

tree_argmax([1, 5, 2, 5, 0, 5]) gives (5.0, 1, 3).

Understand the idea

A tree argmax is a knockout tournament. In each round, players pair up and the winner moves on, until one champion is left. Equal scores need a fair rule, and the rule here is that the smaller index wins. Worked example: [1, 5, 2, 5, 0, 5] padded to 8. Stride 4: slot 0 compares index 0 (1) with 4 (0), slot 1 compares 1 (5) with 5 (5): tie, index 1 stays. Slot 2 compares index 2 with 6 (padding), slot 3 compares 3 (5) with 7 (padding). Stride 2: slot 1 holds index 1 and slot 3 holds index 3, both 5, so index 1 wins. Final answer (5, 1) after 3 steps. Rule: keep the larger value; on a tie keep the smaller stored index. In a strided tree the slot number does not tell you the index, so store it.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletree_argmax([1, 5, 2, 5, 0, 5])
  • Sample 2: tie across halvestree_argmax([0, 0, 0, 0, 3, 0, 3, 3])