Part 5 of 6 · A Linear layer, proved by gradcheckLearn and do
A worked example
Use the trick the practice's tests use. Pick a fixed matrix G and set the loss to L=∑ijYijGij, which in code is (y * g).sum(). Then dY=G exactly, so you choose the gradient backward receives.
A=[102103],B=120−101,G=[1−102]
The code checks autograd against worked(), this step's task, which returns dA and dB from the formulas:
A = torch.tensor([[1., 2., 0.], [0., 1., 3.]])B = torch.tensor([[1., -1.], [2., 0.], [0., 1.]])G = torch.tensor([[1., 0.], [-1., 2.]])a = A.clone().requires_grad_()b = B.clone().requires_grad_()loss = (a @ b * G).sum()loss.backward()print(loss.item())dA, dB = worked()print(torch.equal(a.grad, dA), torch.equal(b.grad, dB))
Predict
With loss = (a @ b * G).sum(), G is the gradient that arrives at Y. Does autograd agree with the formulas' dA and dB, from worked()?
Pick one to see what it prints.
Autograd agrees with both formulas, entry for entry:
Shape
Value
Y=AB
2 × 2
[[5, -1], [2, 3]]
L
scalar
9
dA
2 × 3
[[1, 2, 0], [-3, -2, 2]]
dB
3 × 2
[[1, 0], [1, 2], [-3, 6]]
Check one entry by hand. dA[1, 0] is -3, for the entry of A you nudged in Part 1:
From the formula: row 1 of G times row 0 of B, (−1)(1)+(2)(−1)=−3.
By nudging: move A[1, 0] by 0.001, and row 1 of Y moves by 0.001 times row 0 of B, [0.001, -0.001].
So L moves by (0.001)(−1)+(−0.001)(2)=−0.003, a slope of -3.
Now call that pair A1 and G1 and add a second batch element that shares B: