15/31
Part 4 of 6 · A Function of your ownLearn and do

torch.autograd.Function: save in forward, return gradients in backward

With both gradients derived and the batch handled, the formulas go into a Function.

Here's the whole Function, with the sum, and one call to it:

class MatMul(torch.autograd.Function):
    @staticmethod
    def forward(
        ctx: FunctionCtx, a: torch.Tensor, b: torch.Tensor
    ) -> torch.Tensor:
        """a: (..., n, k), b: (k, m). Returns a @ b, (..., n, m)."""
        ctx.save_for_backward(a, b)
        return a @ b

    @staticmethod
    def backward(
        ctx: FunctionCtx, grad_out: torch.Tensor
    ) -> tuple[torch.Tensor | None, torch.Tensor | None]:
        """Returns (grad_a, grad_b), shaped like a and b."""
        a, b = ctx.saved_tensors
        grad_a = grad_b = None
        if ctx.needs_input_grad[0]:
            grad_a = grad_out @ b.transpose(-1, -2)
        if ctx.needs_input_grad[1]:
            grad_b = a.transpose(-1, -2) @ grad_out
            # sum the batch axes
            if grad_b.dim() > b.dim():
                grad_b = grad_b.sum(dim=tuple(range(grad_b.dim() - b.dim())))
        return grad_a, grad_b

a = torch.randn(2, 3, 4, requires_grad=True)
b = torch.randn(4, 5, requires_grad=True)
y = MatMul.apply(a, b)
print(tuple(y.shape), type(y.grad_fn).__name__)
y.sum().backward()
print(tuple(a.grad.shape), tuple(b.grad.shape))
Predict

a is (2, 3, 4) and b is (4, 5). After y.sum().backward(), what shapes are a.grad and b.grad?

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

You call an instance, MatMul()(a, b), instead of MatMul.apply(a, b). What happens?

Pick an answer above to see the rest