13/31
Part 3 of 6 · One weight, a whole batchLearn and do
Sum over every leading axis, behind an if
A batch can have more than one leading axis.
a | Per-element grad_b | Sum over |
|---|---|---|
(n, k) | (k, m) | nothing |
(S, n, k) | (S, k, m) | axis 0 |
(P, S, n, k) | (P, S, k, m) | axes 0 and 1 |
For code that takes a 2-D or a 3-D a, or more, sum every axis in front of the last two:
if grad_b.dim() > b.dim():
grad_b = grad_b.sum(dim=tuple(range(grad_b.dim() - b.dim())))
Read the second line from the inside out:
grad_b.dim() - b.dim()counts the leading axes thatbdoesn't have.rangenumbers them from 0.tuplehands them tosumas the axes to remove:(0,)for a 3-Daand(0, 1)for a 4-D one.
What's left has b's shape.
The if matters. With a 2-D a, the tuple is empty.
Without the if, a 2-D a gives grad_b.sum(dim=()). What happens?
Pick an answer above to see the rest