14/31
Part 3 of 6 · One weight, a whole batchLearn and do
PyTorch hides a missing sum, and NumPy doesn't
Here is a backward that forgets the sum:
from torch.autograd.function import FunctionCtx
class NoSum(torch.autograd.Function):
@staticmethod
def forward(
ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
) -> torch.Tensor:
ctx.save_for_backward(a, b)
return a @ b
@staticmethod
def backward(
ctx: FunctionCtx, grad_out: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
a, b = ctx.saved_tensors
# (2, 4, 5), never summed
grad_b = a.transpose(-1, -2) @ grad_out
print("returned", tuple(grad_b.shape))
return grad_out @ b.transpose(-1, -2), grad_b
a = torch.randn(2, 3, 4, requires_grad=True)
b = torch.randn(4, 5, requires_grad=True)
NoSum.apply(a, b).sum().backward()
print("b.grad ", tuple(b.grad.shape))
NoSum's backward returns a.transpose(-1, -2) @ grad_out for b, with no sum. What shape is that, before PyTorch sees it?
Pick one to see what it prints.
Pick an answer above to see the rest
In NumPy, W is (4, 5) and an unsummed dW is (2, 4, 5). What shape is W - 0.1 * dW?
Pick one to see what it prints.
Pick an answer above to see the rest