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.

aPer-element grad_bSum 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 that b doesn't have.
  • range numbers them from 0.
  • tuple hands them to sum as the axes to remove: (0,) for a 3-D a and (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.

Predict

Without the if, a 2-D a gives grad_b.sum(dim=()). What happens?

Pick an answer above to see the rest