How PyTorch's autograd works, rebuilt in 60 lines of Python A tutorial adapted from Chapter 6 of Farid Alexander's book "The Complete Guide to PyTorch 2: From Tensors to Compiled Deep Learning" rebuilds PyTorch's autograd engine in roughly 60 lines of plain Python and checks every gradient against PyTorch. The piece walks through a one-weight, one-bias model (ŷ = wx + b, squared error, with x = 2, y = 5, w = 1, b = 0) to show that each forward operation records a backward node — MulBackward0, AddBackward0, SubBackward0, PowBackward0 — whose next_functions link to another node, an AccumulateGrad leaf, or None. Calling L.backward() on the loss of 9 yields w.grad = -12 and b.grad = -6, matching PyTorch's own graph, with code posted in the small_autograd.py and check_with_pytorch.py repositories. How PyTorch's autograd works, rebuilt in 60 lines of Python Call loss.backward and PyTorch fills in .grad for every parameter. It can look like magic, but the mechanism is small. During the forward pass, each operation leaves a note saying how to pass a gradient back through it. backward follows those notes from the loss back to the parameters. This article builds that mechanism in about 60 lines of plain Python and checks it against PyTorch. It is adapted from Chapter 6 of my book, The Complete Guide to PyTorch 2: From Tensors to Compiled Deep Learning Kindle https://www.amazon.com/dp/B0HR97T3B2?maas=maas adg DF6D3FACBAE3B2418250A1CEC6B73802 afap abs&ref =aa maas&tag=maas , paperback https://www.amazon.com/dp/B0HRP36BS4?maas=maas adg DFD31D0BA3B70A4C96A95276A3F4356F afap abs&ref =aa maas&tag=maas . If you know Andrej Karpathy's micrograd https://github.com/karpathy/micrograd , the idea is the same. The difference is that each piece here is named and shaped like PyTorch's own objects, so you can print PyTorch's graph and this one side by side, and every gradient is checked against PyTorch. The code below runs top to bottom as one script. The engine needs only Python; the comparisons need PyTorch. small autograd.py https://github.com/farid-alexander/autograd-from-scratch/blob/main/small autograd.py holds the engine on its own, and check with pytorch.py https://github.com/farid-alexander/autograd-from-scratch/blob/main/check with pytorch.py compares it with PyTorch on more expressions. One weight, one bias, one example Take the smallest model that still has a gradient worth computing: a prediction $\hat y = wx + b$ and the squared error $L = \hat y - y ^2$, with $x = 2$, $y = 5$, $w = 1$ and $b = 0$. The input and target are fixed. We want the gradients with respect to $w$ and $b$. By hand, with the chain rule: In PyTorch, give each intermediate result a name: python import torch x = torch.tensor 2.0 y = torch.tensor 5.0 w = torch.tensor 1.0, requires grad=True b = torch.tensor 0.0, requires grad=True p = w x y hat = p + b e = y hat - y L = e 2 print L tensor 9., grad fn=