Lab#DL01-1: Derivatives and the computation graph

Lab

📘 Lab#DL01-1: Derivatives and the computation graph

A derivative is a sensitivity: if I nudge this input, how much does the output move? We measure that with a tiny step, then we start wrapping numbers in a Value object that remembers how they were made. That memory is the computation graph.

This lab follows Andrej Karpathy’s lecture The spelled-out intro to neural networks and backpropagation: building micrograd (the first video of Neural Networks: Zero to Hero). The code lives in AlbertProfe/wikiml-zero-to-hero (z2h-01), derived from karpathy/micrograd (MIT Licence).

Code on GitHub

The cells on this page are live Python in the browser. There is no PyTorch here, and no install. The first load takes a few seconds.

1 What a derivative actually says

Karpathy’s opening move is not a long symbolic derivation. It is a measurement.

Take a function of one input, say \(f(x) = 3x^2 - 4x + 5\). At \(x = 2\) the value is \(f(2) = 9\). Now nudge the input by a tiny amount \(h\) and look at how far the output moved:

Screenshot of a Jupyter notebook from Karpathy’s micrograd lecture: the function f of x equals 3 x squared minus 4 x plus 5, f of 3 equals 20, and a plot of the parabola.

Karpathy writes \(f(x) = 3x^2 - 4x + 5\) and plots the curve. At \(x = 3\), \(f(3) = 20\).

\[ \frac{f(x + h) - f(x)}{h} \]

That ratio is the derivative at \(x\). In words: how sensitive is the output to this input, right here? If the derivative is \(8\), then a small nudge of \(+0.001\) on \(x\) should lift \(f\) by about \(0.008\). If it is negative, the output falls when the input rises.

An everyday picture: you stand on a hillside in the fog. You cannot see the whole slope, but you can shuffle one foot a centimetre downhill and feel how far you dropped. The derivative is that drop, divided by the shuffle. A steep hill gives a large number; a flat terrace gives almost zero; if the ground rises when you shuffle “forwards”, the sign flips.

The same idea has many names later — gradient, sensitivity, “how much blame this weight deserves” — but it is this measurement.

Two plots of the curve f of x equals 3 x squared minus 4 x plus 5. Each marks the point at x and the nudged point at x plus h, with the rise, the run, the secant line, and the tangent. The right-hand plot uses a smaller h and is zoomed in, so the secant almost coincides with the tangent.

At \(x = 2\), a nudge \(h\) gives a rise over a run: the slope of the secant. As \(h\) shrinks, that secant lies on the tangent, whose slope is the derivative. Own diagram, based on Andrej Karpathy’s micrograd lecture (Neural Networks: Zero to Hero, lecture 1).

Two plots of the curve f of x equals 3 x squared minus 4 x plus 5. Each marks the point at x and the nudged point at x plus h, with the rise, the run, the secant line, and the tangent. The right-hand plot uses a smaller h and is zoomed in, so the secant almost coincides with the tangent.

At \(x = 2\), a nudge \(h\) gives a rise over a run: the slope of the secant. As \(h\) shrinks, that secant lies on the tangent, whose slope is the derivative. Own diagram, based on Andrej Karpathy’s micrograd lecture (Neural Networks: Zero to Hero, lecture 1).

Karpathy works this through from about 8:08 in the lecture.

Ex#DL01-1

The numerical slope sits right next to \(8\). That is all we asked: a number that tells us, at this point, which way \(f\) moves and how strongly.

Example: measuring the slope at \(x = 3\).

Karpathy’s notebook then stays with this function but moves to \(x = 3\), where \(f(3) = 20\). A nudge of \(h = 0.001\) lifts the output only a little, to about \(20.014\). That is the measurement in miniature: a small shuffle, a small rise.

Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: with h equal to 0.001 and x equal to 3, f of x plus h is about 20.014.

A small nudge \(h = 0.001\) raises \(f\) a little, from 20 to about 20.014.

Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: with h equal to 10 to the minus 8 and x equal to 3, the difference quotient is about 14.

Rise over run, with a tiny \(h\), is about 14, which matches the exact derivative \(6x-4\) at \(x = 3\).

Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: with h equal to 10 to the minus 16 and x equal to 3, the difference quotient is 0.0 because of floating-point precision.

A too-tiny \(h\), around \(10^{-16}\), gives 0 because of floating point.

The slope is that rise divided by the run, \((f(x+h)-f(x))/h\). With a still smaller \(h\), say \(10^{-8}\), the ratio comes out at about \(14\). That is exactly what the derivative \(6x-4\) says at \(x = 3\). The number is not a mystery: it is the steepness of the curve, right there.

There is a catch if you push \(h\) too far. With something like \(h = 10^{-16}\), a computer can no longer tell \(f(x+h)\) from \(f(x)\), so the difference is \(0\) and the ratio comes out as \(0\) — not because the hill is flat, but because the shuffle was smaller than the machine can see. A comfortable middle, such as \(10^{-4}\) or \(10^{-8}\), stays close to the true tangent without falling off the number line.

2 Several inputs at once

Most interesting functions have more than one input. Then we do not have one slope; we have one slope per input, each measured while the others stay still. Those are the partial derivatives. Together they make the gradient.

A useful analogy is a mixing desk. Each slider is an input. You wiggle one slider and listen to how much the output changes; then you put it back and wiggle the next. The gradient is the list of those listenings.

Karpathy does this with a small multi-input expression from about 14:12.

Karpathy’s notebook takes \(d = ab + c\) with \(a = 2\), \(b = -3\) and \(c = 10\), so \(d = 4\). He nudges one input by a tiny \(h\) and holds the others still. In this run \(d\) drops a little, to about \(3.9997\), and the slope is \(-3\). That is \(b\): the derivative of \(ab + c\) with respect to \(a\) is \(b\). Nudge \(b\) instead and the slope is \(a = 2\); nudge \(c\) and it is \(1\). Each slider has its own slope; together they are the gradient.

Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: with a equal to 2, b equal to minus 3 and c equal to 10, d equals a times b plus c; after a tiny nudge the printed slope is about minus 3.

\(d\) starts at 4. This output comes from nudging \(a\), so \(d\) drops to about \(3.9997\) and the slope is \(-3\), which equals \(b\).

Ex#DL01-2

Read the numbers as advice. If you want \(g\) to go up, increase \(b\) (its derivative is \(+2\)) and decrease \(a\) (its derivative is \(-3\)). Changing \(c\) moves \(g\) one-for-one. A neural network will later take exactly this advice, on millions of sliders at once. The idea does not change.

3 A Value that remembers its parents

A calculator throws the recipe away and keeps only the result. To take derivatives automatically we have to keep the recipe.

Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: a first Value class with init, repr and add; Value of 2.0 plus Value of minus 3.0 prints as Value data equals minus 1.0.

Value wraps a single number. __repr__ makes it print nicely. __add__ lets Python’s + build a new Value from two others, so a + b calls a.__add__(b) and gives Value(data=-1.0). This is the first brick of the computation graph.

That is Karpathy’s Value object, started at about 19:09. Each Value stores:

  • data — the number itself;
  • _prev — the values it was made from;
  • _op — the operation that combined them (+, *, and later tanh);
  • grad — how much \(L\) changes if we nudge this value, starting at \(0\) (\(L\) gets \(1\) when backpropagation starts). We add this field in Adding grad to each Value.

A label is only there so we can point at a node when we draw the graph.

Ex#DL01-3

Nothing here computes a derivative yet. The object has only learned to remember. That memory is already the computation graph: a directed acyclic graph whose leaves are the inputs and whose root is the expression we care about.

Screenshot from Karpathy’s micrograd lecture: the trace and draw_dot functions, and the Graphviz drawing of d, with 2.0 and minus 3.0 feeding a times node to minus 6.0, then plus 10.0 giving 4.0.

trace walks back through _prev to collect the nodes and the edges. draw_dot then uses Graphviz to draw each Value as a box and each operation as an oval, left to right. Graphviz is an open-source tool that lays out graphs from a text description; the Python graphviz package is the wrapper used here.

Screenshot from Karpathy’s micrograd lecture: a labelled Graphviz drawing in which e and c feed a plus node to give d, and d and f feed a times node to give L equals minus 8.

With a label on each Value, the drawing matches our names \(a\) to \(L\), and \(L = d \times f = -8\) is the final output.

flowchart BT
  a["a = 2"] --> e["e = a × b = −6"]
  b["b = −3"] --> e
  e --> d["d = e + c = 4"]
  c["c = 10"] --> d
  d --> L["L = d × f = −8"]
  f["f = −2"] --> L

An explanatory diagram of the computation graph for L equals a times b plus c, times f. Leaf nodes a equals 2, b equals minus 3, c equals 10 and f equals minus 2 are styled differently from operation nodes e equals minus 6, d equals 4 and L equals minus 8. A forward-pass arrow runs up the left; a faint backward arrow is labelled next, backpropagation sends gradients back down.

The same graph, explained: leaves are numbers we choose; operation nodes remember their parents and the operation; L is the final output. Own diagram, based on Andrej Karpathy’s micrograd lecture (Neural Networks: Zero to Hero, lecture 1).

An explanatory diagram of the computation graph for L equals a times b plus c, times f. Leaf nodes a equals 2, b equals minus 3, c equals 10 and f equals minus 2 are styled differently from operation nodes e equals minus 6, d equals 4 and L equals minus 8. A forward-pass arrow runs up the left; a faint backward arrow is labelled next, backpropagation sends gradients back down.

The same graph, explained: leaves are numbers we choose; operation nodes remember their parents and the operation; L is the final output. Own diagram, based on Andrej Karpathy’s micrograd lecture (Neural Networks: Zero to Hero, lecture 1).

Every arrow is a parent pointing to a child that used it. When we later walk backwards along those arrows, we will be doing backpropagation. For now it is enough to see that the graph is just the arithmetic, written down.

The full Value class, with gradients, lives in engine.py of the lab repo. The next lab fills the graph in by hand.

4 Adding grad to each Value

The graph we have just built is not only a picture of the arithmetic. It is the road map for backpropagation.

Screenshot from Karpathy’s micrograd lecture: the same labelled Graphviz drawing, now with a grad field on each Value; d has data 4.0 and grad 0.0, f has data minus 2.0 and grad 0.0, and they feed a times node to give L with data minus 8.0 and grad 1.0.
Figure 1

Each Value now also carries grad: how much \(L\) would change if we nudged that value. \(L\)’s grad is 1 because \(L\) changes one-for-one with itself; the others start at 0 until backpropagation fills them in.

A Jupyter cell showing the full Value class: init with data, children, op and label; repr; add; mul; then a equals 2.0, b equals minus 3.0, c equals 10.0, e equals a times b, and d equals a times b plus c.

The full Value class: data, children, op, label, plus + and *.

Each node will carry a number called grad. For a node \(x\), that number is \(\partial L / \partial x\): how much \(L\) changes if you nudge this value. We fill those numbers in by walking the graph backwards, from the output toward the inputs.

We have to start somewhere. The start is \(L\) itself. If I nudge \(L\) by a tiny \(h\), \(L\) changes by exactly \(h\), so the slope is \(1\):

\[ \frac{\partial L}{\partial L} = 1. \]

That is why, in the drawing beside this, \(L\) already shows grad \(1\) and every other node still shows \(0\). Nothing has been walked backwards yet. The \(1\) at \(L\) is the first push; the rest of the grads are still waiting.

The cell below is the same measurement we used at the start of the lab, now applied to \(L\) itself. Nudge the output by \(h\), and the slope is \(1\).

Then we walk back along the arrows, and every other grad gets filled in. That walk is Lab#DL01-2: Backpropagation by hand.

The Value objects in the graph are built from a Python class. If the syntax is new, the note below is a short map. A slower walk through classes is in Python: classes, objects and methods.

A class is a blueprint for creating objects that bundle data and behavior together. The Value class is an example.

1. Class = blueprint, object = thing built from it

a = Value(2.0, label='a')

This builds one Value object. a, b, and c are three separate objects made from the same blueprint.

2. __init__ runs when the object is created

def __init__(self, data, _children=(), _op='', label=''):
    self.data = data

self means “this object”. self.data = data stores the number inside the object. Every object keeps its own data, _prev, _op and label.

3. Methods are functions that belong to the class

They always take self as the first parameter. Python passes it automatically, so you call a.something() and never write self yourself.

4. Double-underscore (“dunder”) methods hook into Python syntax

  • __repr__ controls how the object prints, which is why d shows Value(data=4.0).
  • __add__ makes a + b work. Python turns it into a.__add__(b).
  • __mul__ does the same for a * b.

5. What your code builds

a=2.0 ──┐
        (*) → e=-6.0 ──┐
b=-3.0 ─┘               (+) → d=4.0
                c=10.0 ─┘

Each result remembers its inputs in _prev and the operation in _op. This is the foundation for backpropagation in neural networks.

5 Summary

Idea In one sentence
Derivative How much the output moves when you nudge one input by a tiny \(h\), divided by \(h\).
Sign and size The sign says which way to move the input; the size says how strongly the output cares.
Partial derivative The same measurement, with the other inputs held still.
Gradient The list of all partial derivatives.
Value A number that also stores its parents and the operation that made it.
Computation graph The directed acyclic graph of those parent links, from inputs to the final expression.
grad How much \(L\) changes if you nudge this node; \(L\) itself starts at \(1\), and the rest are filled in backwards.

6 FAQ

Do I need a lot of calculus? No. Karpathy deliberately avoids long symbolic expansions. If you can accept “nudge, measure, divide” and, later, the chain rule as “multiply local slopes”, you can follow the lecture and these labs.

Why is \(h\) so small? Why not \(1\)? The true derivative is the limit as \(h\) goes to zero. A large \(h\) sees the curve bend; a tiny \(h\) stays on an almost straight piece of it. Too tiny, and floating-point noise takes over. \(10^{-4}\) is a comfortable middle.

Why wrap numbers in a class instead of using Python floats? A float is a bare result. A Value is a result plus the recipe. Automatic differentiation needs the recipe.

Is this already a neural network? No. It is the bookkeeping a network will sit on. A network is just a large expression of this kind, with the “sliders” being its weights.

Where is this in the lecture? Overview of micrograd from 0:25; the one-input derivative from 8:08; several inputs from 14:12; the Value object and its graph from 19:09. The official YouTube chapter markers were checked on the video page (30 November 2026).

7 See also

8 References

Back to top