{"slug": "how-pytorch-s-autograd-works-rebuilt-in-60-lines-of-python", "title": "How PyTorch's autograd works, rebuilt in 60 lines of Python", "summary": "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.", "body_md": "# How PyTorch's autograd works, rebuilt in 60 lines of Python\n\nCall `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.\n\nThis 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)).\n\nIf 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.\n\nThe 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.\n\n## One weight, one bias, one example\n\nTake 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$.\n\nBy hand, with the chain rule:\n\nIn PyTorch, give each intermediate result a name:\n\n``` python\nimport torch\n\nx = torch.tensor(2.0)\ny = torch.tensor(5.0)\nw = torch.tensor(1.0, requires_grad=True)\nb = torch.tensor(0.0, requires_grad=True)\n\np = w * x\ny_hat = p + b\ne = y_hat - y\nL = e ** 2\n\nprint(L)\ntensor(9., grad_fn=<PowBackward0>)\n```\n\nThe loss is 9. The interesting part is `grad_fn`: PyTorch has recorded how `L` was made.\n\n## What the forward pass leaves behind\n\nEvery result computed from a tensor that requires a gradient gets a `grad_fn`, a **backward node** for the operation that produced it. Each node lists in `next_functions` where it will send gradients:\n\n```\nfor name, t in [(\"p\", p), (\"y_hat\", y_hat), (\"e\", e), (\"L\", L)]:\n    links = [type(n).__name__ if n else None\n             for n, _ in t.grad_fn.next_functions]\n    print(name, type(t.grad_fn).__name__, links)\np MulBackward0 ['AccumulateGrad', None]\ny_hat AddBackward0 ['MulBackward0', 'AccumulateGrad']\ne SubBackward0 ['AddBackward0', None]\nL PowBackward0 ['SubBackward0']\n```\n\nEach operation has one link per input, and a link is one of three things:\n\n- **Another backward node** , when the input was itself computed.`y_hat` links to`MulBackward0` because its input`p` came from the multiplication.\n- **`AccumulateGrad`** , when the input is a leaf tensor that requires a gradient, like`w` and`b` . This node adds whatever arrives into the leaf's`.grad` .\n- **`None`** , when the input needs no gradient, like` x` and`y` .\n\n*The graph for this example, from the book. The forward pass computes values left to right; the backward pass sends gradients right to left. Parameters are green, data gray, intermediate results blue, and each blue box names the backward node PyTorch records for it.*\n\nNothing has been differentiated yet. The forward pass has computed the values and kept the ones the backward rules will need: the multiplication keeps `x`, because $\\partial p / \\partial w = x$, and the square keeps `e`, because $\\partial L / \\partial e = 2e$.\n\n## What `backward()` does with it\n\n```\nL.backward()\nprint(w.grad, b.grad)\ntensor(-12.) tensor(-6.)\n```\n\nThe engine starts at the loss with $\\partial L / \\partial L = 1$ and follows the links. Each node multiplies the gradient it receives, *g*, by its local derivative and passes the result on:\n\n| Node | Rule for an incoming gradient *g* | Sends | \n|---|---|---|\n| `PowBackward0` ,*L* =*e* ² | *g* · 2*e* toward*e* | 1 · 2(−3) = −6 | \n| `SubBackward0` ,*e* =*ŷ* −*y* | *g* toward*ŷ* | −6 | \n| `AddBackward0` ,*ŷ* =*p* +*b* | *g* toward both*p* and*b* | −6 and −6 | \n| `MulBackward0` ,*p* =*wx* | *g* ·*x* toward*w* | −6 · 2 = −12 | \n\nThe two `AccumulateGrad` nodes store −12 in `w.grad` and −6 in `b.grad`, the values worked out by hand. Autograd is recorded local rules, applied in the right order. Now build it.\n\n## Recording the forward pass\n\nStart with the two kinds of node:\n\n``` python\nclass Node:\n    def __init__(self, name, rule, inputs):\n        self.name = name\n        self.rule = rule    # incoming gradient -> one per input\n        self.next_functions = [t.grad_fn or t.accumulator\n                               for t in inputs]\n\nclass AccumulateGrad:\n    name = \"AccumulateGrad\"\n    next_functions = []\n\n    def __init__(self, leaf):\n        self.leaf = leaf\n\n    def rule(self, g):\n        old = self.leaf.grad\n        self.leaf.grad = g if old is None else old + g\n        return []\n```\n\nA `Node` is what `grad_fn` will point to. Its `rule` takes the incoming gradient *g* and returns one gradient per input, like a row of the table above. Its `next_functions` holds the same three kinds of link PyTorch printed: an input's own `grad_fn` if an operation produced it, its accumulator if it is a leaf that requires a gradient, and `None` otherwise. `AccumulateGrad` ends a path by adding what arrives into the leaf's `.grad`.\n\nNext, a number type whose operations record themselves:\n\n``` python\nclass Scalar:\n    def __init__(self, value, requires_grad=False):\n        self.value = value\n        self.requires_grad = requires_grad\n        self.grad = None\n        self.grad_fn = None\n        self.accumulator = (AccumulateGrad(self)\n                            if requires_grad else None)\n\n    def __add__(self, other):\n        return record(\"AddBackward\", self.value + other.value,\n                      [self, other], lambda g: [g, g])\n\n    def __sub__(self, other):\n        return record(\"SubBackward\", self.value - other.value,\n                      [self, other], lambda g: [g, -g])\n\n    def __mul__(self, other):\n        a, b = self.value, other.value   # saved for backward\n        return record(\"MulBackward\", a * b, [self, other],\n                      lambda g: [g * b, g * a])\n\ndef record(name, value, inputs, rule):\n    out = Scalar(value)\n    if any(t.requires_grad for t in inputs):\n        out.requires_grad = True\n        out.grad_fn = Node(name, rule, inputs)\n    return out\n```\n\nEach operator computes its value and hands it to `record`. If any input requires a gradient, `record` creates the node and attaches it to the result. The values a backward rule needs are saved by the `lambda` that captures them. The multiplication keeps `a` and `b`, because the derivative of *ab* is *b* with respect to *a* and *a* with respect to *b*. Addition and subtraction keep nothing, since their local derivatives are 1 and −1 whatever the inputs. Like a tensor, a `Scalar` keeps its value (`value`) apart from its history (` grad_fn`).\n\nRun the same forward pass with it. Writing the square as `e * e` keeps the class to three operations:\n\n```\nx, y = Scalar(2.0), Scalar(5.0)\nw = Scalar(1.0, requires_grad=True)\nb = Scalar(0.0, requires_grad=True)\n\np = w * x\ny_hat = p + b\ne = y_hat - y\nL = e * e\n\nfor name, t in [(\"p\", p), (\"y_hat\", y_hat), (\"e\", e), (\"L\", L)]:\n    links = [n.name if n else None\n             for n in t.grad_fn.next_functions]\n    print(name, t.grad_fn.name, links)\nprint(L.value, w.grad)\np MulBackward ['AccumulateGrad', None]\ny_hat AddBackward ['MulBackward', 'AccumulateGrad']\ne SubBackward ['AddBackward', None]\nL MulBackward ['SubBackward', 'SubBackward']\n9.0 None\n```\n\nThe links match PyTorch's. The only difference is the square: its node links to the subtraction node twice, once for each `e` in `e * e`. And `w.grad` is still `None`. Here too, the forward pass only builds the graph.\n\n## Running the backward pass\n\n``` python\ndef backward(loss):\n    order, seen = [], set()\n    def visit(node):               # a node's inputs go first\n        if node is not None and node not in seen:\n            seen.add(node)\n            for nxt in node.next_functions:\n                visit(nxt)\n            order.append(node)\n    visit(loss.grad_fn)\n\n    grads = {loss.grad_fn: 1.0}    # dL/dL = 1\n    for node in reversed(order):   # the loss's node comes first\n        g = grads.pop(node)        # every arrival, summed\n        for nxt, g_in in zip(node.next_functions, node.rule(g)):\n            if nxt is not None:\n                grads[nxt] = grads.get(nxt, 0.0) + g_in\n\nbackward(L)\nprint(w.grad, b.grad)\n-12.0 -6.0\n```\n\n`backward` works in two stages.\n\nFirst it settles the order. `visit` follows `next_functions` from the loss's node and appends a node to `order` only after every node it sends gradients to. Reversed, the list puts each node after all the nodes that send gradients to it, an order called a **topological order**. A node must not run until everything coming to it has arrived, and this order guarantees that.\n\nThen it walks the nodes in that order, starting from $\\partial L / \\partial L = 1$. When a node's turn comes, its entry in `grads` already holds the sum of all its incoming gradients. It applies its rule and adds each result to the entry of the node that result goes to. The `AccumulateGrad` nodes come last and store the totals.\n\nThe sum is where `e * e` matters. The multiplication node sends −3 along each of its two links (*g* · *b* and *g* · *a*, with *g* = 1 and *a* = *b* = −3), and `grads` adds them into −6. That is the same $\\partial L / \\partial e$ that PyTorch's `PowBackward0` produced in one step.\n\n## Values used more than once\n\nThat sum is the chain rule's answer for a value that reaches the loss along several paths: add the contributions. Check it in both engines on *s* = *a* · *a* + *a* at *a* = 3, where the derivative is 2*a* + 1 = 7:\n\n```\na = Scalar(3.0, requires_grad=True)\ns = a * a + a\nbackward(s)\n\na_t = torch.tensor(3.0, requires_grad=True)\ns_t = a_t * a_t + a_t\ns_t.backward()\n\nprint(a.grad, a_t.grad.item())\n7.0 7.0\n```\n\n`a` receives 3 through each input of the multiplication and 1 through the addition.\n\nGradients also add up across backward calls, because `AccumulateGrad` adds to whatever `.grad` already holds. Run the backward pass of the first example a second time:\n\n```\nbackward(L)\nprint(w.grad)\n-24.0\n```\n\nPyTorch would refuse this particular call. It frees the saved values once backward has used them, so a second `L.backward()` on the same graph raises an error unless the first call passed `retain_graph=True`. After a fresh forward pass, though, PyTorch accumulates exactly like this, which is why training loops clear the gradients with `optimizer.zero_grad()` before each backward pass.\n\n## What PyTorch adds\n\nThe real engine does the same job at a much larger scale:\n\n- **Tensors instead of numbers.** Each rule receives a gradient tensor and computes a vector-Jacobian product without ever building the full Jacobian matrix.\n- **Hundreds of rules.** The derivative formulas are written once (most are in`tools/autograd/derivatives.yaml` in the PyTorch source), and the C++ backward nodes are generated from them.\n- **A different scheduler.** Instead of a recursive search, the engine counts the links into each node and runs a node once all its gradients have arrived. It is written in C++, not Python.\n- **Memory.** Saved values are freed as soon as backward has used them, which is why the second call above fails in PyTorch.\n- **Safety checks.** Every tensor carries a version counter, so changing a saved tensor in place before backward raises an error instead of giving a silently wrong gradient.\n- **An off switch.** Inside`torch.no_grad()` nothing is recorded, so inference spends no memory on graphs.\n\nWhen you need an operation PyTorch doesn't have, `torch.autograd.Function` lets you write its forward and backward rules, much like the `lambda` s here, and plug them into the real engine.\n\n## Try it yourself\n\n1. Add an `exp()` method. The derivative of*eˣ* is*eˣ* itself, so the rule can reuse the output value. Compute exp(*a* ·*c* ) with*a* = 2 and*c* = 3 and compare`a.grad` with PyTorch's; both should be about 1210.29. This is Exercise 6.8 in the book.\n2. Let `Scalar` accept plain numbers, so that`2 * w` and`w - 1` work. Python calls`__rmul__` for the first.\n3. Train the model above with gradient descent: repeat the forward pass, `backward` , an update of`w.value` and`b.value` , and a reset of both gradients to`None` . The loss should fall toward 0 as 2*w* +*b* approaches 5.\n\n## About the book\n\nThis article is adapted from Chapter 6, \"Autograd: How PyTorch Computes Gradients\", of *The Complete Guide to PyTorch 2: From Tensors to Compiled Deep Learning* by Farid Rahmani. The book starts from your first tensor and goes on to train image classifiers, build a small GPT-style language model from scratch, and speed training up with mixed precision, `torch.compile` and distributed training. It explains the math as you need it and has 237 exercises with answers; the ebook adds worked solutions.\n\n## License\n\nThe code in this repository is under the [MIT License](https://github.com/farid-alexander/autograd-from-scratch/blob/main/LICENSE). The article text and the figure are © 2026 Farid Rahmani.", "url": "https://wpnews.pro/news/how-pytorch-s-autograd-works-rebuilt-in-60-lines-of-python", "canonical_source": "https://farid-alexander.github.io/autograd-from-scratch/", "published_at": "2026-11-25 01:40:39+00:00", "updated_at": "2026-11-25 02:14:38.749470+00:00", "lang": "en", "topics": ["machine-learning", "artificial-intelligence", "developer-tools"], "entities": ["PyTorch", "Farid Alexander", "The Complete Guide to PyTorch 2: From Tensors to Compiled Deep Learning", "Andrej Karpathy", "micrograd", "small_autograd.py", "check_with_pytorch.py"], "also_reported_by": [], "takeaway": "Each forward operation records a backward node whose next_functions point to another node, an AccumulateGrad leaf, or None, so a ~60-line Python engine reproduces PyTorch's gradients exactly (w.grad = -12, b.grad = -6 on the worked example).", "recommendation": {"advice": "When implementing or debugging autograd, name each intermediate result and inspect grad_fn.next_functions to confirm each input maps to a backward node, an AccumulateGrad leaf, or None, then verify gradients against PyTorch.", "playbook": "training-data", "playbook_url": "https://wpnews.pro/playbooks/training-data"}, "alternates": {"html": "https://wpnews.pro/news/how-pytorch-s-autograd-works-rebuilt-in-60-lines-of-python", "markdown": "https://wpnews.pro/news/how-pytorch-s-autograd-works-rebuilt-in-60-lines-of-python.md", "text": "https://wpnews.pro/news/how-pytorch-s-autograd-works-rebuilt-in-60-lines-of-python.txt", "jsonld": "https://wpnews.pro/news/how-pytorch-s-autograd-works-rebuilt-in-60-lines-of-python.jsonld"}}