Route gradients through a max reduction
Why it matters Max pooling and top-k routing in MoE layers both backpropagate this way.
The gradient of a max goes only to the winning element. With ties, frameworks differ; here split it evenly.
Write max_backward(x, axis, dout). x is an array, dout has the shape of x.max(axis). Return dx with the shape of x: at positions equal to the max along axis, dout divided by the number of tied maxima; zero elsewhere.
def max_backward(x, axis, dout)Example
max_backward([[1, 3, 3]], 1, [6]) gives [[0, 3, 3]].
Understand the idea
The output of a max depends only on the winning element, so in the backward pass only the winner gets gradient and every other element gets zero. When several elements tie for the max, this problem splits the gradient evenly among them, so the total gradient still equals dout. Worked example: x = [[4, 1, 4], [2, 5, 0]], axis 1, dout = [6, 2]. Row 0 has a tie: two 4s, so each gets 6 / 2 = 3, giving [3, 0, 3]. Row 1 has one max, 5, which gets all of 2, giving [0, 2, 0]. Result: [[3, 0, 3], [0, 2, 0]]. Rule: compute the max along the axis with keepdims, build a mask where x equals that max, count the ties along the axis, and set dx = mask * dout_expanded / count, where dout_expanded has the reduced axis restored so it broadcasts. Giving the full dout to every tie would double count. Used in: max pooling layers in CNNs, max reductions in models, and autograd engines in general.