PyTorch Autograd Explained: Rebuilt in 60 Lines of Python

PyTorch autograd can feel like a black box: one loss.backward() call and every parameter has a gradient. A new tutorial shows the machinery fits in roughly 60 lines of plain Python, and it verifies the result against PyTorch.

The core trick is bookkeeping. While the model computes its output, each operation records how to send a gradient back through itself. Backpropagation then replays those records in reverse.

The smallest useful example

The tutorial picks a single-weight model: prediction = w times x plus b, with a squared-error loss. It fixes x at 2 and the target y at 5, and starts w at 1 and b at 0.

Written in PyTorch with a named variable per step (p, y_hat, e, then L), the loss evaluates to 9. Printing it reveals a grad_fn, which is PyTorch’s trace of how that number was produced.

What gets recorded

Any value derived from a tensor that needs gradients carries a backward node. Inspecting next_functions on each node shows where gradients flow next, one entry per input. Each entry falls into one of three cases:

  • A further backward node, if the input came out of an earlier operation.
  • An AccumulateGrad node, if the input is a trainable leaf such as w or b. It deposits incoming gradients in that leaf’s .grad.
  • None, if the input is plain data like x or y.

No derivative has been computed yet. The forward pass has stored only the values the backward rules will need later. Multiplication holds on to x, since the slope of p with respect to w is x. The squaring step holds on to e, since the slope of L with respect to e is 2e.

The result of a backward call

After L.backward(), w.grad is -12 and b.grad is -6. The process begins at the loss with a gradient of 1. Every node scales the gradient it gets by its own local derivative and hands the product to the nodes behind it. The same figures fall out of a by-hand chain-rule calculation.

Writing the engine

The home-made version defines a Node that stores a rule and its list of upstream links, plus an AccumulateGrad class for leaves. The accumulator adds to any gradient already stored, so repeated arrivals stack up.

A Scalar wrapper holds a number and overloads addition, subtraction and multiplication. Each overload computes its answer and calls a small record function, which builds a node whenever any operand needs gradients.

The saved values live inside closures. Multiplication captures both operands. Addition and subtraction capture nothing, since their local slopes are always 1 and -1.

Replaying the example on this class prints the same links as PyTorch, with one quirk. The square is written as e * e, so the final node points at the subtraction node twice. As in PyTorch, w.grad stays None until backward runs.

Visiting nodes in the right order

The backward function runs in two passes. A depth-first walk from the loss collects nodes so that each appears after the nodes it feeds. Reversing that list yields a topological order: no node fires before all of its contributions have landed.

The second pass starts with a gradient of 1 at the loss and processes nodes in order. Each applies its rule and adds the outputs into a running total for its neighbors.

The doubled link shows why totals matter. Multiplication sends -3 down both paths, and they sum to -6, which equals what PyTorch’s power node computes in a single step. The script prints -12.0 and -6.0 for w and b. A value that reaches the loss along several routes just adds up the gradients from each route.

Running it yourself

The engine needs nothing beyond Python. Only the side-by-side comparisons require PyTorch. Since the classes mirror PyTorch’s names and shapes, you can print both graphs and compare them link by link.

It’s a useful exercise for anyone debugging odd None gradients or detached tensors. A sensible next step is adding division, exponentiation or other operators to the Scalar class and checking each new rule against PyTorch.

Source: farid-alexander.github.io

Written by

Saksham Bhargava

Saksham Bhargava runs Alteroid and has been writing about consumer technology for over five years, covering iPhone, Android, Windows, AI tools and gaming. With an MCA and six years of hands-on web development experience, he tests the features he writes about on his own devices and focuses on clear, practical guides that solve real problems. Away from the screen, he enjoys travelling to places most tourists skip.