2/31
Part 1 of 6 · Derive the two gradientsLearn

How autograd runs your Function

The skeleton is a node in autograd's graph, and it helps to see where it sits before you fill it in.

Your Function in the graphInteractive
a (2, 3)b (3, 2)@y (2, 2)opsloss
forward, values backward, gradients
MatMul.apply(a, b) runs your forward, y = a @ b, and records a MatMulBackward node in the graph.

This is how PyTorch runs that picture:

  • Autograd, PyTorch's gradient machinery, records each op whose inputs require grad as a node in a graph.
  • loss.backward() walks that graph in reverse and calls each node's backward with the gradient flowing in.
  • The results are added into the .grad of the tensors you made with requires_grad=True, such as the weights.

A torch.autograd.Function is a node of your own. You write its forward and its backward, and the engine calls your backward when its turn comes.