Reverse-mode automatic differentiation, in eager Python
Autograd is PyTorch's automatic differentiation engine. It does one specific thing: when you compute a scalar (like a loss), it walks backwards through the operations that produced that scalar and accumulates the gradient of the scalar with respect to every leaf tensor that asked to track gradients.
"Reverse-mode" matters: forward-mode AD computes derivatives forwards (good when you have few inputs and many outputs); reverse-mode goes backwards (good when you have many inputs and one output — exactly the loss-vs-parameters shape of deep learning). For a model with 100M parameters and a scalar loss, reverse-mode is the only practical option.
"Dynamic graph" — what that buys you
PyTorch builds the graph on the fly, every forward pass. This means:
- You can use Python control flow (if/else, while, for) inside
forward(). The graph reflects the actual path taken on this particular input. - You can debug with print statements, breakpoints, even pdb. The forward pass is just Python.
- The graph is thrown away after each backward call (unless you ask it to be retained). Memory stays bounded.
The cost: dynamic graphs are slightly slower to set up than static ones because there's no opportunity for ahead-of-time optimization. torch.compile() (later track) gives you the static-graph speedup without giving up the dynamic feel — but autograd itself stays dynamic.