Training a network means asking, for every weight, how the loss changes when that weight changes. Writing those derivatives by hand for each new model does not scale. An autograd engine records the arithmetic as it runs and then produces every derivative on its own. This is the first lesson of the course Build a language model, in the unit Predicting the next character. It pairs with The spelled-out intro to neural networks and backpropagation: building micrograd by Andrej Karpathy, linked under Watch & read. That video's chapters cover derivatives of simple functions, a value object with a backward step, a neuron and a small network. You build a Scalar class with a backward pass, plus a one-neuron helper, and it is graded against PyTorch's autograd.
The idea has two halves. Going forward, every operation creates a new Scalar and remembers two things: which values it came from, and the local derivative of its result with respect to each of them. For a * b those are b.data for a and a.data for b. For a ** n it is n * a.data ** (n - 1). Computing the local derivatives while the value is fresh is cheap, and after that nobody needs to know which operation produced a node.
Going backward, the chain rule does the rest. If a node's gradient is the derivative of the final output with respect to that node, then each of its parents receives local * node.grad. The only subtlety is the order of the sweep. A node must be visited after every node that uses it, so that its gradient is complete before it is passed down.
Now the backward pass on that graph. Start with L's gradient set to 1. Because L = d·d, d receives d.data twice, once for each use, so d.grad = -4 + -4 = -8. The node d is c + a, whose local derivatives are both 1, so c.grad = -8 and a receives -8 from this route. Then c = a·b passes b.data · c.grad = -3 · -8 = 24 to a and a.data · c.grad = 2 · -8 = -16 to b. In total a.grad = -8 + 24 = 16 and b.grad = -16.
a, b = 2.0, -3.0
c = a * b # -6
d = c + a # -4
L = d * d # 16
dL_dd = 2 * d # d is used twice: -8
a_from_d = 1.0 * dL_dd # d = c + a, local derivative 1
a_from_c = b * dL_dd # c's grad is -8, then times b
b_grad = a * dL_dd
print(L, dL_dd, a_from_d + a_from_c, b_grad)The line that matters is how a total is formed: a received two contributions, -8 and 24, and its gradient is their sum. An implementation that writes parent.grad = local * node.grad keeps only the contribution that arrives last. A single expression such as a * b + c, where every value is used once, still comes out right, which is how the mistake survives casual testing. Use += and test a value that is used twice.
The order comes from a depth-first walk that appends a node after all of its parents. Write it with an explicit stack instead of recursion. Python stops recursing near a thousand frames, and a loop that adds one operation per step builds a chain of that length easily. The stack version handles a chain of thousands of nodes without trouble. A set of visited nodes keeps shared values, like a above, from being ordered twice.
parents = {"L": ["d", "d"], "d": ["c", "a"], "c": ["a", "b"], "a": [], "b": []}
order, seen, stack = [], set(), [("L", False)]
while stack:
node, done = stack.pop()
if done:
order.append(node)
elif node not in seen:
seen.add(node)
stack.append((node, True))
stack.extend((p, False) for p in parents[node])
print(order)Read the printed list from right to left and every node appears before the nodes it was built from, which is the sweep order.
Other mistakes are quieter. Getting the power rule wrong, for instance dropping the factor n so that x ** 3 reports x ** 2, is invisible when the exponent is 1 and the base is 1, so test with other numbers. ReLU needs a slope of 1 only where the input is strictly positive. Calling backward a second time on the same graph adds the root again into the stored gradients of the intermediate nodes, so build a fresh expression, and call zero_grad on the parameters, before every pass.
You check the engine against PyTorch. The hidden tests build random expressions from every operator and compare each value and each gradient with torch autograd in float64, then run a five-thousand-node chain. A second, independent check is a measured slope: nudge a leaf by ±ε and take (f(x + ε) - f(x - ε)) / 2ε.
def L(a, b):
return (a * b + a) ** 2
eps = 1e-6
da = (L(2 + eps, -3) - L(2 - eps, -3)) / (2 * eps)
db = (L(2, -3 + eps) - L(2, -3 - eps)) / (2 * eps)
print(round(da, 4), round(db, 4))These checks confirm that your gradients match the function you wrote. They do not tell you that the function is a good model, that its values stay finite for extreme inputs, or that it is fast: one Python object per number is far slower than a tensor, which is why real frameworks differentiate whole arrays at once. The structure you build here is still the one they use.