flowchart LR x1((x1)) --> H1[hidden 4] x2((x2)) --> H1 x3((x3)) --> H1 H1 --> H2[hidden 4] H2 --> y((y))
Lab#DL01-4: From neuron to MLP and training
Lab
📘 Lab#DL01-4: 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).
The cells are live Python in the browser. There is no PyTorch here. One cell builds Neuron, Layer and MLP so the page stands alone; a later 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.
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.
1.1 Creating the class Neuron
A Neuron is the basic building block of a neural network. It takes inputs, multiplies each by a weight, adds a bias, and produces one output.
__init__(self, nin)
self.w = [Value(random.uniform(-1,1)) for _ in range(nin)]
self.b = Value(random.uniform(-1,1))ninis the number of inputs.Neuron(2)means two inputs.- It creates one random weight per input, each a
Valuebetween -1 and 1. Thefor _ in range(nin)loop just repeatsnintimes, and_means you don’t need the loop counter. - It also creates one random bias
b.
__call__(self, x)
This special method lets you call the object like a function. n(x) runs n.__call__(x).
Right now it’s a placeholder:
zip(self.w, x)pairs each weight with its input:(w1, 2.0)and(w2, 3.0). That’s the list you see printed.return 0.0is a dummy value, which is why the Out cell in the screenshot is0.0.
What it will compute
x1=2.0 ─ × w1 ─┐
(+ b) → output
x2=3.0 ─ × w2 ─┘
That’s w1*x1 + w2*x2 + b. Usually an activation function like tanh is then applied to the result.
Where it’s heading
The comment # w * x + b is the plan. The next step replaces the print and return 0.0 with a sum of wi * xi over the pairs, plus b. That is what the finished __call__ in the screenshot does, and then it applies tanh. The final code is in Final code below.
Since x holds plain floats, Value.__mul__ has to accept a plain number, not only another Value. The engine in this lab already does that: if other is not a Value, it is wrapped with Value(other), so wi * xi works.
1.2 Creating the classes Layer and MLP
A Layer is a list of neurons. They all see the same inputs and do not talk to each other. Each one produces its own output.
__init__(self, nin, nout)
self.neurons = [Neuron(nin) for _ in range(nout)]ninis how many inputs each neuron takes.noutis how many neurons sit in the layer.Layer(2, 3)means three neurons, each with two inputs. Thefor _ in range(nout)loop just repeatsnouttimes.
__call__(self, x)
outs = [n(x) for n in self.neurons]
return outs- It calls every neuron on the same
xand returns one output per neuron. - In the screenshot,
Layer(2, 3)onx = [2.0, 3.0]gives threeValues.
An MLP (multi-layer perceptron) is layers in a queue: the outputs of one layer become the inputs of the next.
__init__(self, nin, nouts)
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i+1]) for i in range(len(nouts))]ninis the number of inputs to the whole network.noutsis the size of each layer after that.szis the list of sizes, start to finish. ForMLP(3, [4, 4, 1])that list is 3, 4, 4, 1.- Each
Layer(sz[i], sz[i+1])is wired from one size to the next: 3 to 4, 4 to 4, then 4 to 1.
__call__(self, x)
This feeds x through each layer in turn.
3 → 4 → 4 → 1
Three inputs, two hidden layers of four neurons, then a single output. Try it with x = [2.0, 3.0, -1.0] and n = MLP(3, [4, 4, 1]). Three numbers go in; after the last layer you get one Value out. The exact number depends on the random weights. In the screenshot it is about -0.886.
1.3 Final code
This is the finished Neuron, Layer and MLP from the screenshots, sitting on the lab’s Value engine. A fixed random seed keeps the output stable.
The final code above is the walk-through from the video. The cell below is the same classes, with parameters() and zero_grad() added, which the training loop will need.
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.
1.4 The whole graph
draw_dot on the output lays out the whole expression, left to right. Every multiply, every add, and every tanh becomes a node. This graph has 126 Value boxes and 73 operation ovals — 199 pieces in all. Among the leaves are the 41 parameters: the weights and the biases. This is what backpropagation walks through, from the single output on the right back to those leaves.
At 1:50:35 in the lecture the picture is already huge, and this is only one tiny forward pass.
MLP(3, [4, 4, 1]) on \(x = [2.0, 3.0, -1.0]\), with random.seed(0). Our own render, using micrograd’s draw_dot (MIT Licence, Andrej Karpathy).MLP(3, [4, 4, 1]) on \(x = [2.0, 3.0, -1.0]\), with random.seed(0). Our own render, using micrograd’s draw_dot (MIT Licence, Andrej Karpathy).Open the full SVG or the PDF. Dark versions: SVG, PDF.
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.
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.py3 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
- Lab#DL01-3: Building micrograd
- The learning loop
- ANN: Model And Demos
- nn.py and train.py in the lab repo
7 References
- [1] Andrej Karpathy, The spelled-out intro to neural networks and backpropagation: building micrograd, 2022. Video in Neural Networks: Zero to Hero.
- [2] Andrej Karpathy, micrograd, GitHub, MIT Licence. https://github.com/karpathy/micrograd
- [3] Lab code: AlbertProfe/wikiml-zero-to-hero, tag
z2h-01. - [4] Notebook screenshots on this page are from Andrej Karpathy, The spelled-out intro to neural networks and backpropagation: building micrograd (Neural Networks: Zero to Hero, lecture 1).
- [5] The MLP computation graph is our own render of that same forward pass, using
draw_dotfrom karpathy/micrograd (MIT Licence).


![Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: class Neuron plus a new class Layer. Layer.__init__ creates self.neurons = [Neuron(nin) for _ in range(nout)]. __call__ returns [n(x) for n in self.neurons]. Layer(2, 3) on x = [2.0, 3.0] outputs three Values, about 0.831, 0.810 and 0.995.](../images/deep/dl01-4-karpathy-layer.png)
![Screenshot of a Jupyter cell from Karpathy’s micrograd lecture: class Neuron, class Layer, and a new class MLP. MLP.__init__ sets sz = [nin] + nouts and self.layers = [Layer(sz[i], sz[i+1]) for i in range(len(nouts))]. __call__ feeds x through each layer in turn. With x = [2.0, 3.0, -1.0], MLP(3, [4, 4, 1]) outputs [Value(data=-0.8862273530216576)].](../images/deep/dl01-4-karpathy-mlp.png)

