8/31
Part 2 of 6 · Shapes place each factorLearn and do

The shapes leave one way to write each product

A gradient has the shape of its input

The derivation is the proof, but the shapes are the fastest check.

dAdA must be n×kn \times k like AA, and dBdB must be k×mk \times m like BB. With the practice tests' sizes, a is (3, 4), b is (4, 5) and grad_out is (3, 5). Try each product:

Only one product fits each gradientInteractive
grad_out(3n,5m)@b.T(5m,4k)=result(3n,4k)matches a (3, 4)
The inner m's meet and are summed away, which leaves (3, 4): the shape of a. This is the gradient.

grad_a has n rows and so does grad_out, so grad_out goes on the left. The other factor must be (m, k), and the only one is b transposed.

grad_b has m columns and so does grad_out, so grad_out goes on the right. The other factor must be (k, n), which is a transposed.

Forget the formulas under pressure and you can rebuild them this way in a few seconds. With the practice's names:

TensorShapeWhat it is
a(n, k)the first input
b(k, m)the second input, a weight
y(n, m)the output, a @ b
grad_outlike yhanded to backward
grad_alike agrad_out @ b.transpose(-1, -2)
grad_blike ba.transpose(-1, -2) @ grad_out

In the editor, write shapes(n, k, m): the shapes of grad_out, grad_a and grad_b as tuples, for any sizes.