Interactive course · about 4 hours

Neural Networks

A neural network is a pile of multiplications with a rule for changing the numbers being multiplied. This course builds one from a single neuron, and works the changing out by hand. You will find a slope by moving a weight a little and watching the error move, and get an answer of minus 20. Then you will watch the fast method that real networks use produce minus 20 as well. You will fail, on purpose, to make one neuron switch a stairway light. Then fix it with two more. By the end you will have pushed nine slopes backwards through a network on paper and checked every one of them.

How this works

Every number on every step is worked out here and now, by one small network implementation shared across the whole course. Nothing is quoted from a book. Where the text says a slope is minus 20, something computed minus 20, and something else measured it a second way to check. The two methods disagreeing would be a defect, so a test beside this page compares them on random networks every time the course is changed. The charts answer your pointer too: rest it anywhere on a drawing and the values under it are read out. A marked point that answers to one slider can be dragged directly.

What you need to know first

Arithmetic, negative numbers, and the idea that a letter can stand for a number. There is no calculus here and no calculus notation. Where a textbook writes a derivative, this course changes a number a little, sees how much another number moved, and divides. That is the same thing done with a subtraction and a division.

Introduction to Machine Learning is the course before this one. It is not required. If you have not done it, the words weight, loss and learning rate are all defined again here the first time they appear.

The steps

Step 1

Multiply, add up, and compare against a threshold

A porch lamp that comes on when it is dark outside and somebody is standing at the door. Two facts go in, each of them a 1 or a 0. One decision comes out. Start with the smallest model that can represent that decision: a weighted sum followed by an activation function.

Give each incoming fact a number of its own, called a weight, and multiply the fact by its weight. Add the results together. Compare the total against a fixed number called the threshold, and answer 1 if the total reaches it and 0 if it does not. That is a neuron: some weights, one sum, one comparison. It is not a model of a brain cell and the name is a hopeful guess from the 1940s that stuck.

Why weights at all, when the facts are only 1 and 0?

Because the two facts do not matter equally, and the weights are where that gets said. A weight of 2 on darkness and 0.1 on somebody being there builds a lamp whose answer is mostly settled by the light. Swap them and it is mostly settled by the visitor. The same three lines of arithmetic become a different machine. Nothing about the structure changed.

A weight can be negative, which means the fact argues against the answer rather than for it. A burglar alarm might have a strongly negative weight on "the owner's phone is in the house". Negative weights are not an edge case, they are half the vocabulary.

Lab 1 · One neuron, three sliders
Try this firstDrag the threshold slider slowly down from 1.5 towards 0.5 and watch the answer column. The four rows are the four situations the lamp can be in. Each row prints its own total, so you can see exactly which rows cross the threshold and when.
Only the threshold moved, and the lamp changed its mind about what it is for. At 1.5 it needs both facts, because 1 on its own falls short. At 0.5 either fact is enough. The weights never changed. A neuron is not one rule, it is a family of rules, and picking numbers is how you choose which member of the family you get.
What is the threshold really doing?

Drawing a line. Think of the two facts as an across value and an up value, so the four situations are four corners of a square. The weighted total grows as you go in one direction, and the threshold picks out a straight line across the square. On one side of that line the total reaches it. On the other side it does not.

That is worth holding on to, because it is the exact limit of one neuron and Step 7 is about running into it. One neuron draws one straight line, and answers 1 on one side of it and 0 on the other. Nothing else.

Lab 2 · Build three neurons to order
Try this firstPress Either switch, then set the two weights and the threshold until all four rows say right. The verdict underneath grades what your neuron does, not what your numbers look like, so any set that behaves correctly passes. Then press the third task, which needs a negative weight.
Three different jobs, one machine, three sets of numbers. The third task is the interesting one. To build "only the first, never the second" the second weight has to be negative: the second fact must actively push the total back down below the threshold. Nothing about the neuron changed to allow that. A negative weight was always allowed, and it is the only thing that makes a fact count against an answer.
A neuron has weights of 3 and 3 and a threshold of 4. Somebody doubles both weights and doubles the threshold. What happens to the four answers?
Nothing changes. The neuron only ever asks whether the total reaches the threshold. Multiply the total and the threshold by the same number and the answer to that question is the same in all four rows. This is worth noticing early: the weights of a neuron are not unique, and many different sets of numbers give the identical machine. That is one reason reading the weights of a trained network tells you so little.
Step 2

Move one weight by hand until the error stops falling

A neuron with the threshold taken off, so that whatever the sum is, out it goes. That sounds like a downgrade and it is temporary: Step 9 puts a squashing rule back and explains why the hard threshold had to go first. For now the simplest possible machine, one input and one weight, and a job with real measurements behind it.

Pancakes and flour. One pancake took 3 spoons, two took 6, three took 9. The model is one number, the spoons per pancake, and the job is to find it. Multiply the number of pancakes by the weight and that is the answer the machine gives.

To know whether a weight is any good you need one number that says how wrong it is. Take each measurement, subtract what the machine said from what actually happened, multiply that miss by itself, add them all up and divide by how many there are. That number is the loss, and everything in this course is about pushing it down. Multiplying each miss by itself stops a miss above and a miss below cancelling each other out.

Lab 3 · Hunt for the weight by hand
Try this firstSet the slider to 1.0, press Try this value, then set it to 5.0 and press again. Two rows appear with the loss for each. Now try to beat both by narrowing in, and watch the column that says whether you improved on your last go. The line on the drawing is the weight: tilt it by dragging, or with the slider, and commit with the button.
You can get there, and you are being told almost nothing. The loss says how bad a weight is. It does not say which way to move, and it does not say how far. You worked both of those out by trying a value in each direction and comparing, which is two whole runs to learn one fact. A model with a million weights cannot afford that, and the next three steps are about the cheaper way.
Why divide by the number of measurements at the end?

So that the number means the same thing whatever size the data is. Without the division, adding a fourth measurement makes the loss bigger even if the model got better, simply because there is one more miss in the pile. Dividing turns a total into an average miss, and an average can be compared between a run on three measurements and a run on three hundred.

The squaring is a real choice rather than a formality. A miss of 10 costs 100 while a miss of 1 costs 1, so one large miss is treated as worse than ten small ones. This behaviour suits regression tasks where large errors should receive extra weight. Other tasks need a different loss, chosen to match the meaning of an error.

Lab 4 · Commit, then count
Try this firstLook at the three candidate weights and what each predicts, pick the one you think is least wrong, then press Count it up. Choose before you press. The point of the lab is the gap between your guess and the arithmetic.
Most people get this one right, and that is the problem. Your eye is good at separating things that differ a lot. It is useless at separating 2.98 from 3.01, and those are exactly the comparisons that fill the last nine tenths of training a model. One number that can be compared to another number is what makes the rest of this course possible.
Somebody tries a weight of 2 and gets a loss of 4.67, then tries 4 and gets 4.67 again. What have they learnt?
The bottom is between them. Two equal scores either side of a low point is a real clue, and pinning it to the middle is a good guess. Notice what it cost: two complete runs over all the measurements, to learn one fact about one weight. That is the expense the next two steps get rid of.
Step 3

Draw the error for every weight at once

The hunt in Step 2 was blind because you could only see one weight at a time. Nothing stops us working out the loss for every weight in a range and drawing the lot. No training procedure ever gets to see that picture, but it makes the next three steps obvious.

Along the bottom, the weight. Up the side, the loss for that weight. Because each miss is multiplied by itself, the shape is a bowl: steep far out on either side, and flatter as it approaches the lowest point. The lowest point is the answer.

Lab 5 · Walk along the curve
Try this firstDrag the weight slider from one end to the other slowly, or grab the marker on the curve and pull it. Either control moves the other. The pills underneath print the loss at that exact weight, along with the lowest point the curve reaches.
The bowl has one bottom, and it is at a weight of 3. Three spoons per pancake fits all three measurements exactly, so the loss there reaches zero rather than merely getting small. That is unusual and it happens here because the numbers were chosen to be checkable on paper. What matters is the shape, and the shape is what the next step exploits: from anywhere on a bowl, the direction downhill is a fact you can measure locally.
Why is the curve a bowl rather than a V?

Because of the squaring. If the loss were the plain size of each miss, doubling how wrong the weight is would double the loss. The picture would be two straight lines meeting in a sharp point. Squaring means doubling how wrong you are makes the loss four times worse. That is a curve.

The curve matters more than it sounds. A sharp point has no slope at the bottom, and the whole method coming up reads the slope to decide where to go. A smooth bowl gets flatter as you approach the bottom, so the steps get smaller on their own as you arrive. Nobody has to arrange that.

Lab 6 · Change a measurement
Try this firstDrag the third reading from 9 spoons up to about 15. The whole curve reshapes, and the marked bottom slides to the right and lifts away from the floor. Watch the second pill, which prints the best loss anything can now reach.
The bottom is a compromise, not a solution. Once the three readings stop agreeing, no single weight fits all of them, and the lowest point of the bowl is the best available failure rather than a success. That is the normal case with real measurements, and it changes nothing about the method. The bowl is still a bowl and its bottom is still what training goes looking for.
A model has 300 weights instead of one. Why can nobody draw its loss curve and simply look for the bottom?
There are too many directions. With one weight you can try a hundred values and look. With two you can try ten thousand and draw a map. With three hundred, trying even ten values each means more combinations than there are atoms in the observable universe. The picture in this step is a luxury of having exactly one weight. Everything from Step 4 on works without it, using only what a machine standing at one point can measure from where it stands.
Step 4

Measure a slope by nudging the weight

A machine at one point on the bowl cannot see the picture. What it can do is ask for the loss, change a weight by a small amount, and ask again. Two answers and a subtraction estimate which way the loss decreases. The formal name for this rate of change is a derivative.

Take how much the loss moved and divide it by how much you moved the weight. If the loss went down when the weight went up, the answer is negative, and negative means keep going up. The size says how steep the ground is. That single number is the slope of the loss for that weight.

Here is one measurement to work through with a pencil, and the lab below computes the same numbers so you can check yourself. Two pancakes took 6 spoons. The weight is currently set to half a spoon per pancake, so the machine says 1 spoon. The miss is 1 minus 6, which is minus 5 and the loss is minus 5 times minus 5, which is 25.

How can dividing by a nudge give a slope?

The same way it does on a hill. Walk one metre east and note that you rose three metres: the ground rises 3 metres per metre, and you divided 3 by 1 to get it. Here you walk 0.1 in the weight and note the loss fell by 1.96. So the loss falls 19.6 per unit of weight, because minus 1.96 divided by 0.1 is minus 19.6.

The awkward part is that the ground bends while you are walking on it. Over a nudge of 0.1 you measure the average steepness across that whole stretch, not the steepness at the exact place you were standing. Make the nudge smaller and the two get closer, which is what the second lab is about.

Lab 7 · The nudge, line by line
Try this firstLeave both sliders where they are and read the table from the top. It should say the loss here is 25 and the measured slope is minus 19.6, which are the numbers to check against your pencil. Then drag the nudge slider left and watch the last row creep towards minus 20. Both dots on the bowl drag too: the standing point is the weight, and the far dot is the nudge.
Minus 19.6 by measurement, minus 20 by the rule. The rule, which Step 10 works out from scratch, is twice the miss times the input: twice minus 5 times 2 is minus 20. The measurement is close and not equal, and the difference is the curve bending across the nudge. Both numbers are computed here, neither is quoted, and the whole of backpropagation is a way of getting the second one without doing the first.
Lab 8 · Shrink the nudge
Try this firstPress Shrink the nudge seven times, once for each row. Each row uses a smaller nudge than the one above. Watch the last column, which is how far the measured answer is from the exact one. Then compare the second and third columns against each other.
The middle column is only ever approximate. The one beside it is exact. Looking a nudge each way and dividing by twice the nudge cancels the bending, and on a curve built from squares it lands on minus 20 at every size tried. That trick is how anybody checks a network: work the slopes out the fast way, then measure a few of them the slow way, and see whether the two agree. Step 11 does exactly that on a real network.
A network has one million weights. Somebody suggests finding every slope by nudging each weight in turn. Why is that impractical even though it works?
The bill. Measuring one slope costs one extra pass over the data. Measuring a million slopes costs a million extra passes, and a round of training would take longer than the rest of the year. Backpropagation gets all one million slopes for the cost of roughly one extra pass, which is the entire reason anyone uses it. Nudging survives as the thing you check it against, on a handful of weights, which is what Step 11 does.
Step 5

Step downhill, and pick how far to step

The slope says which way is down. It does not say how far to go, and it cannot: it is the steepness right where you are standing. It says nothing reliable about how long the ground stays that way. So somebody chooses a fixed number, multiplies the slope by it, and moves the weight by that much in the downhill direction.

That fixed number is the learning rate. Nothing measures it and nothing works it out. It is chosen, usually by trying a few. Repeating the whole business, measure the slope and take a step, over and over, is called gradient descent. Almost every model you have heard of is trained by some version of it.

Why does the step get smaller near the bottom on its own?

Because the step is the slope multiplied by the rate, and the slope is small where the bowl is flat. Far out the ground is steep, the slope is large and the step is long. Close in the ground is nearly level, the slope is nearly zero and the step is tiny. Nobody arranged that and no rule has to detect the arrival.

It also means a flat place stops the procedure dead whether or not it is the bottom. A wide flat shelf halfway up a hill gives slopes near zero, so the steps become tiny and training appears to have finished. Plateaus, saddle points, and saturated activations can all produce this symptom. Step 10 examines the activation-related case.

Lab 9 · One step at a time
Try this firstPress One step four or five times and read the pills after each press. They print the weight now, the slope there, and the move that slope buys at the current rate. Then press Ten steps and watch the trail of markers bunch up as it arrives.
The markers crowd together near the bottom without anything telling them to. Each step is the slope times the rate, and the slope shrinks as the ground levels off. Now push the rate slider up past 0.21 and press One step repeatedly. The weight starts landing on the far side of the bottom each time, and past about 0.214 each landing is further out than the last.
Lab 10 · Four rates, forty steps
Try this firstBefore pressing anything, decide which of the four rates will end up closest to a weight of 3. Then press Run all four for 40 steps. Four loss curves are drawn on the same axes and a table gives the ending weight for each.
Same bowl, same starting weight, four outcomes. Nothing about the model or the measurements differed between the run that arrived and the run that left the chart. Only the step size did. A loss that climbs steadily, often doubling, is the signature of a rate that is too large, and dividing it by ten is the first thing to try.
A run oscillates: the weight lands above the bottom, then below, then above, but each time it is closer than the last. Is anything wrong?
Nothing is broken, and it is wasteful. Each step overshoots the bottom but by less than it started out, so the distance still shrinks every time. It arrives, having travelled much further than it needed to. Push the rate up a little more and each overshoot becomes larger than the last, at which point it never arrives at all. The boundary between those two behaviours is a property of the bowl, not of the model.
Step 6

Two weights make a surface instead of a curve

One weight gives a curve. Two weights give a landscape: the loss is a height above a flat map whose across direction is the first weight and whose up direction is the second. The bowl becomes a valley with a lowest point somewhere in it.

Pancakes and waffles now, each taking its own amount of flour. Four batches were measured, and three spoons a pancake with five a waffle fits all four exactly. Nothing tells the machine that pair, and it starts somewhere else.

The slope becomes two slopes: nudge the first weight with the second held still and divide, then nudge the second with the first held still. That pair of numbers is called the gradient, which is only a name for the list of slopes with one entry per weight. A network with a million weights has a gradient a million numbers long, and it is still just that list.

Lab 11 · Roll down the valley
Try this firstPress Run 60 steps and look at the shape of the path, not just where it ends. Darker shading is a larger loss, and the ring marked bottom is the answer. Then click anywhere on the map to start somewhere else and run it again.
The path curves rather than heading straight for the ring. Steepest is not the same as shortest. The valley falls away faster in one direction than the other. So the steepest way down from any given point points across the valley rather than along it, and the run has to correct as it goes. With two weights this is a curiosity. With a million it is why training takes as long as it does.
Could you not just work out the best weights directly?

For this model, yes. When the neuron passes its sum straight out and the loss is built from squares, a formula exists. It takes the measurements and hands back the best weights in one go. No stepping, and no rate to choose. It has existed since the early 1800s, and if your problem really is this shape then use it.

The reason to learn the slow way is that the formula stops existing the moment a squashing rule appears in the middle, which is Step 8. Rolling downhill keeps working when the model gets complicated, which is why it is worth understanding on something small enough to watch. Safe to skip: nothing later depends on this note.

Lab 12 · Two nudges, one arrow
Try this firstLeave both sliders at 0 and read the table: the two measured slopes should be minus 31 and minus 21. Those are whole numbers you can check on paper. Then drag the pancake slider to 3.0 and watch its row of the table fall towards zero while the arrow swings round.
Each number in the gradient is one nudge of one weight. There is nothing more to a gradient than that, however many weights there are. The arrow points the opposite way to the pair, because the pair points uphill and you want down. When a slope reaches zero, no small change to that weight improves anything for now, and the arrow lies flat in that direction while still pointing hard in the other.
At one point the two slopes are minus 30 and minus 1. What does that tell you about which weight to change?
Both up, and the first by thirty times as much. Gradient descent multiplies each slope by the same learning rate. So a weight with a large slope takes a large step, and one with a small slope takes a small one, automatically. The second weight is not finished. Once the first has settled and its slope has shrunk, the second is what is left, and this is exactly the long thin valley the last lab drew.
Step 7

One neuron cannot do the stairway light

A light on a staircase with a switch at the top and a switch at the bottom. Either switch changes the light, whatever the other one is doing. So the lamp is on when exactly one switch is up, and off when both are up or both are down. This is the XOR pattern. A single linear boundary cannot separate its two classes, but a network with a hidden layer can.

Step 1 built the both-switches rule and the either-switch rule out of one neuron without much trouble. This looks like a third rule of the same kind. It is not, and the difference is worth meeting by running into it rather than being told.

Lab 13 · Try to build it
Try this firstGet the two middle rows right, so that one switch up lights the lamp. That part is easy. Now, without breaking those two, get the bottom row off as well: both switches up should leave the lamp dark. The fence on the square drags bodily, and the sliders set its angle. The pill marked "your best so far" keeps the lowest loss you have reached.
Getting three rows is easy and the fourth undoes one of them. Look at the totals column while you try. Making either switch on its own clear the threshold makes both switches together clear it by even more, because the total is a sum and both weights are contributing. There is no way to add two numbers and have the sum be large for each one alone and small for the pair. Then press Let the machine train it and watch it fail in a more organised way.
Why is this one different from the first two?

Go back to the square from Step 1, with the four situations at four corners. A neuron draws one straight line and answers one way on each side of it. For the both-switches rule you can draw a line with the top-right corner alone on one side. For either-switch you can draw one with the bottom-left corner alone. Both work.

For the stairway light the two corners that need a 1 are diagonally opposite each other, and so are the two that need a 0. No straight line separates one diagonal pair from the other. Try it on paper with two crosses and two circles at the corners of a square, crosses on one diagonal. It is not that it is hard. It cannot be done.

Lab 14 · Search the whole range
Try this firstWith the stairway light selected, press Try every setting on the grid. It builds 15,625 different neurons, scores every one, and keeps the best. Then switch to either of the other two tasks and search again with the same range.
The best of 15,625 is a neuron with all three numbers at zero. It answers exactly one half to every row, which scores 0.25 and is the least bad thing available: hedging on all four beats getting two right and two badly wrong. The other two tasks are solved outright by the same search over the same range, so the difficulty is in the job and not in the searching. This is a limit, not a tuning problem, and it stopped the field for most of the 1970s.
Someone says the search just did not look hard enough, and that a wider range of weights would find an answer. What is wrong with that?
A wider range is the same neurons. Step 1's quiz showed that multiplying every weight and the threshold by the same number leaves all four answers unchanged. So the range is not what limits the search. The pattern of answers a single neuron can produce is fixed by the geometry, and no straight line at any scale separates the two diagonals of a square. The fix has to change the machine, not the numbers in it.
Step 8

Two neurons in the middle, and the stairway light works

Step 7 built the both-switches rule and the either-switch rule easily, and failed on the stairway light. But the stairway light is exactly "either switch is up, and not both", which is those two easy rules combined. So build both of the easy ones, and give their answers to a third neuron.

A row of neurons all fed by the same inputs is a layer. A layer whose answers nobody outside the network ever reads, because they only feed the next layer, is a hidden layer. Two hidden neurons and one output neuron is nine numbers in total: six weights and three biases. A bias is the threshold moved to the other side of the comparison. Instead of asking whether the total reaches 1.5, the neuron adds minus 1.5 to the total and asks whether the result reaches zero. Same machine, tidier arithmetic.

Where did the hard threshold go?

It has been replaced by the sigmoid, a smooth S-shaped rule that squashes any total into a number between 0 and 1. A large positive total comes out near 1, a large negative one near 0, and zero comes out at exactly a half. It is the hard threshold with the cliff smoothed into a slope.

The reason is Step 4. A hard threshold answers the same 0 or the same 1 however much you nudge a weight, so every measured slope is zero and there is nothing to roll down. The sigmoid always has some slope, which is what makes the network trainable at all. Step 9 is about that trade and about what else you might use instead.

Lab 15 · Step through the four rows
Try this firstPress each of the four switch buttons in turn and watch the two hidden circles fill and empty. The number inside each circle is what that neuron is putting out, and the table underneath names what each one has been built to do. These nine weights were set by hand, not trained.
Hidden 1 is the either-switch rule and hidden 2 is both-switches. Both of those a single neuron can do, and Step 7 proved it. The output neuron adds twenty times the first and subtracts twenty times the second, which is "either, but not both". The thing one neuron could not do has been assembled from two things it could. Notice that the output neuron never sees the switches at all: it sees two numbers between 0 and 1, and has no idea what they came from.
Lab 16 · Let it find its own weights
Try this firstPress Train and watch both panels. The shading on the left is what the network answers for every setting between fully down and fully up, and the curve on the right is the loss falling. Then set the hidden neurons slider to 2 and train a few times from fresh random weights.
Nobody chose the twenty and the minus thirty this time. Every one of the nine numbers started random, and the only instruction was to move each one against its own slope. With two hidden neurons some starting positions walk into a dip that is not the bottom, get three rows right and cannot fix the fourth without going uphill first. That is the ordinary way this fails and the ordinary fix is to start somewhere else, which is why the Fresh random weights button exists in real tools too.
The trained network solves the stairway light, but its two hidden neurons are doing something quite different from the hand-built pair. How is that possible?
Nothing asks the hidden neurons to mean anything. The loss is computed from the final answer only. Every arrangement of hidden weights that lets the output neuron finish the job scores identically, so training has no reason to prefer the tidy one a person would design. This is the honest core of why explaining a trained network is hard. The readable version and the found version are both correct, and there is no force pushing towards the readable one.
Step 9

Threshold, sigmoid and ReLU

The rule a neuron applies to its total before passing it on is its activation. Three are worth knowing, and the differences between them are practical rather than theoretical. They decide whether a network can be trained at all, and how well it trains once it can.

The hard threshold from Step 1 answers 0 or 1 and nothing between. The sigmoid from Step 8 is the same shape with the cliff smoothed out. ReLU is the plainest of the three: if the total is negative answer 0, otherwise answer the total itself. ReLU stands for rectified linear unit. It remains a common default for hidden layers because it is cheap and does not saturate on positive inputs, although other activations can work better for particular architectures.

Lab 17 · The three rules and their slopes
Try this firstPress threshold and read the two slope pills. Both say zero. Then press sigmoid and press ReLU, watching the dashed line, which is the slope measured by nudging at every point along the solid one.
A slope of zero everywhere is why the hard threshold cannot be trained. Nudge any weight feeding a threshold neuron and its answer does not move, so the loss does not move, so the measurement says stay exactly where you are. Not "move slowly": stay. The sigmoid fixes that and introduces its own problem, which is that its slope fades to nearly nothing past about five either way. ReLU has a slope of exactly 1 wherever it is positive, which is why it survived.
If ReLU is a straight line for positive totals, is it not a straight line?

It is two straight lines with a corner where they meet, and the corner is the whole point. A single straight line through the origin is a multiplication and can be absorbed into the weights either side of it, which is what the next lab demonstrates. A corner cannot be absorbed into anything, because whether you are on the flat part or the sloping part depends on the input.

That is the minimum requirement for an activation: it has to be something other than a multiply. ReLU is close to the cheapest thing that qualifies, which is a large part of why it won. Safe to skip: nothing later needs this note.

Lab 18 · A stack of straight lines
Try this firstWith no squashing selected, compare the two middle columns row by row. The left one is a network with two hidden layers of three neurons. The right one is a single neuron whose two weights were worked out by multiplying the deep network's weight tables together. Then press sigmoid squashing.
Twenty-five numbers doing the work of three. With no squashing anywhere, a weighted sum of weighted sums is a weighted sum, so the whole stack flattens to one neuron and every extra layer is decoration. This is why an activation is not an optional refinement. Without something that is not a multiply between the layers, depth buys exactly nothing, and a hundred layers has precisely the power of one.
A network uses ReLU throughout. During training one hidden neuron's total drifts negative for every single example in the data. What happens to that neuron from then on?
It is dead, and nothing in the method revives it. ReLU has a slope of exactly zero on the flat part, and Step 10 shows that a slope of zero anywhere in a chain makes the whole product zero. So every weight feeding that neuron measures a slope of zero, moves by nothing, and the total stays negative for ever. It has a name, the dying ReLU, and it is the price of the flat part that made ReLU attractive in the first place.
Step 10

Multiply the links to get the whole slope

A weight in the middle of a network does not touch the loss. It changes a sum, the sum changes what a neuron puts out, that changes the next sum, and eventually something changes the loss. To find out how much the weight moves the loss you can follow the chain link by link.

Each link is a slope of exactly the kind Step 4 measured: nudge this, watch that, divide. The rule is that the slopes multiply. Suppose nudging the weight moves the sum by 2 for every 1, and nudging the sum moves the output by 0.2 for every 1. Then nudging the weight moves the output by 0.4 for every 1. Two steps of 2 and 0.2 make one step of 0.4. That is the chain rule, and in this course it is a multiplication and nothing more.

Lab 19 · Three links, measured separately
Try this firstRead the last two rows of the table against each other. One is the three link slopes multiplied together; the other is a single nudge of the weight with the loss watched at the far end and everything in between ignored. Then drag either slider and confirm they stay equal.
The product of the parts equals the whole, at every slider position. That is why nobody has to nudge each weight of a real network. Measure each link once, and the slope for any weight is the product of the links along its path back to the loss. Link 1 is always simply the input, because the sum contains the weight multiplied by it, so a weight that multiplied a big number gets a big slope.
Why do the links multiply rather than add?

Because each one is a rate, not an amount. Metres per step and pence per metre multiply to give pence per step; adding them would be nonsense with the wrong units. It is the same arrangement here. Loss moved per unit of output, times output moved per unit of sum, times sum moved per unit of weight, gives loss moved per unit of weight.

A quick check that the multiplication is the right one: if any single link is zero, the whole thing is zero. That is right. A weight whose sum has no effect on the output has no effect on the loss either, however strongly the loss depends on that output.

Lab 20 · Break one link
Try this firstDrag the slider, or the dot on the sigmoid itself, until the sum is past 8. Watch the middle bar shrink to nothing and the total bar go with it. The number beside each bar is its own slope, so you can read exactly which link collapsed and by how much.
One dead link kills the product, and the other two cannot make up for it. Far out on the sigmoid a nudge to the sum barely moves the output at all. So the middle link is nearly zero, and the weight gets almost no instruction however wrong the answer is. This is the vanishing gradient. In a deep network it is worse than it looks here. Ten sigmoid layers means ten of these links multiplied together, and ten numbers under a quarter come to about one in a million.
A weight sits four layers deep. Three of its four links measure about 0.5 and one measures about 0.001. Roughly how large is its slope?
About 0.000125, and the small link is in charge. Three halvings give 0.125, and multiplying by 0.001 gives 0.000125. Three perfectly healthy links cannot rescue one dead one, and that is the whole difficulty with deep networks. It is the reason ReLU, with its slope of exactly 1 on the positive side, replaced the sigmoid in hidden layers.
Step 11

Backpropagation on nine numbers

Everything needed is now in place. Run the network forwards and keep every intermediate value. Work out how much the loss moves per unit of change at the output. Then walk backwards, and at each neuron multiply by the links from Step 10 to get how much the loss moves per unit of change at that neuron. That is backpropagation, and it is the chain rule applied in a particular order so that nothing is computed twice.

One quantity does the travelling. For a given neuron, how much the loss moves per unit of change in the sum arriving at it is called that neuron's delta. Once you have a neuron's delta, the slope of every weight feeding it is the delta multiplied by whatever that weight was multiplying on the way in. One multiplication per weight, and that is the whole saving.

Lab 21 · One number at a time
Try this firstPress Next number nine times, reading the new table row and the sentence underneath at each press. The weights are fixed and printed on the diagram, the inputs are 1 and 0, and the wanted answer is 1. Every value has a column saying where it came from, so each one can be checked with a calculator.
Nine slopes, and none of them needed the loss recomputed. One forward pass and one backward pass produced every slope in the network. Compare that with Step 4, where each slope cost a full extra pass. Notice the weight that multiplied the second input: its slope is exactly zero, because that input was zero. However wrong the answer was, that particular weight is not to blame this time.
Why does only the delta travel backwards, and not everything?

Because every weight feeding one neuron shares the same rest-of-the-journey. Whatever happens between that neuron's sum and the loss is identical for all of them, and that shared part is exactly what the delta is. Working it out once per neuron rather than once per weight is where the saving lives.

The size of the saving is the reason large networks exist. Nudging every weight in turn costs one pass over the data per weight. Backpropagation obtains all parameter gradients with a reverse pass whose cost is on the same order as the forward computation. Modern systems add better hardware, optimisers, data pipelines, and architectures around that core calculation.

Lab 22 · Check it against the nudge
Try this firstPress Fresh random weights a few times and watch the worst-gap pill. Every row compares backpropagation's answer for one weight against the answer from moving that weight a little each way. Then drag the nudge slider all the way to the left and watch the check fall apart.
Two methods, no shared arithmetic, agreeing to eight or nine decimal places. That is the gradient check, and it is what everybody who implements backpropagation runs before believing their own code. Making the nudge too small breaks it, because subtracting two nearly identical losses leaves mostly rounding error. Too large and the curve bends across the nudge. The check works in the valley between the two, which is why the slider has a middle rather than a best end.
Someone writes their own backpropagation, and the gradient check shows a relative gap of about 0.3 on one weight and near zero on all the others. What is the most likely explanation?
The code is wrong on that weight's path. A gradient check that fails on one weight and passes on all the others is pointing straight at the term that computes that weight's slope. Look there for a wrong sign, a missing activation slope, or a wrong index. This is the whole value of the check. Without it a network with one wrong gradient still trains, just worse, and there is nothing on the screen to tell you which of the two you have.
Step 12

What another layer buys, and what it costs

Everything so far has had at most one hidden layer. The obvious question is what a second one is for, and the obvious answer, that it makes the network better, is not true in any simple way. The real answer is easier to see with one input than two. So this step uses a network with a single number going in and a single number coming out, and draws its whole answer as a curve.

Wire two ReLU neurons so that together they fold the line in half. The output climbs for the first half of the input range and comes back down for the second. Feed that into another pair wired the same way and the fold is applied to something already folded, so the number of straight pieces doubles. A single layer of many neurons cannot do this, because each of its neurons puts one bend in the line and the bends simply add up.

Lab 23 · Folding, layer by layer
Try this firstDrag the layers slider from 1 up to 5, one notch at a time, and read the two piece-count pills at each notch. The solid line is the deep network; the dashed line is a single hidden layer with the same total number of neurons, wired for the most bends it can manage. Neither is trained, both are just wired up, and the crossover happens at three layers.
Two, four, eight, sixteen, thirty two. Each layer doubles the pieces, because it folds a shape that is already folded. A single layer of the same neurons can only add one bend per neuron. Ten neurons in one layer is at most eleven pieces, while five layers of two is thirty two. The dashed line is drawn with its bends spaced out deliberately, which is the best a single layer can do; press the other button and it does worse, never better. This is the honest mathematical case for depth, and it is about what a shape can be, not about what training will find.
Why does folding double the pieces instead of adding to them?

Fold a strip of paper in half and draw a line across it. Unfold it and there are two lines. Fold it twice and draw once and there are four. Each fold copies whatever comes after it onto both halves, so the count doubles rather than growing by one.

The layers work the same way. The first pair maps two different parts of the input range onto the same output range, so whatever the layers above do to that range, they do to both parts. A wide single layer has no such copying: each neuron puts one bend somewhere and the bends just accumulate.

Lab 24 · The same weights, two shapes
Try this firstPress Train both, twelve times each and wait a second or two. One hidden layer of six, or two hidden layers of three, on the same dots at the same learning rate. Both shapes have exactly twenty-five adjustable numbers. Read the last column of the table before the others.
The middling losses are too close to call and the failure counts are not. Twelve runs cannot separate the two on loss, and pretending otherwise would be reading noise. What does hold up is that the deeper shape fails to get going far more often. One more layer is one more link in every chain. A run whose neurons all switch off early has no slope left to recover with. Depth earns its keep on problems with structure worth reusing and on data far larger than eighty dots in a square.
Lab 23 shows depth reaching shapes that width cannot, and Lab 24 shows the deeper network training worse. How can both be true?
Reachable and findable are different questions. Lab 23 sets the weights by hand and asks what the network can express. Lab 24 starts from random weights and asks what rolling downhill actually gets to. A shape can be perfectly expressible and still sit behind a hill that no run climbs. Most of the practical work in this field is about closing that gap, with better starting weights, better activations and better step rules. Expressiveness stopped being the bottleneck decades ago.
Step 13

Train a network of your own choosing

Nothing here is graded and several settings can work. Choose one of four datasets, then select the network shape, activation, and learning rate. The lab uses the forward pass from Step 8, backpropagated gradients from Step 11, and the parameter update from Step 5.

Some things worth trying, each of which teaches something the earlier steps only asserted.

What is the shading, and what does the percentage mean?

The shading is what the network answers at every point of the square, not only at the dots. One shade for answers above a half and another for answers below, with the strength showing how confident it is. The training dots are drawn on top: a filled disc for the class that should answer 1, an open ring for the class that should answer 0.

The percentage is the share of training dots that land on the correct side of a half. It is a different number from the loss, and it moves in jumps rather than smoothly. A dot that goes from 0.49 to 0.51 changes the percentage but barely changes the loss. Training pushes the loss down; the percentage is what a person actually wanted and the gap between those two is a subject of its own.

Lab 25 · Your own network
Try this firstPress Train 600 rounds on the settings it opens with, and watch the shading close around the inner blob. Then set the first hidden layer to 1 neuron and train again: one neuron draws one straight fence and cannot enclose anything. Then put it back to 6 and set the learning rate to 0.01 to watch the same network crawl.
Three failures worth causing on purpose. Too few neurons and no amount of training helps, because the shape it needs is not reachable. Too small a rate and it would get there eventually but not today. Sigmoid on the checkerboard stalls where ReLU on the same shape keeps going. That is the vanishing gradient from Step 10 showing up in a picture rather than in a table of link slopes.
A run reaches a loss of 0.002 and gets 100% of the dots right. What does that tell you about how it will do on dots it has never seen?
Nothing at all. A score measured on the data a model was fitted to answers a different question from the one you are asking. It might have found the real shape or it might have wrapped itself tightly around these eighty dots, and both look identical here. The fix is to hold some dots back and never train on them. That is what the Making Training Work course is about, and it is the most common way a model that looks finished turns out not to be.
Where foundation models fit

Current language and vision models contain far more layers and weights than the networks in these labs. Transformers add attention, and image models may work with patches instead of only convolutional filters. Their parameters are still fitted by a forward pass, a loss, backpropagation and an optimiser.

Most projects do not train all those weights again. They may keep the base model fixed, train a small output head, or add low-rank adapter weights. The choice changes cost and flexibility, not the need for held-out evaluation. The next steps are Making Training Work, Language Models, and Computer Vision.

Backpropagation checkpoint

  • Write down what a neuron computes, in three lines, and say what each weight and the bias are for.
  • Turn a set of measurements into a loss, and explain why the misses are multiplied by themselves before being added.
  • Measure the slope of a loss against a weight by nudging, and say why looking both ways is more accurate than looking one way.
  • Choose a learning rate by reading the shape of a loss curve, and recognise a rate that is too large from the shape alone.
  • Say why a single neuron cannot switch a stairway light, and draw the reason on a square.
  • Explain what a hidden layer adds, and why nothing forces its neurons to mean anything a person would recognise.
  • Pick between a threshold, a sigmoid and a ReLU for a job, and give the slope-based reason rather than a preference.
  • Work the chain rule as a product of measured slopes, without calculus notation.
  • Follow backpropagation through a small network number by number, and say what a delta is.
  • Run a gradient check on somebody's implementation and know what a single failing weight means.
  • Say what depth buys in principle, what it costs in practice, and why those two answers point in opposite directions.

Courses used so far

  • Making Training Work. The model that scores perfectly and is useless. Held-out data, leakage, imbalance, and the metrics that survive contact with a real problem.
  • How a Language Model Guesses. The same forward pass and the same backpropagation, with words turned into lists of numbers and a layer that scores which earlier words each new word should be built from.
  • A Model on a Microcontroller. What happens to these weights when they have to fit in 64 kilobytes and answer in ten milliseconds, on a chip with no floating point.
  • Introduction to Machine Learning. If any of the words here were new, that course builds the same ideas from dots you place yourself, with no network in sight until near the end.
Step 14

Turn a picture into numbers the network can eat

Every lab so far fed the network two numbers at most: two switches, or where a dot sits in a square. Real jobs start from a photograph, a recording, or a sentence, and a network cannot eat any of those. It eats lists of numbers and nothing else, so the first move of every real system is to turn its input into numbers, honestly and completely.

A picture gives its numbers up easily. Cut it into a grid of tiny squares, called pixels, and write down how much ink is in each one. A grid of seven rows of seven is a list of forty-nine numbers; that list is the picture, and nothing about it is lost. Words get numbers from a table instead: each word is assigned its own list of numbers, and those lists are adjusted during training exactly the way weights are. Sound is a list of air pressure readings, thousands per second. Whatever went in, the network sees a list of numbers, and everything this course has built so far applies to it unchanged.

Does the network know it is looking at a picture?

No. The forty-nine numbers arrive as one long row, always in the same order, and the network learns which positions tend to matter. The fact that pixel 8 sits directly under pixel 1 is something you can see in the grid and the network cannot. That neighbourly arrangement is real knowledge about pictures. The plain list throws it away.

Keep that loss in mind. A few steps ahead, convolution puts exactly that knowledge back. It does not tell the network where each pixel was. It wires the layer so that neighbours are treated as neighbours.

Lab 26 · A picture is a grid of numbers
Try this firstPress the two picture buttons and watch the row of numbers under the grid change with the drawing. Then drag the ink cut-off slider and watch cells flip between counting as ink and counting as paper. Then paint: press a cell, or sweep across several, and watch the list change as you draw. The pill counts how many of the forty-nine numbers currently clear the cut-off.
The grid and the row underneath it are the same thing. You see a shape because your eye lays the numbers out in rows. The network is handed the row and never the layout, so a pattern of neighbouring pixels is, to it, a pattern of positions that are forty-nine apart or one apart. It can still learn the job. It just starts without something you were given for free.
A photograph is 100 pixels wide and 100 pixels tall. How many numbers does the plain list version hand the network?
10,000, one per pixel. Multiply the sides, because pixels fill the area. This is why real inputs get big fast: a modest photo is tens of thousands of numbers, and a neuron reading all of them needs that many weights. One neuron per interesting pattern, each with ten thousand weights, is a heavy bill. The convolution step ahead is about paying far less for the same watching.
Step 15

Train on a handful of examples at a time

Every training run so far measured its slopes on the whole dataset before every step, because the whole dataset was three pancake batches or eighty dots. A real dataset can be millions of photographs. Reading every one of them to earn one small step would make each step cost hours. The intermediate numbers for millions of examples may not even fit in the machine.

So training deals the data into a batch: a small handful of examples, drawn at random, used to measure an approximate gradient. The approximation is noisy. Eight photographs might happen to be eight odd ones, and the step they suggest points slightly the wrong way. The next handful errs in some other direction, and on average the walk still heads downhill. Small batches buy many cheap, scattered steps, while large batches buy fewer, smoother, dearer ones. One pass through the whole pile, however it was dealt, is called an epoch.

Why not share the batches across many machines?

That is exactly what large training runs do. Several machines each take their own batch, measure slopes on it, and average their answers before anyone steps. The averaging has to travel over wires, and the wires are slower than the arithmetic, so the machines spend part of every step waiting on each other.

There is a subtler cost. Averaging across enough machines makes the combined batch enormous, and an enormous batch is very smooth. Some of the scatter in small batches turns out to be useful, jiggling the walk out of shallow dips. So giant batches often need adjustments of their own to train as well.

Lab 27 · Average a handful of slopes
Try this firstDrag the batch size from 1 up to 8 and watch the bars settle towards the dashed line. Each bar is the slope one batch would report. The dashed line is the answer the whole set gives. The pills count how far the bars scatter and how many updates one pass through 800 examples would make.
Smoothness and cost move together. At a batch of 1 the bars disagree loudly, and one pass through the pile makes 800 cheap, scattered updates. At 8 the bars agree closely, and the same pass makes 100 careful ones. Neither end is simply right. The working range is chosen by trying, like the learning rate in Step 5, and the two settings lean on each other.
A training set has 800 examples. The batch size is doubled from 8 to 16. What changes immediately?
Half the updates, each one smoother. The batch size only changes how the slopes are estimated and how often a step is taken. That is still a real change: fewer, smoother steps often want a different learning rate. The two settings are usually reported together, so someone else can repeat the run.
Step 16

Keep the signal alive through a deep stack

A message whispered through twenty children arrives mangled, because each child changes it a little and the changes compound. A deep network plays whispers with numbers. If each layer shrinks what passes through to nine tenths of its size, twenty layers pass on about an eighth of it. If each layer grows the signal slightly, twenty layers make it enormous. Either way, the far end works with rubbish.

The slopes travelling backwards suffer the same compounding, which Step 10 met as the vanishing gradient. The defences have names worth knowing. Careful initialisation deals the starting weights at a size chosen so that a layer neither shrinks nor swells its signal on average. Normalisation re-centres and re-scales the numbers between layers while training runs. A residual connection adds a short cut: a layer's input is added straight onto its output. The signal, and the slope coming back, both get a route that skips the risky part entirely.

What the residual short cut does to the chain of links

Step 10 showed that a slope reaching a deep weight is a product of links, and one feeble link starves the product. A residual connection changes the arithmetic: the slope now flows through the layer and around it, so the two contributions add. The around-route is an unweighted copy, a link of exactly 1.

A product with a guaranteed 1 added alongside it cannot be starved to nothing by one bad layer. That is the whole trick, and it is a large part of why networks hundreds of layers deep became trainable at all.

Lab 28 · Compound one layer's gain through depth
Try this firstSet the per-layer gain to 0.9, then drag the depth up and watch the curve sink towards the floor. Then press residual and watch the same gain arrive at the far end alive. Try a gain of 1.1 as well, and read which pill turns hot.
Compounding is the whole story, in both directions. A gain of 0.9 feels harmless and twenty layers of it keep an eighth of the signal. A gain of 1.1 explodes just as surely. This one-number model is a caricature: a real network has a different gain at every layer, and nobody knows them in advance. That is why real work measures the sizes layer by layer instead of trusting a formula.
Why not start every hidden neuron in a layer with the same weights?
They would stay copies for ever. Two neurons that start identical see identical inputs, produce identical outputs, and receive identical slopes, so no step ever separates them. Random starting weights break the tie. The size of the randomness matters as much as its presence. Dealt too wide, sigmoid neurons start in their flat ends, and Step 10 showed what a flat sigmoid does to every slope behind it.
Step 17

Match the output and the loss to the question

Everything so far answered with one number and was scored by squared misses. Real questions come in shapes. How much flour is a quantity question. Which of ten digits is this, is a pick-one question. Which of these five faults does this engine have, is a yes-or-no question asked five times, because faults can arrive together. The output layer and the loss must be chosen to fit the shape of the question, or training pushes on the wrong thing.

For pick-one questions, the network gives each choice a raw score, called a logit. A rule called softmax then converts the list of scores into a list of positive shares that add up to 1. The shares read as how the network splits its confidence. Only the gaps between scores matter: add 5 to every logit and the shares do not move. The matching loss, called cross-entropy, charges the network by how little share it gave the correct answer. Confidently wrong is charged heavily, and hedging is charged a little. That is the behaviour a pick-one task wants, and squared misses do not provide it.

One practical trap deserves its name on the page. Softmax works by raising a fixed number to the power of each score. The result of a big score is too large for the computer to hold. The standard repair is to subtract the biggest logit from all of them first. The shares come out identical, because only the gaps matter, and nothing overflows.

The loss is not the report card

Training needs a score that slopes, so that every weight always has an instruction. The thing a person wanted, answers on the right side, safe decisions, fair treatment of rare cases, usually moves in jumps, exactly as the percentage did in Step 13. So the loss is a stand-in that slopes, chosen to move in sympathy with the thing wanted.

The sympathy has to be checked, not assumed. A falling loss with a flat report card means the stand-in has come apart from the goal, and the fix is a better loss, not more training.

Lab 29 · Four question shapes, four output rules
Try this firstPress each of the four question shapes and read the bars. Softmax bars always share one whole unit between them, so one can only grow by starving the others. The yes-or-no bars spend their confidence independently, and can all be high at once.
The output rule states what can be true at once. One softmax over five engine faults would force the faults to compete, and an engine with two faults would be scored as though it could only have one. Five separate yes-or-no outputs make the opposite claim. Neither is cleverer; one of them matches the world and the other does not, and only you know which.
Before applying softmax, an implementation subtracts the largest logit from every logit. What does that change?
The answer is identical and the overflow is gone. This is a rewrite for the machine, not for the mathematics. It matters because the failure it prevents is silent. An overflowed softmax does not look wrong, it poisons the loss, and the first visible symptom is a training run that dies for no stated reason.
Step 18

Give the walk downhill a memory

Gradient descent, as Step 5 left it, has no memory. Each step reads the slope where it stands, multiplies by the rate, moves, and forgets. In a long thin valley, the kind Step 6 drew, that produces the zig-zag. The walk bounces between the steep walls while creeping along the gentle floor, and most of the travel is wasted sideways.

Momentum is the first fix: keep a running average of recent slopes, and step along the average instead of the latest reading. The sideways parts of the slope point opposite ways on alternate steps, so in the average they cancel. The along-the-valley part points the same way every step, so it accumulates. The name is honest, because the walk now behaves like a rolling ball that takes time to turn. Adam adds a second memory: a running typical size for each weight's slope, kept separately. A weight whose slopes run huge takes careful small steps, while a rarely nudged weight takes bolder ones.

None of this changes where downhill is. It changes how the walk behaves on the way, and it adds settings of its own. Runs often start the rate small while the first noisy steps pass, then shrink it late so the walk can settle. A written plan for changing the learning rate over a run is called a schedule. It is chosen and reported like everything else.

Two ways of keeping weights small quietly disagree

Many recipes also pull every weight gently towards zero, so that no single weight grows monstrous. There are two ways to write that pull: add a penalty for big weights into the loss, or directly shrink each weight a little at every step. Under plain gradient descent the two are the same move.

Under Adam they are not, because Adam rescales what flows through the loss, penalty included, while a direct shrink bypasses the rescaling. The version that shrinks directly is called AdamW, and the W is the whole difference. A pair of methods that agree on the easy case and split on the real one is a pattern worth expecting in this field.

Lab 30 · Roll a ball down the same bowl
Try this firstWith momentum at 0, read the weight after 25 steps. Then push momentum up towards 0.9 and watch the path change shape. Then find a learning rate that overshoots, and watch what the memory does to the overshoot.
Read the trajectory, not the method's name. Momentum crosses the bowl in fewer steps. The same memory that carries it through flat stretches also carries it past the bottom when the rate is high, because remembered speed is exactly what makes stopping harder. No optimiser removes the choosing. It moves the choosing to different knobs.
Does switching to Adam remove the need to choose a learning rate?
No. Adam adjusts relative step sizes between weights, which is real help, and it leaves the absolute size, the warm-up and the decay in your hands. The honest procedure is unchanged from Step 5: try a few, read the loss curves, and keep notes precise enough that someone else could rerun the winner.
Step 19

Teach one small filter, use it everywhere

An edge in a photograph is the same event wherever it happens: sky meets roof at the top of the frame, cat meets carpet at the bottom. A plain layer reading the pixel list from Step 14 would have to learn to spot that edge separately at every position, one full set of weights per place. That is wasteful, and worse, what is learned about edges at the top teaches the bottom nothing.

A convolution fixes both at once. One small set of weights, called a kernel, is slid along the input and applied at every position in turn, like one rubber stamp pressed along the whole row. Three weights scanning seven readings produce five answers, one per stop. The same three weights made all five. The saving in weights is the small half of the win. The large half is the built-in claim that a pattern means the same wherever it appears. That claim is true of pictures and of sound, and it is exactly the neighbourly knowledge the flat list threw away.

Edges of the row, and whether the stamp is compulsory

A three-wide kernel cannot centre itself on the first reading without hanging off the end. Either the output row comes out shorter, or the input is padded with zeros to let the stamp reach the ends. Sliding two positions at a time instead of one halves the output length. These are bookkeeping choices, but shapes have to be tracked through every layer, because detail dropped early cannot be recovered later.

The stamp itself is a choice, not a law. Some current image models cut the picture into patches and let the attention of the next step relate them instead. Which wiring wins is settled by measurement on held-out data, not by argument.

Lab 31 · Slide one three-number kernel
Try this firstChoose the edge kernel, then drag the position slider and watch the window slide along the input. The output bar under the window fills in stop by stop. Then switch to blur and slide again: same input, different stamp, different story.
Three weights, used at five positions. The edge kernel answers loudest where the input jumps and stays silent on the flat stretches, wherever the jump sits. The blur kernel answers with each neighbourhood's average. A real image layer runs many kernels at once, each learning to watch for its own small pattern, and their outputs stack into the next layer's input.
What does sharing one kernel across every position buy?
Learn once, recognise everywhere. Sharing also multiplies the training signal: every edge in every photo teaches the one edge kernel, instead of each position hoarding its own lessons. The claim built into the wiring is only that position does not change meaning. Rotation, size and lighting are different claims, and the kernel makes none of them.
Step 20

Let each word ask the others for help

In the sentence "the dog that chased the cat was muddy", which animal was muddy? You answered by looking back: "was muddy" belongs to "dog", five words away, and the cat in between is a distraction. A network reading a sentence needs that same move. Each position must be able to pull in information from other positions, near or far, by how relevant they are rather than by how close they sit.

Attention is that move written as arithmetic. Every position publishes a key, a list of numbers advertising what it holds, and a value, the information it will hand over. A position wanting help publishes a query, which is scored against every key, scoring high where the two lists line up. Softmax from Step 17 turns the scores into shares that sum to 1; the asking position receives the values, mixed in those shares. Nothing is fetched by position number. Everything is fetched by how well it matches, which is why the faraway dog can outweigh the nearby cat.

Two practical notes complete the picture. The scores know nothing about word order, so each word's position is folded into its numbers separately. And a model being trained to guess the next word must not peek at it, so scores pointing at later positions are blocked. The block is called a causal mask.

What the anywhere-to-anywhere lookup costs

Every position scoring every other position is a table of scores with one row and one column per position. A hundred words make ten thousand scores. A thousand words make a million. The cost grows with the square of the length, which is why long documents are the expensive case. Much engineering goes into cheaper lookalikes that skip most of the table.

The standard recipe also scales the scores, a small cousin of Step 16. Raw scores grow with the length of the key lists, and unscaled they push softmax into premature certainty. So the recipe divides them back down by a fixed amount before the softmax.

Lab 32 · Turn three matches into one mixture
Try this firstDrag the temperature down and watch one arrow fatten while the others starve. The mixed answer slides towards that key's value. The slider divides every score by a temperature: cold, and the best match takes nearly the whole mixture; hot, and the shares even out.
The shares always sum to one, so attention never invents information. It redistributes what the values already carry, weighted by match quality. That also bounds what an attention pattern can prove about a model: it shows where information flowed on this input, which is a routing fact, not a reason. Step 24 returns to that gap.
During next-word training, what does the causal mask prevent?
It stops the model reading the answer sheet. Without the mask, position ten can attend to position eleven, which holds the word it is being asked to guess. The training loss collapses to nearly nothing and the model is useless the moment the future is actually unknown. The mask keeps the exam honest, at training time and after.
Step 21

Start from a network that already knows something

A cook who can already make pancakes learns waffles in an afternoon, because most of the skill carries over. Networks can be given the same head start. A network trained for months on mountains of text or images has built internal machinery for recognising structure, and that machinery is reusable by tasks its builders never imagined. Starting from it is called transfer, and it is how most real projects begin, because almost nobody can afford the months.

The recipe: take the big trained network, called the base, freeze its weights, and train only a small addition on your own data. The addition can be a fresh output layer, or an adapter, a thin set of extra weights threaded through the base. Training one hundredth of the weights means one hundredth of the slopes to compute and store, so the training bill collapses. The answering bill does not: the frozen base still runs in full every time a question is asked. Cheap to train and cheap to run are different claims, and an adapter only buys the first.

Where did the base's months of training come from, when nobody can label mountains? The trick is called self-supervision: hide part of the data and train the network to fill it back in. Cover the next word and demand it. The text itself is the answer sheet, so no person labels anything, and the supply of practice material is every sentence ever written.

How an adapter stays thin

The popular trick writes each adapter as two skinny weight tables multiplied together, a wide-to-narrow table into a narrow-to-wide one. The narrow middle, called the rank, sets how much the adapter can express and how little it costs. A rank of 8 threaded through a base of billions is a few million trainable numbers.

The narrowness is a restriction, not a free lunch: some adjustments the full network could make are out of the adapter's reach. Whether the restriction costs anything on your task is a measurement, made against full tuning on held-out data, never an assumption.

Lab 33 · Weigh an adapter against its base
Try this firstDrag the adapter share from 1% down towards 0.1% and watch the trained sliver shrink against the frozen slab. The pills keep both bills: the weights you train, and the weights that still run at answer time.
Trainable weights and answer-time weights are different budgets. The sliver is what your gradient descent touches, and it is tiny. The slab still has to sit in memory and run for every answer, and it still carries its builders' licence terms and its training data's habits. An adapter changes what you pay to teach, not what you took on by choosing the base.
A team trains an adapter that is 1% of a frozen billion-weight base. What is guaranteed?
Only the training bill shrinks by arithmetic. Quality against full tuning is an open measurement, and the answer-time cost is the whole base plus a little. Teams choose between a frozen base with an adapter, full tuning, or no training at all, by running the comparison on their own held-out data. The answer moves from task to task.
Step 22

Networks that produce instead of judging

Everything so far took data in and answered a question about it. A generative network runs the other way: it produces new examples that could pass for members of the training pile. A sentence that was never written, or a face that belongs to nobody. There is no single algorithm behind the word. There are several different training tasks, and which one was used decides how the model produces.

Four families cover most of what you will meet. An autoregressive model produces one piece at a time, each piece guessed from the pieces so far, which is next-word guessing run as a factory. An autoencoder squeezes its input through a deliberately narrow middle and rebuilds it on the far side, learning a compact description on the way. A diffusion model is trained to remove a little noise from a spoiled example. It produces by starting from pure noise and cleaning it up, step after step, until a picture condenses. An adversarial pair trains a forger network against an inspector network, and each drives the other to improve.

One habit matters more than the mechanisms. A single convincing sample proves almost nothing. It does not show the model can produce variety, and it does not show the sample is new rather than a training example memorised and handed back. Produced data also needs marking as produced, because a later model trained on it as though it were measured truth inherits every one of its quirks.

Synthetic data helps and hurts for the same reason

A generator can manufacture practice examples for situations too rare or costly to collect: night-time faults, dangerous near-misses. Since it produces only what it learned, the rare cases it never saw stay missing from its output too, now hidden under bulk that looks plentiful.

The trade is the same both ways: synthetic data carries the generator's view of the world, gaps included. The check is always against real held-out measurements, and the result decides whether the manufactured pile helped.

Lab 34 · Four routes to a fresh sample
Try this firstPress each family and read its diagram: what the network learns, and the route from the learned thing to a new sample. The caution pill names each family's characteristic failure, which is as much a part of the choice as the mechanism.
Generative names an outcome, not a method. The families produce by different routes, fail in different ways, and cost differently. One piece at a time is slow for long outputs, denoising pays per cleaning pass, and the adversarial game can refuse to settle. Picking a family is picking which costs and failures you can live with.
A generative model produces one strikingly convincing image. What has been established?
One inspected sample, nothing more. The impressive demo is the cheapest thing a generative model makes. Whether it produces variety, whether it leaks memorised training data, and whether it holds up under many draws are separate tests. Every one of them has embarrassed a public model at least once.
Step 23

Count the bill before agreeing to train

Weights cost memory. Every example flowing through costs memory for its intermediate values, the ones Step 11 kept for the backward pass. Every weight costs arithmetic each time an example passes it. Training multiplies everything: the optimiser memories from Step 18 can triple the space for weights, and each step runs the network forwards and backwards. Before anyone trains a large model, someone counts, because the count decides what is affordable before any cleverness starts.

The counting is ordinary multiplication, and one shape in it deserves respect. Double the width of every layer and the weight count quadruples, because weights connect a doubled layer to a doubled layer. The same square that made the pixel list expensive in Step 14 makes width expensive here. Work then scales with weights times examples, so the bill is a product of choices, and halving any factor halves it.

The standard economies have names. Mixed precision stores numbers with fewer digits, halving memory and speeding arithmetic. The sums that need care are kept in full width, so small gradients do not round away to zero. For answering rather than training, quantisation shrinks the stored weights further, and distillation trains a small network to copy a big one's answers.

When one machine is not enough

Past a certain size the model or the batch no longer fits on one machine, and the work is laid out across many. Either whole copies of the model are fed different batches, or one model is sliced across machines, layer by layer or within layers. Every layout pays the same tax, which is the wires. Moving numbers between machines is slower than arithmetic on them.

So the practical question is never how many machines, but whether the wires between them are busier than the arithmetic. Adding machines to a run that is waiting on wires makes it wait harder.

Lab 35 · Estimate a transformer's bill
Try this firstDouble the width and watch which bar jumps furthest. Then double the layer count and compare the jumps. The bars are drawn on a scale where each gridline is ten times the last, or the small settings would vanish.
Width squares, depth adds. That is the shape of the whole estimate, and it is why wide models grow expensive faster than deep ones. Treat the numbers as sizing, not truth: the estimate omits embeddings, activations and the wires, and a real decision is made by profiling the real machine.
A team switches its model to fewer digits per number to save memory. What must be re-checked?
All of it, because precision is a trade rather than a discount. Fewer digits really does save memory and time, and it quietly rounds the smallest gradients to nothing. The protections are standard: scale the loss up so small slopes survive, and keep the accumulating sums in full width. The proof is measured task quality on the actual hardware, not the memory graph.
Step 24

Show that it survives the messy world

A model that scores well on clean test photos has answered one question: how it does on data like its training data. The porch camera from Step 1 will meet rain, glare, cobwebs and a moth on the lens. Any of those can flip an answer. Worse, some flips can be caused on purpose. A small, carefully chosen change to an input, invisible to a person, can walk an example across the network's decision boundary. The boundary was never trained to be far from anything.

That distance has a name. An example's margin is how far it sits from the nearest point where the model's answer flips. A wide margin means every small change leaves the answer alone; a change larger than the margin can cross. Measuring margins is honest evidence with a stated scope: it speaks about small changes near this example, and says nothing about snow, new camera angles, or the moth.

The same discipline applies to explanations. Tools that highlight what an answer leaned on show where information flowed, like the attention shares in Step 20. Routing is not a reason, and a highlight is not proof of cause. A release argument is a pile of separate evidence. Error rates on the worst slices rather than the average. Confidence that matches how often the model is right. A stated fallback for the inputs it declines, and monitoring that keeps measuring after the launch.

Testing against an opponent needs a stated opponent

Claiming a model resists attack means nothing until the attacker is described: what they can see, what they can change, and what they gain. A stranger nudging pixels, an insider poisoning training data, and a user coaxing a chatbot are three different opponents, and defences against one are routinely useless against another.

Every successful attack found in testing becomes a regression case, rerun for ever. And the strongest defences often sit outside the model: limiting what the surrounding system lets any answer do costs less than teaching the network to refuse every trick.

Lab 36 · Spend an example's margin
Try this firstDrag the nudge size up and watch the arrow grow towards the ring around the example. The ring is the measured margin. While the arrow stays inside, this nudge cannot flip the answer; the moment it crosses, the guarantee is spent.
One claim, one scope. Inside the ring, small changes of this kind are provably harmless, and that is a real guarantee worth having. Outside it, the measurement says nothing at all. Reading a margin as general toughness is how narrow evidence gets stretched into a promise nobody measured.
An attention map highlights one word as the model answers. What has the highlight proved?
A routing fact about one input. Useful, and easily over-read. Checking whether the highlight is faithful means testing: remove or replace the word and see whether the answer actually moves. Explanations earn trust the same way models do, by surviving attempts to break them, not by looking plausible.

What you can do now

  • Turn a picture into the list of numbers a network actually receives, and say what the list loses.
  • Choose a batch size by naming what it trades: noise against memory against updates per pass.
  • Explain why deep signals vanish or explode, and what initialisation, normalisation and residual paths each do about it.
  • Match an output layer and loss to a question's shape, and name the overflow trap softmax brings.
  • Say what momentum remembers, what Adam adds, and what neither removes.
  • Explain what sliding one kernel buys, and track a shape through padding and stride.
  • Walk one attention lookup by hand: query, keys, scores, shares, mixture.
  • Weigh a frozen base plus adapter against full tuning, using both bills.
  • Tell the four generative families apart by what each one is trained to do.
  • Estimate a training bill, and say why width costs more than depth.
  • Scope a margin claim, an attention highlight, and a release argument honestly.

Continue the learning path

  • Training and Evaluation holds data back, measures honestly, and catches the model that memorised its homework.
  • Language Models builds tokenisation, transformers, retrieval and tool use on top of the attention you just met.
  • Computer Vision takes the pixel grids and kernels onwards to detection and segmentation.
  • TinyML squeezes these networks into microcontrollers, where every byte and millisecond is counted.