12/31
Part 3 of 6 · One weight, a whole batchLearn and do
Three ways to write the sum, all equal
A loop is clear, but not how you'd write it in practice. Here are two more ways, by_einsum and by_fold, which you write in this step's task, against the sum of the batched products:
torch.manual_seed(0)
a = torch.randn(2, 3, 4, dtype=torch.float64)
grad_out = torch.randn(2, 3, 5, dtype=torch.float64)
s1 = (a.transpose(-1, -2) @ grad_out).sum(dim=0)
s2 = by_einsum(a, grad_out)
s3 = by_fold(a, grad_out)
print(tuple(s1.shape), torch.allclose(s1, s2), torch.allclose(s1, s3))
Three ways to get b's gradient over a batch: sum the batched products, an einsum, or fold the batch into the rows first. Do they agree?
Pick one to see what it prints.
Pick an answer above to see the rest