Computational Graphs & Autograd
loss.backward(). Afterwards, training a network is no longer magic: it is one forward walk and one backward walk over a DAG.After this lesson, you will be able to:
- Explain a computational graph as a directed acyclic graph of operations, compute a gradient on one by hand, and describe why reverse-mode autodiff is the algorithm of choice for training neural networks
- Describe what `loss.backward()` does in a framework, why reverse mode beats forward mode for training, and what memory it costs
- Implement a minimal reverse-mode autograd engine (a `Value` class with one local backward function per operation) and verify its gradients against a hand calculation
Before you start
#Computational Graphs
x = 2 and y = 3 and compute three things in turn: u = x * y, v = x + y, and L = u * v. The graph has the inputs x and y, then the nodes u, v and L. Going forward: u = 6, v = 5, L = 30. Note that x feeds two nodes (u and v) and so does y.L change if x changes a little? Put the local slope (how much each node's output moves per unit change of one of its inputs) on every arrow:L = u * vgivesdL/du = v = 5anddL/dv = u = 6.u = x * ygivesdu/dx = y = 3.v = x + ygivesdv/dx = 1.
x to L. Through u: 5 * 3 = 15. Through v: 6 * 1 = 6. Add the paths: dL/dx = 15 + 6 = 21. For y: through u, 5 * 2 = 10 (since du/dy = x = 2); through v, 6 * 1 = 6; total dL/dy = 16. Check with algebra: L = x²y + xy², so dL/dx = 2xy + y² = 12 + 9 = 21 and dL/dy = x² + 2xy = 4 + 12 = 16. The same numbers.The picture below is this kind of graph. Numbers flow forward along the arrows, and the local slopes sit on the edges. Move an input and watch which node values change, then multiply the slopes along a path to see where each gradient comes from.
What we just did by hand is the general rule: the gradient of the final result with respect to an input equals the sum, over every path from that input to the result, of the product of the local slopes along the path.
The path rule is a result, not a definition. Open the derivation to see it follow from the chain rule you already have.
loss). The backward pass walks the same graph in reverse. Starting from loss with seed gradient dloss/dloss = 1, each node uses its own local slopes plus its already-computed children's gradients to compute the gradient for its parents. In the example: seed 1 at L, then u gets 5, v gets 6, then x collects 5*3 + 6*1 = 21.#Forward mode vs reverse mode (a teaser)
- Forward mode computes derivatives in the same direction as the forward pass: it pushes a nudge (a "tangent vector", meaning one chosen direction in which to wiggle the inputs) forward through the graph. Cost: about one pass per input variable. Cheap if you have few inputs and many outputs.
- Reverse mode (a.k.a. backpropagation) traverses the graph backward from a single output: it pulls a "cotangent vector" (the gradient seed,
1for a scalar loss) back through the graph. Cost: about one pass total, regardless of how many inputs there are.
Why is one backward pass enough? The derivation below counts the work, edge by edge, and compares it with adding up the paths one by one.
#What loss.backward() actually does
loss.backward() walks the computational graph in reverse, applying the chain rule node by node. This lesson's DAG is exactly the graph being walked. Every tensor with requires_grad=True has its .grad field populated with the corresponding partial derivative. The optimizer (SGD, Adam, etc.) then reads .grad and updates the parameter.nn.Embedding(vocab, dim, sparse=True) exists: the gradient of the loss w.r.t. an embedding row is sparse. Only the rows for tokens that appeared in the batch get nonzero gradients (the others were never read during the forward pass, so the chain rule yields zero). A naive dense gradient tensor would be (vocab_size, dim), which for a large vocabulary is a lot of zeros to allocate. The sparse version stores only the rows that changed, cutting memory and compute for large embedding tables.#Try It Yourself
One exercise: a 20-line autograd engine.
#Build autograd: 20 lines
loss.backward(). Each Value holds a number, a grad slot, and the nodes it was made from. Each operation records a tiny function _back that pushes gradient to its parents using the local slopes from the worked example. Use += because a node like x can feed several others, and its gradient is the sum over paths. The test graph is the one you solved by hand: x = 2, y = 3, u = x * y, v = x + y, L = u * v.+= are not arbitrary. Open the derivation to see each one follow from the path rule._back has run.| node run | what its _back does | x.grad | y.grad | u.grad | v.grad | L.grad |
|---|---|---|---|---|---|---|
| start | set L.grad = 1 | 0 | 0 | 0 | 0 | 1 |
| L | u += v × 1 = 5, v += u × 1 = 6 | 0 | 0 | 5 | 6 | 1 |
| v | x += 1 × 6, y += 1 × 6 | 6 | 6 | 5 | 6 | 1 |
| u | x += y × 5 = 15, y += x × 5 = 10 | 21 | 16 | 5 | 6 | 1 |
| y | no parents, nothing to do | 21 | 16 | 5 | 6 | 1 |
| x | no parents, nothing to do | 21 | 16 | 5 | 6 | 1 |
+= adds the second path onto the first. Also, _back can see out because the inner function captures it from the method that built it, which is how each node remembers its own parents. Python calls this a closure.Tests: Verify u = 6, v = 5, L = 30, dL/dx = 21, dL/dy = 16, dL/du = 5, dL/dv = 6, and that the check against the hand calculation prints True.
u, v, L = 6.0 5.0 30.0, then dL/dx = 21.0 dL/dy = 16.0, then dL/du = 5.0 dL/dv = 6.0, then matches hand calculation: True. Those are exactly the numbers from the path sums above. Before you fill in the TODOs the gradients print as 0.0, which is a good sign the skeleton is wired correctly. Notice what reversed(order) guarantees: a node's _back runs only after every node that depends on it has already pushed its gradient in.One derivative, three spellings. In code it is x.grad, in the formulas ∂L/∂x, and in the derivations x̄ (x with a bar). All three are the same number, 21 for x in this graph. L is the loss here. In the Convex Optimization lesson script L is the Lagrangian, and in the Gradient Descent lesson L can also be a smoothness constant.
#Key Takeaways
- Computational graphs make autodiff possible. Forward = topological evaluation of a DAG; backward = the gradient is the sum over paths of products of local slopes, computed in reverse. PyTorch builds it dynamically; JAX traces it once.
loss.backward()is just one DAG traversal. - Reverse mode wins for training. A network has millions to billions of inputs and one scalar loss, so one backward pass gives every gradient. The price is memory, because the forward values must be kept or recomputed.
- A tiny engine is enough. A
Valueclass with one_backclosure per operation,+=accumulation and a reversed topological order reproducesloss.backward()on the worked example: dL/dx = 21 and dL/dy = 16.
#Quick Check
Why is reverse-mode autodiff (backprop) the default for training neural networks instead of forward-mode?