25/31
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 GG and set the loss to L=∑ijYijGijL = \sum_{ij} Y_{ij} G_{ij}, which in code is (y * g).sum(). Then dY=GdY = G exactly, so you choose the gradient backward receives.

A=[120013],B=[1−12001],G=[10−12]A = \begin{bmatrix} 1 & 2 & 0 \\ 0 & 1 & 3 \end{bmatrix}, \quad B = \begin{bmatrix} 1 & -1 \\ 2 & 0 \\ 0 & 1 \end{bmatrix}, \quad G = \begin{bmatrix} 1 & 0 \\ -1 & 2 \end{bmatrix}

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.
Pick an answer above to see the rest
Predict

Two batch elements, A with G and A2 with G2, share one b. What is b.grad?

Pick one to see what it prints.
Pick an answer above to see the rest