Lab#DL-0004: From neuron to MLP and training

Lab

📘 Lab#DL-0004: From neuron to MLP and training

The engine can differentiate any expression. A neural network is one particular expression: a neuron, then a layer of them, then layers stacked as a multi-layer perceptron. We put a loss on top, take a small step against the gradient, and repeat on a tiny dataset of four examples.

This lab follows Andrej Karpathy’s lecture The spelled-out intro to neural networks and backpropagation: building micrograd (playlist), from about 1:43:55. The library and the training script are nn.py and train.py in wikiml-zero-to-hero (z2h-01), derived from karpathy/micrograd (MIT Licence).

Code on GitHub

The cells are live Python in the browser. There is no PyTorch here. The first cell rebuilds a compact engine so the page stands alone; the second cell trains.

1 A neuron, a layer, then an MLP

Karpathy models the library on PyTorch’s nn modules, starting at 1:43:55.

  • A neuron has a weight per input and a bias. It computes a weighted sum, plus the bias, then \(\tanh\). The bias is the neuron’s “trigger happiness”: a higher bias means the neuron fires more readily.
  • A layer is just a list of neurons that all see the same inputs and do not talk to each other.
  • An MLP (multi-layer perceptron) is layers in a queue: the output of one is the input of the next. MLP(3, [4, 4, 1]) means three inputs, two hidden layers of four neurons, and a single output.

flowchart LR
  x1((x1)) --> H1[hidden 4]
  x2((x2)) --> H1
  x3((x3)) --> H1
  H1 --> H2[hidden 4]
  H2 --> y((y))

None of this is a new kind of mathematics. It is a tidy way to build a large expression whose leaves are the weights. parameters() collects those leaves so we can step them later. zero_grad() clears their .grad before the next backward pass.

Ex#DL-4001

MLP(3, [4, 4, 1]) has \(41\) parameters: \((3\times 4 + 4) + (4\times 4 + 4) + (4\times 1 + 1) = 16 + 20 + 5\). The exact output of the first forward pass does not matter; the weights are random. What matters is that it is an ordinary Value, so .backward() already works on it.

2 A tiny dataset, a loss, and a step

From 1:51:04 Karpathy uses four examples, each with three numbers, and targets in \(\{+1, -1\}\). It is a miniature binary classifier, small enough that you can watch every prediction.

\[ \begin{aligned} x^{(1)} &= (2, 3, -1),\quad y^{(1)} = +1 \\ x^{(2)} &= (3, -1, 0.5),\quad y^{(2)} = -1 \\ x^{(3)} &= (0.5, 1, 1),\quad y^{(3)} = -1 \\ x^{(4)} &= (1, 1, -1),\quad y^{(4)} = +1 \end{aligned} \]

The loss is the sum of squared errors, \(\sum_i (y_{\mathrm{pred}}^{(i)} - y^{(i)})^2\). It is zero only when every prediction hits its target. One call to loss.backward() fills a gradient into every weight. Then each parameter takes a small step

\[ p \leftarrow p - \eta \cdot \frac{\partial L}{\partial p} \]

with a learning rate \(\eta\). That is gradient descent: walk downhill on the loss, a short step at a time.

The loop, shown from 2:01:12, is always the same four beats: forward, zero the gradients, backward, update. Forgetting to zero is a classic bug. Because _backward uses +=, a second backward pass would add a fresh gradient on top of the old one and the step would look mysteriously too large. A toy problem can hide it for a while; then it bites.

Ex#DL-4002

The predictions should drift towards \(+1, -1, -1, +1\), and the loss should fall. If you re-run the first cell you get a new random start; the curve will look different and the destination should be the same idea.

On your own machine you can run the same loop from the repo, with a few more steps:

git clone https://github.com/AlbertProfe/wikiml-zero-to-hero.git
cd wikiml-zero-to-hero/01-micrograd
python train.py

3 What does not change when the network grows

Karpathy’s summary, from 2:14:03, is the sentence to keep: a production model has vastly more parameters and a different loss, but the loop is the same. Forward, zero, backward, update. micrograd works on scalars so you can see every node; PyTorch packs those scalars into tensors so the same mathematics can run quickly. You have already implemented the thing that libraries wrap.

4 Summary

Idea In one sentence
Neuron Weighted sum of inputs, plus a bias, then \(\tanh\).
Layer Several neurons that share the same inputs and are otherwise independent.
MLP Layers chained so each feeds the next.
Loss A single number that says how wrong the whole network is (here, the sum of squared errors).
Gradient descent Move every parameter a little against its gradient, \(p \leftarrow p - \eta\,\partial L/\partial p\).
Training loop Forward, zero_grad, backward, update; repeat.
zero_grad Required because gradients accumulate; leftover grads make a silently oversized step.

5 FAQ

Why \(\tanh\) and not ReLU? Because that is what the lecture uses, and it matches the neuron we differentiated by hand. The official micrograd repository uses ReLU in Neuron. The local derivative changes; the rest of the library does not.

Why only four examples? So you can watch them. The same loop trains a model on thousands of examples; the arithmetic does not change.

What learning rate should I use? Small enough not to bounce past the bottom, large enough not to crawl. \(0.1\) is comfortable on this toy. If the loss explodes, shrink \(\eta\).

Why is the last layer a single neuron? Because we want one number per example, a score we can compare to \(+1\) or \(-1\). A classification head with more classes would be a larger last layer and a different loss; the MLP wiring would be the same.

Where is this in the lecture? Building Neuron, Layer, and MLP from 1:43:55; the tiny dataset and the loss from 1:51:04; collecting parameters at 1:57:56; manual gradient descent and training from 2:01:12; the summary from 2:14:03. Official YouTube chapter markers, checked on the video page (30 November 2026).

6 See also

7 References

Back to top