14.2 Scalar reverse mode: the Value graph
A byte-level bigram model has weights and one loss. Forward mode, from Dual numbers and forward-mode autodiff, would need 65536 passes to get the gradient, one per weight, and a training run takes thousands of steps. Reverse mode gets all 65536 partial derivatives from one forward pass and one backward pass. That asymmetry is why every neural network trains with reverse mode, and it is the engine that Tensor, broadcasting backward, and no_grad in AI Engineering builds over numpy tensors, on the way to a bigram trained by the book’s own autograd.
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE in AI Engineering
- bigram model: a language model that predicts the next token from the current token alone, stored as a table. Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- Forward mode: automatic differentiation that carries tangents alongside values, costing one pass per input direction. Read more: 14.1 Dual numbers and forward-mode autodiff
- Partial derivative: the ordinary derivative of along one coordinate with every other coordinate frozen. Read more: 10.1 Partial derivatives, gradients, and gradcheck
- dual numbers: forward-mode autodiff values that carry an exact derivative alongside each number. Read more: 6.3 The op library and gradcheck_all in AI Engineering
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Topological order: a list of the vertices in which every edge points from an earlier vertex to a later one. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- Jacobian-vector product (JVP): , the directional derivative of a vector function, computed by one forward-mode pass. Read more: 14.1 Dual numbers and forward-mode autodiff
- gradient accumulation: summing the gradients of micro-batches weighted by to reproduce one large batch’s gradient. Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing in AI Engineering
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all in AI Engineering
- Differential test: a check that two implementations of the same contract agree on generated inputs. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Product rule / quotient rule: and , the rules for differentiating a product or a ratio of two functions. Read more: Chapter 7: Calculus 1
- Forward trace: following a bad source through manifests to the shards, token streams, checkpoints, evaluations, and releases built from it. Read more: 12.9 A data incident in Systems Engineering
- Backpropagation: reverse-mode automatic differentiation that computes all parameter gradients in one backward pass. Read more: Chapter 2: Deep Learning in AI Engineering
- Power rule: , the derivative of a power, and with linearity the derivative of any polynomial. Read more: Chapter 7: Calculus 1
Tensors add broadcasting, shapes, and in-place buffers, all of which hide the mechanics. So this section builds the same engine one scalar at a time, where every node is a number you can print. The tensor engine then uses it as an oracle: a tensor op’s gradient must equal the gradient of the same computation spelled out in scalar Values.
You will need the iterative topological sort from Graphs, DAGs, and an iterative topological sort (its toposort lives in graph.py), the dual numbers of the previous section (forward mode must agree with reverse mode), and the numeric VJP of Jacobians, the multivariable chain rule, and numeric JVP/VJP. The complete implementation is scalar.py, with its interface in the contract course/contracts/py/tinyllm/autograd/scalar.pyi.
Learning objectives
- Explain how reverse mode turns the multivariable chain rule into a backward walk over a recorded graph.
- Run a forward and backward pass by hand on a small graph with a reused node.
- Implement a scalar
Valuewith closures for local rules and a backward pass in reverse topological order.- Explain why adjoints accumulate with
+=, why the walk must visit each node once, and why backward costs a constant times the forward pass.
Recording the computation as a graph
Section titled “Recording the computation as a graph”The notation is short. is the final scalar output, the loss. is any node of the graph: an input, a constant, or an intermediate result. Its adjoint says how much changes per unit change of , and lives in v.grad. An operation has inputs (recorded in _prev) and local derivatives . For a vector-valued output, is a weight vector, as in .
Every operation creates a new Value holding its result, the inputs it came from (_prev), and a closure (_backward) that knows the local derivatives. Inputs are leaves. Because a node is created only after its inputs exist, the graph has no cycles: it is a directed acyclic graph, exactly the object that Discrete Math 2 taught you to sort.
The chain rule, pushed backward
Section titled “The chain rule, pushed backward”If depends on only through the nodes that consume , the multivariable chain rule says
So each node , once its own is complete, adds into each input’s adjoint. The sum over consumers is why the update is x.grad += ...: a node used twice (the variable in the worked example below, or every weight shared across time steps in Vanilla RNN with manual BPTT and truncation) collects one term per use.
That raises the question of order. A node may push its adjoint only after every consumer has pushed into it; otherwise it pushes a partial sum. Seed ( changes one-for-one with itself) and visit nodes so that every node comes before its inputs: a reverse topological order. toposort(root, parents) returns exactly that list for parents = lambda v: v._prev, each reachable node once, and it is iterative, so a graph 50000 nodes deep does not hit Python’s recursion limit of about 1000 frames. Walking paths instead of nodes (a stack that pushes every input every time) visits a shared node once per path: its _backward runs several times and its inputs get multiples of the right gradient.
Local rules
Section titled “Local rules”Each operation’s _backward adds times its partial derivatives into its inputs:
| adds to its inputs | |
|---|---|
| , | |
| , | |
| , constant | |
| (reuse the output) | |
| (reuse the output) | |
| , so 0 at exactly |
Subtraction and division need no rules of their own: and . A Python number in an operation becomes a constant leaf; Python calls the reflected method (__rsub__, __rtruediv__) when the number is on the left, and the operand order must survive.
What it costs, and what it computes
Section titled “What it costs, and what it computes”The forward pass does one operation per node; the backward pass does one local-derivative product per edge. So the full gradient of a scalar costs a small constant times one forward pass, whatever the number of inputs. That is the asymmetry with forward mode, which costs one pass per input.
For a vector output , run backward from . The leaves end up holding , a vector-Jacobian product (VJP), the row-vector counterpart of the JVP from the previous section.
One behavior surprises people: backward accumulates, it never resets. Calling backward twice adds every gradient twice, and PyTorch behaves the same. Training loops clear gradients before each step for this reason (zero_grad in The Optimizer protocol: SGD, momentum, Nesterov, weight decay).
Working it by hand
Section titled “Working it by hand”Take at , , . The forward pass creates three nodes:
| node | operation | value |
|---|---|---|
The backward pass visits them in reverse topological order , then the leaves:
| visit | its adjoint | pushes |
|---|---|---|
| (seed) | , | |
| , | ||
| , |
The result is , , . Check it by hand: , so , , and . The two paths into (through directly and through ) add up; with = instead of +=, would end as or depending on the order. These numbers become the first test of the implementation.
Designing the interface
Section titled “Designing the interface”The whole engine is one class:
class Value: data: float; grad: float; _prev: tuple[Value, ...]; _op: str; _backward: Callable[[], None] def __init__(self, data: float, _children: tuple = (), _op: str = '') -> None # + - * / with Values or numbers on either side, unary -, ** with a constant exponent def exp(self) -> Value; def log(self) -> Value; def tanh(self) -> Value; def relu(self) -> Value def backward(self) -> None # self.grad = 1, then _backward in toposort orderbackward calls toposort(self, lambda v: v._prev) from tinyllm.autograd.graph: each reachable node once, every node before the nodes it was computed from. Value ** Value is a TypeError.
Building it step by step
Section titled “Building it step by step”The design follows from the chain rule in six steps.
- The backward chain rule needs, at each node, its inputs and its local derivatives. A node is created by an operation, so the operation is the one place that knows both: each operator method builds the output
Value, records its inputs in_prev, and attaches a closure_backwardthat adds into each input. - Because a node can have several consumers, its adjoint is a sum. So every closure uses
+=on its inputs’grad, andgradstarts at 0. - A node may push only once its adjoint is complete, which forces the order: every node before the nodes it was computed from.
toposort(root, parents)returns that order with each node once, iteratively. - The seed is , set (not added) on the output before the walk.
- Subtraction, division, and negation are compositions of
+,*, and**, so they get their gradients from those rules and need no closures of their own. Numbers become constant leaves via_lift, and reflected methods keep the operand order. - The closures for and reuse the forward output;
relupasses the gradient only where the input is strictly positive.
Start with the node and the two basic rules:
class Value: def __init__(self, data, _children=(), _op=""): self.data = float(data) self.grad = 0.0 # adjoints are sums: start at 0 self._prev = tuple(_children) # the inputs this node was computed from self._op = _op # for printing the graph only self._backward = _noop # leaves have nothing to push
def __add__(self, other): o = _lift(other) out = Value(self.data + o.data, (self, o), "+")
def _backward(): # d(x1 + x2)/dx_j = 1; += because self may be used elsewhere too self.grad += out.grad o.grad += out.grad
out._backward = _backward return out
def __mul__(self, other): o = _lift(other) out = Value(self.data * o.data, (self, o), "*")
def _backward(): # each factor gets the OTHER factor's value; for x * x both lines # hit the same node and add 2x, as they should self.grad += o.data * out.grad o.grad += self.data * out.grad
out._backward = _backward return outThe closure captures self, o, and out, so it reads out.grad at the time it runs, after the walk has completed it, not at the time it was created.
Everything else is built from those two, or has a one-input rule:
def __radd__(self, other): # 2 + x: addition commutes return self + other
def __sub__(self, other): # a - b = a + (-1) b return self + (-_lift(other))
def __rsub__(self, other): # 1 - x: the number stays on the left return _lift(other) + (-self)
def __truediv__(self, other): # a / b = a * b^-1 return self * _lift(other) ** -1
def __rtruediv__(self, other): # 6 / x = 6 * x^-1 return _lift(other) * self**-1
def __neg__(self): return self * -1.0
def __pow__(self, k): # a Value exponent would need the x^y rule (with log x); refuse it # rather than apply k x^(k-1) with the wrong meaning if isinstance(k, Value) or not isinstance(k, (int, float)): raise TypeError("Value ** k needs a constant int or float k") out = Value(self.data**k, (self,), f"**{k}")
def _backward(): self.grad += k * self.data ** (k - 1) * out.grad
out._backward = _backward return out
def exp(self): out = Value(math.exp(self.data), (self,), "exp")
def _backward(): self.grad += out.data * out.grad # (e^x)' = e^x: reuse the output
out._backward = _backward return out
def log(self): out = Value(math.log(self.data), (self,), "log")
def _backward(): self.grad += out.grad / self.data
out._backward = _backward return out
def tanh(self): t = math.tanh(self.data) out = Value(t, (self,), "tanh")
def _backward(): self.grad += (1.0 - t * t) * out.grad # 1 - y^2, y the OUTPUT
out._backward = _backward return out
def relu(self): out = Value(self.data if self.data > 0 else 0.0, (self,), "relu")
def _backward(): # strict >: gradient 0 at exactly 0, as in PyTorch self.grad += (1.0 if self.data > 0 else 0.0) * out.grad
out._backward = _backward return outAnd finally the walk:
def backward(self): # root first, every node before the nodes it was computed from, # each reachable node once; iterative, so deep chains are fine order = toposort(self, lambda v: v._prev) self.grad = 1.0 # seed: set, not += for v in order: v._backward() # v.grad is complete when v is reached
def _lift(x): """A Value as is; a number as a constant leaf.""" return x if isinstance(x, Value) else Value(x)Run the worked example through it. toposort returns and then the leaves (in some order, all after the nodes that consume them). ’s closure adds 2 to and 4 to ; ‘s adds 2 to and ; ‘s adds to and 4 to . Leaves run _noop. .
The full solution is scalar.py; the walk order comes from graph.py.
Why this design
Section titled “Why this design”The cost is what the theory promised. Forward: one node per operation. Backward: one topological sort, , then one closure call per node, each . So the whole gradient costs a small constant times the forward pass, independent of the number of inputs. Memory is one Value per intermediate, which is why scalar autograd is an oracle, not an engine: a matmul on one vector would be a third of a million nodes.
Closures beat a table of op rules because the closure captures exactly the values the rule needs (t for tanh, out for exp) at the time they are computed. A table keyed by _op would have to re-derive them from _prev and could not reuse the forward output.
A precomputed order is simpler than a ready queue. PyTorch counts each node’s pending consumers and runs a node when its count hits zero, which handles graphs that are freed as they go, and multiple devices. For a scalar oracle, one toposort gives the same order with less machinery and reuses the sort you already have.
Composite subtraction and division mean fewer rules and therefore fewer places to get a sign wrong. The cost is a few extra nodes per operation, irrelevant for an oracle.
The tradeoff you accept is that backward accumulates across calls instead of zeroing first. That matches PyTorch and makes gradient accumulation across micro-batches possible; the price is that a training loop must clear gradients itself.
What a correct implementation must handle
Section titled “What a correct implementation must handle”The hand example pins the walk: the forward and backward tables above must come out exactly. Every operation is gradchecked against frozen central differences at three points, so each local rule is right on its own. Two differential tests tie reverse mode to the earlier tools: one expression using every operation is differentiated in both partials and compared with Dual at 25 points, so forward and reverse mode agree; and for a map is compared with vjp_numeric, confirming that reverse mode is a VJP.
The structural cases matter most downstream. A reused node (, , ) models weights shared across positions. A diamond, , must give , since shared subexpressions are everywhere. A 50000-node chain models unrolled recurrences in the RNN chapter of AI Engineering. ReLU at exactly zero must have gradient 0, for agreement with PyTorch at kinks. Constants on either side (, , , , , , , ) cover numbers mixed into expressions. Value ** Value must be a TypeError, so that no rule is silently wrong. And a second call to backward must double the leaf gradient, which is why training zeroes gradients.
The common mistakes, with the symptom each produces:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
x.grad = ... instead of += | a node used twice keeps only its last contribution | every closure adds into grad |
| Walking inputs first, or walking every path | partial or repeated pushes; shared nodes get wrong multiples | toposort gives each node once, consumers first |
A recursive topological sort inside backward | RecursionError on a deep chain | toposort uses an explicit stack |
| Giving each factor its own value in the product rule | is wrong in the worked example | self.grad += o.data * out.grad: each factor gets the other’s value |
| from the input () instead of the output () | wrong slopes away from 0 | captures the output t and uses |
>= in relu’s backward | gradient 1 at the kink, unlike PyTorch | strict self.data > 0 |
| A reflected method that reverses the operands | has slope | __rsub__ builds _lift(other) + (-self) |
| Adding to the seed instead of setting it | the second backward starts from 2 | self.grad = 1.0 before the walk |
Where this leads
Section titled “Where this leads”Looking back, toposort(root, parents) from Graphs, DAGs, and an iterative topological sort supplies the order of the walk without recursion; Dual from Dual numbers and forward-mode autodiff computes the same derivatives forward, and the two must agree; and vjp_numeric from Jacobians, the multivariable chain rule, and numeric JVP/VJP approximates the same by central differences. Looking forward, the tensor engine’s broadcasting backward in Tensor, broadcasting backward, and no_grad is checked against the same computation spelled out in Values. Within this chapter, Matrix differentials, the trace trick, and closed-form VJPs replaces graphs of scalars with one closed-form VJP per matrix operation.
Production engines follow the same pattern with more machinery. micrograd is this same engine plus a tiny neural-network library on top (micrograd/engine.py). PyTorch’s autograd engine uses dependency counting and a ready queue instead of a precomputed order, runs multithreaded per device, and supports retained or freed graphs (torch/csrc/autograd/engine.cpp). JAX’s jax.vjp derives reverse mode by linearizing and transposing the forward trace (jax/_src/interpreters/ad.py).
Further reading:
- Karpathy, micrograd and the lecture “The spelled-out intro to neural networks and backpropagation”.
- Baydin et al., Automatic Differentiation in Machine Learning: a Survey, section 3.2.
Key terms
Section titled “Key terms”- Adjoint: , the sensitivity of the final output to a node, stored in
v.grad. - Reverse mode: automatic differentiation that records the computation and walks it backward once from the output, pushing adjoints into inputs.
- Reverse topological order: an ordering in which every node comes before the nodes it was computed from.
- Vector-Jacobian product (VJP): , what one backward pass from leaves in the leaves.
- Leaf: a node with no inputs, such as a parameter or a constant.
- Seed: the initial adjoint set on the output before the walk.
Summary
Section titled “Summary”- Reverse mode records the computation as a graph, then walks it once from the output, pushing into each node’s inputs by the chain rule.
- A node used several times receives several contributions, so gradients are accumulated with
+=, never assigned. - The walk must visit each node once, after every consumer has added to it: reverse topological order, which an iterative
toposortprovides without recursion. - One backward pass gives the gradient with respect to every input, at a constant times the cost of the forward pass, and it agrees with forward mode on every input.
backwardaccumulates across calls, so training loops clear gradients each step.
Review questions
Section titled “Review questions”-
In ,
__mul__’s closure runsself.grad += o.data * out.gradando.grad += self.data * out.gradwithself is o. What is the result, and why is it right?Answer
Both lines add to the same node, giving , the derivative of . With
=instead of+=, the second line would overwrite the first and give . -
Why must the walk visit nodes in reverse topological order rather than, say, depth-first from the output pushing as it goes?
Answer
A node’s adjoint is a sum over its consumers. Pushing from a node before all its consumers have added to it pushes a partial sum. A depth-first walk that pushes on every visit would also run a shared node’s closure once per path, so in the diamond the inputs would get multiples of the right gradient.
-
Why does
tanhcapturetand use , rather than recomputing fromself.data?Answer
is a function of the output. Using with the input is a different, wrong function (correct only at 0). Capturing
talso avoids recomputing . -
Why is the seed
self.grad = 1.0and notself.grad += 1.0?Answer
by definition, and the root has no consumers that could contribute to it, so the seed is a definition, not a contribution. With
+=, a second call would find the 1 left by the first call and start the walk from 2. (Intermediate nodes also still hold their first-call adjoints, so a second call on the same graph re-pushes them; that is why training builds a fresh graph and clears gradients each step.) -
Why does
Value ** Valueraise instead of using the power rule?Answer
The rule treats the exponent as a constant. With a
Valueexponent, the gradient with respect to the exponent () would be silently missing. Raising makes the unsupported case loud. -
For at , , , what would be if the closures assigned instead of accumulating?
Answer
receives two contributions, 4 from and from . With
=, whichever closure runs last wins, so ends as or depending on the order, instead of the correct .