A network learns by changing its numbers so that a loss gets smaller. The tool that tells each number how to change is called autograd. Autograd means automatic gradients. A gradient is the slope of the loss with respect to a number in the net. If you can compute that slope, you can take a small step downhill.
micrograd is a tiny autograd engine, plus a small neural net library on top of it. The project's README says both pieces are tiny, with about 100 and 50 lines of code. In the current code, micrograd/engine.py is 94 lines and micrograd/nn.py is 60 lines. The engine only works on single numbers, called scalars. A real library like PyTorch works on tensors, which are blocks of numbers. The ideas are the same.
Hao Hoang's first question is the right one: how does a network learn? Start here. If you can rebuild this engine without looking, you are ready for the tokenizer lesson later.
Environment setup
Use Python 3.11 or newer. uv manages the project and the virtual environment. Install PyTorch in the same environment. On Apple Silicon, the official macOS ARM wheel includes the MPS backend. On a machine with no GPU, the same install runs on CPU. Check which device you got before you run anything heavier in later lessons.
curl -LsSf https://astral.sh/uv/install.sh | sh
mkdir -p llm-built && cd llm-built
uv init --python 3.11
uv venv
uv add torch pytest
uv run python -c "import torch; print(torch.__version__); print('MPS:', torch.backends.mps.is_available()); print('CUDA:', torch.cuda.is_available())"
If MPS prints True, later PyTorch examples can use device = "mps". If it does not, use device = "cpu". See the PyTorch MPS notes for the Apple Silicon path. You do not need a GPU for this lesson. The engine below is plain Python. PyTorch is here so you can, if you want, check a gradient against torch.Tensor, which is how micrograd's own tests work.
A value, then a graph
Wrap a number in a Value. When you add or multiply two values, you do not only store the result. You also remember the parents and how they were combined. That memory is the graph.
flowchart LR
A["a = -4.0"] --> C["c = a + b"]
B["b = 2.0"] --> C
Each node stores the number from the forward pass, and a gradient that starts at zero. The backward pass will fill those gradients in.
flowchart LR
A["a = -4.0, grad = ?"] --> C["c = a + b"]
B["b = 2.0, grad = ?"] --> C
C --> G["g, grad = 1.0"]
You start backward from the last node, usually the loss, and set its gradient to 1. Then you walk the graph in reverse and apply the local rule for each operation. For addition, each parent receives the same gradient that arrived at the child. For multiplication, each parent receives the other parent's value times the arriving gradient. If a value is used more than once, its gradient adds up.
flowchart LR
A["a, grad filled"] --> C["c"]
B["b, grad filled"] --> C
C --> G["g, grad = 1.0"]
G -.->|backward| C
C -.->|backward| A
C -.->|backward| B
A short engine you can run
The code below is a small teaching engine in the same spirit as micrograd. It is not a copy of the repo. Save it as engine.py and run it with uv run python engine.py. The printed numbers should match the example in the micrograd README: g is 24.7041, the gradient on a is 138.8338, and the gradient on b is 645.5773.
class Value:
def __init__(self, data, _children=(), _op=""):
self.data = float(data)
self.grad = 0.0
self._backward = lambda: None
self._prev = tuple(_children)
self._op = _op
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), "+")
def _backward():
self.grad += out.grad
other.grad += out.grad
out._backward = _backward
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), "*")
def _backward():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, power):
assert isinstance(power, (int, float))
out = Value(self.data ** power, (self,), f"**{power}")
def _backward():
self.grad += (power * self.data ** (power - 1)) * out.grad
out._backward = _backward
return out
def relu(self):
out = Value(self.data if self.data > 0 else 0.0, (self,), "relu")
def _backward():
self.grad += out.grad if self.data > 0 else 0.0
out._backward = _backward
return out
def __neg__(self):
return self * -1
def __radd__(self, other):
return self + other
def __sub__(self, other):
return self + (-other)
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
return self * other**-1
def __rtruediv__(self, other):
return other * self**-1
def backward(self):
order = []
seen = set()
def build(node):
if node not in seen:
seen.add(node)
for child in node._prev:
build(child)
order.append(node)
build(self)
self.grad = 1.0
for node in reversed(order):
node._backward()
a = Value(-4.0)
b = Value(2.0)
c = a + b
d = a * b + b**3
c += c + 1
c += 1 + c + (-a)
d += d * 2 + (b + a).relu()
d += 3 * d + (b - a).relu()
e = c - d
f = e**2
g = f / 2.0
g += 10.0 / f
print(f"{g.data:.4f}") # 24.7041
g.backward()
print(f"{a.grad:.4f}") # 138.8338
print(f"{b.grad:.4f}") # 645.5773
The backward method first builds a topological order. That is a list where every parent appears before the node that used it. Then it walks the list in reverse, so a child is processed before its parents. That is the whole trick. Once you have that walk, each operation only needs a short local rule.
The neural net library on top is thin. A neuron is a weighted sum of inputs, plus a bias, then a nonlinearity such as ReLU. A layer is a list of neurons. A multi-layer net is a list of layers. Because every piece returns a Value, loss.backward() fills gradients for every weight. The micrograd repo trains a small two-layer classifier in demo.ipynb. You do not need that notebook to understand the engine.
When you can write this engine again without looking, go to the lecture map. Watch lecture 1 alongside this lesson if you want the spelled-out version. It is the same engine, built live.
Key concepts
- Autograd records a graph on the forward pass and walks it backward to compute gradients.
- micrograd does this on scalars, in about 100 lines of engine code and about 50 lines of neural net code, as its README states.
- A topological walk makes sure each node applies its local backward rule after its children.
- Addition, multiplication, power, and ReLU each have a short local gradient rule. Shared values add their gradients.
- A neuron, a layer, and a multi-layer net can sit on top of the same Value type.
Takeaways
- Run the engine and match the README numbers: 24.7041, 138.8338, and 645.5773.
- Rebuild the engine without looking before you move to the tokenizer lesson.
- Keep the official repo nearby: github.com/karpathy/micrograd.