11/31
Part 3 of 6 · One weight, a whole batchLearn and do

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), SS sequences of nn tokens each. The practice calls the batch size B, but here BB is the matrix, so the batch size is SS. The weight b stays (k, m), one matrix for the whole batch. Step through a batch of two:

One weight, two batch elementsInteractive
a[0] (2, 3)b (3, 2)a[1] (2, 3)@@y[0] (2, 2)y[1] (2, 2)
forward, values backward, gradients
Both batch elements use the one weight b: y[0] = a[0] @ b and y[1] = a[1] @ b.

a @ b broadcasts b across the batch. In symbols, Ys=AsBY_s = A_s B for each element ss from 1 to SS.

grad_a needs nothing new. grad_out @ b.transpose(-1, -2) broadcasts the same way and gives each element its own dYsB⊤dY_s B^\top.

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:

dB=∑s=1SAs⊤ dYsdB = \sum_{s=1}^{S} A_s^\top\, dY_s

AsA_s is element ss's input and dYsdY_s 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.

TensorShapeWhat 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.