A weight shared by a batch gets the sum of the batch's gradients
Each batch element is its own matmul
A real layer sees a whole batch at once.
In a real layer, a carries a batch: (S, n, k), sequences of tokens each. The practice calls the batch size B, but here is the matrix, so the batch size is . The weight b stays (k, m), one matrix for the whole batch. Step through a batch of two:
a @ b broadcasts b across the batch. In symbols, for each element from 1 to .
grad_a needs nothing new. grad_out @ b.transpose(-1, -2) broadcasts the same way and gives each element its own .
b is used S times, so it collects S gradients, added up
A variable used in several places collects a gradient from each use, added up. b is used once per batch element:
is element 's input and is its output's gradient.
When the batch is folded into the rows, as (S·n, k), the product aᵀ @ grad_out does this adding for you, because the sum over rows happens inside the matmul. Here the batch is an axis of its own, outside the matmul, so the sum is yours to write.
| Tensor | Shape | What it is |
|---|---|---|
a | (S, n, k) | a batch of inputs |
b | (k, m) | one weight for the whole batch |
y, grad_out | (S, n, m) | outputs and their gradient |
grad_a | (S, n, k) | grad_out @ b.transpose(-1, -2) |
per-element grad_b | (S, k, m) | a.transpose(-1, -2) @ grad_out |
grad_b | (k, m) | that, summed over dim=0 |
In the editor, write grad_b_loop(a, grad_out): the sum, one batch element at a time.