Networks
How did a threshold unit of 1943 become the block inside today's language models?
The part opens with a strip from 1943 to 2012, two winters shaded, and a small ReLU network bending its linear pieces around two spirals. McCulloch and Pitts's threshold units compute any logical formula; Rosenblatt's perceptron learns from mistakes, and Novikoff's theorem bounds how many it can make. Then XOR: no line separates it, Minsky and Papert's book appears, and the first winter follows. A hidden layer solves XOR, and backpropagation, derived as the delta equations and checked three ways, trains it. One layer of hinges can approximate any curve, Barron's rate escapes the curse of dimensionality, and depth folds the plane into exponentially many pieces. The part turns on why deep networks would not train: gradients vanish through 50 sigmoid layers. The fixes are derived and measured: initialization that keeps the variance, the edge of chaos, the residual stream, normalization. It ends by assembling the modern block with its gated MLP, weighing Kolmogorov-Arnold networks, and training Bengio's neural language model to 2.38 bits per character, 1.99 when mixed with Kneser-Ney.
What you need. The chain rule and Part 4's autodiff; variances of sums of independent terms (Part 5).
- Mathematics and history
- McCulloch–Pitts to backprop, universal approximation, depth, initialization, signal propagation, residuals, normalization, gating
- Models, data
- a neural n-gram model (Bengio 2003)
What you will be able to do
Undergraduate
- Run the perceptron rule by hand, and show with four inequalities that no single unit computes XOR.
- Explain how a hidden layer makes XOR separable, and how hinges add up to any curve.
- Tell the history from 1943 to 2012: what each winter was about and what ended it.
Master's
- Prove Novikoff's bound, and derive the delta equations of backpropagation.
- Derive the LeCun, Glorot and He initializations from the variance of one layer, and predict how a signal grows or shrinks through depth when the scale is wrong.
- Derive the Jacobians of a residual block and of RMSNorm, and explain what each does to the gradient.
Research
- Reproduce Maurey's argument for the 1/sqrt(n) rate of random units, and state Barron's theorem with its lower bound for fixed bases.
- Compute the mean-field length and correlation maps, locate the edge of chaos, and relate the depth scale to trainability.
- State the Kolmogorov-Arnold theorem and assess the evidence for and against KANs.
Engineering
- Count the weights of a transformer block from a published configuration, including the 8d/3 width of a SwiGLU MLP.
- Choose an initialization, a normalization placement and an activation for a deep network, and diagnose a stalled run from its per-layer gradients.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 20 min · Master's 44 min · Research 55 min · Engineering 26 min.
- 0How we got hereUndergraduate2 min
- 1The first neuronsUndergraduate3 min
- 2The perceptron learnsUndergraduate4 min
- 3XOR, and the first winterUndergraduate3 min
- 4BackpropagationMaster's4 min
- 5One layer can do anythingUndergraduate3 min
- 6Escaping the curse of dimensionalityResearch4 min
- 7What depth addsMaster's3 min
- 8The second winter, and the revivalUndergraduate3 min
- 9Initialization, derivedMaster's3 min
- 10The edge of chaosResearch4 min
- 11The residual streamMaster's4 min
- 12NormalizationMaster's4 min
- 13The modern blockEngineering4 min
- 14Kolmogorov-Arnold networksResearch3 min
- 15A neural language modelEngineering2 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
How we got hereUndergraduate2 min
In 1943, a neurophysiologist and a young logician wrote down the first artificial neuron: a unit that adds up its inputs and fires if the total is big enough. Fifteen years later, Frank Rosenblatt built one that learned from examples, and the New York Times reported the Navy's hope that it would one day walk and talk. In 1969 a book proved what a single layer of such units cannot do, and for a decade few worked on them. In 1986 backpropagation trained the hidden layers in between, and networks learned to read handwritten zip codes. But by the late nineties they were out of fashion again. In 2006 a way to train deep ones was found, and in 2012 a deep network won the ImageNet competition by a wide margin. The field has not looked back.
Here is what a network does, in one picture. Two spirals, wound around each other. No straight line can separate them. Here's a small neural network, three layers of thirty-two simple units, before any training. The thin lines cut the plane into the pieces on which the network is exactly linear. Now train it.
The pieces swing around, and the boundary between the colours bends to follow the spirals, A network is just this: many flat pieces, glued together, placed by gradient descent. This part is about why that works, who found it out, and what it takes to make it work.
This is Part 9 of AI, Built, in the second act: learning from data. In it: the perceptron and its proof; backpropagation; what networks can represent; why deep networks were hard to train, and the fixes; the block inside today's language models; and a neural language model on our scoreboard.
1The first neuronsUndergraduate3 min
In 1943, Warren McCulloch, a neurophysiologist, and Walter Pitts, a young logician, published a logical calculus of the ideas immanent in nervous activity. Their neuron is a switch. Its inputs are zero or one, and each comes in with a weight. The unit fires, it outputs a one, when the weighted sum reaches a threshold. With both weights one and a threshold of two, it fires only when both inputs are on: that's AND. Lower the threshold to one, and it fires when either is on: OR. One input with weight minus one and threshold zero gives NOT. From AND, OR and NOT you can build any logical formula, so a network of these units can compute anything a logic circuit can. But every weight was set by hand. Nothing learned.
Where would learning come from? In 1949 the psychologist Donald Hebb proposed an answer, for real neurons. When an axon of cell A is near enough to excite a cell B, and repeatedly or persistently takes part in firing it, some growth process or metabolic change takes place in one or both cells, such that A's efficiency, as one of the cells firing B, is increased. In symbols: strengthen a connection in proportion to the activity at both of its ends. Decades later it was summed up as: cells that fire together, wire together.
In 1958 Frank Rosenblatt, a psychologist at the Cornell Aeronautical Laboratory, put the two ideas together: a McCulloch and Pitts unit whose weights are learned from examples. He called it the perceptron. That July he showed it, simulated on an IBM 704 computer: after fifty trials, it had taught itself to tell cards marked on the left from cards marked on the right. The New York Times reported that the Navy expected the machine to walk, talk, see, write, reproduce itself, and be conscious of its existence. Then he built it. The Mark I Perceptron, shown in 1960, had a camera of four hundred photocells, twenty by twenty, wired at random to five hundred and twelve association units, which fed eight response units. Its weights were potentiometers, turned by electric motors as it learned.
Two years later, at Stanford, Bernard Widrow and his student Ted Hoff built ADALINE, an adaptive linear neuron, with a different rule. The perceptron changes its weights only after a mistake, and then by the whole input. Widrow and Hoff instead wrote down the squared error on one example, before the threshold, took its gradient, and stepped a little way downhill, on every example, in proportion to the error. That's the least mean squares rule, and it is stochastic gradient descent: the update that trains every network in this series, and the subject of Part 11.
2The perceptron learnsUndergraduate4 min
Here is Rosenblatt's learning rule, in modern notation. Each example is a point x with a label y, plus one or minus one. The perceptron predicts the sign of w dot x: which side of the line where w dot x is zero the point falls on. The weights w form an arrow at right angles to that line. When it gets an example wrong, it adds y times x to w. For a positive point on the wrong side, that turns the arrow toward the point, and the line swings to put the point on its side, or at least nearer to it. That's all there is. A constant input of one gives the line a bias, so it needn't pass through the middle.
Here it is on 50 points that some line can separate. It starts with all its weights at zero. Every time it meets a point on the wrong side, the line jumps. In its first pass through the data it makes 6 mistakes, and 7 more in the passes after that. After 13 mistakes in all, a whole pass goes by without one, and it stops: every point is on its own side.
Is it guaranteed to stop? In 1962 Albert Novikoff proved that it is, whenever some line separates the data. Suppose every point lies within a distance R of the origin, and some unit vector w star puts every point on its side with room to spare, a margin gamma. Watch two numbers. First, w's agreement with w star. Each mistake adds y x, and y x dot w star is at least gamma. So after k mistakes, the agreement is at least k gamma: it grows in proportion to k. Second, w's length. A mistake means y times w dot x was not positive, so the middle term can't help: the squared length grows by at most R squared. After k mistakes, at most k R squared: the length grows only like the square root of k. But the agreement with a unit vector can never exceed the length. So k gamma is at most root k times R. Square both ends and divide: the number of mistakes is at most R over gamma, squared. Something that grows like k can't stay below something that grows like root k for long.
That's the perceptron convergence theorem. The bound doesn't depend on how many points there are, or the order they come in, only on how much room there is between the classes.
For our points, R is 2.78 and the best margin gamma is 0.152, so the theorem allows 334 mistakes. It made 13. Shrink the margin, data set by data set, and run the perceptron twenty times on each, in different orders. The bound always holds, and it's pessimistic: the worst run uses at most 16 percent of it. Two things the theorem doesn't promise. The line it finds is a separating line, not the one with the widest margin; finding that one is the support vector machine of Part 6. And if no line separates the data, the perceptron never stops.
3XOR, and the first winterUndergraduate3 min
Here is the simplest thing a single unit cannot do. XOR, exclusive or: fire when exactly one input is on. Suppose a threshold unit did it. The input zero, zero must not fire, so the threshold is positive. Each input alone must fire, so each weight is at least theta. Both together must not fire, so the two weights add up to less than theta. But adding the middle line, they add up to at least two theta, which is more than theta. A contradiction: no line puts the two blue points on one side and the two pink ones on the other. Run the perceptron on it anyway, and it never settles: in every one of 40 passes, it makes between 2 and 4 mistakes.
In 1969 Marvin Minsky and Seymour Papert of MIT published Perceptrons, a book of careful theorems about what these machines can compute. A single layer of trainable weights can't compute parity, and can't tell a connected figure from a disconnected one, unless some of its units see nearly the whole picture at once. Networks with more layers could do more, and they knew it, but practical training of hidden units remained difficult. Of such machines, the authors wrote that it was an important research problem to elucidate, or reject, their intuitive judgment that the extension is sterile. Rosenblatt died in a boating accident in 1971. Money and students went to the symbolic AI of Part 2. Through the seventies only a few kept going; Kunihiko Fukushima's neocognitron of 1980 is the ancestor of the convolutional networks of Part 10, and John Hopfield's network of 1982 brought physicists back to the subject.
What a single unit can't do, two layers can. Put two units in the middle, hidden between the input and the output, and train all the weights by gradient descent, with the series' own automatic differentiation from Part 4. On the left, the input square, tinted by what the network says about every point of it. On the right, the same square as the hidden layer sees it: every grid line, bent by the two tanh units, and the output unit's line, in yellow.
Now train. The hidden layer bends and folds the square, until the two blue points sit on one side of a straight line and the two pink on the other. Then the output unit, which can only draw a line, has an easy job. The loss falls from to .
4BackpropagationMaster's4 min
XOR showed what was missing: a way to train the units in the middle. At the output, the error is plain to see: compare the answer with the target. But how much is a hidden unit to blame? Its effect on the loss passes through every unit after it. Write the network layer by layer. A layer's weighted sums, z, are a weight matrix times the previous layer's outputs, plus a bias; its outputs, a, bend z with a nonlinearity, phi; and the loss depends on the last layer. The chain rule from Part 4 answers the question, and it can be organized so that a single sweep backwards answers it for every weight at once.
Define delta for a layer: how much the loss changes when that layer's weighted sums change. At the top it's immediate: the loss's gradient with respect to the outputs, times the slope of the bend at each unit. Now go down one layer. Layer l's sums reach the loss only through its outputs, and those only through the next layer's sums. The chain rule says: take the next layer's delta, send it back through the transpose of the same weight matrix, and multiply by the slope of the bend. And once you know a layer's delta, its weights' gradient is just delta times the outputs coming into it, because the sums are linear in the weights. Two lines, applied layer after layer from the top: that's backpropagation.
Picture it as traffic. In the forward pass, values flow up: each layer multiplies by its weights and bends. At the top the loss compares the answer with the target. In the backward pass, errors flow down the same wires, through the transposed matrices, scaled at each unit by the slope of its bend, and every weight gets its gradient on the way past. Pause and predict: how expensive is the backward pass, compared with the forward one? Each layer does two matrix products going back, one for the deltas and one for the weight gradients, against one going forward. So a training step costs about three forward passes, about six arithmetic operations per weight per example. That six comes back in Part 12, in the formula for the cost of training a language model.
Let's check it on chapter three's XOR network, at random weights. Here are its nine gradients three ways: from the series' own automatic differentiation, which knows nothing about networks; from the delta equations, written out by hand; and by brute force, nudging each weight a millionth up and down and watching the loss.
The idea was found more than once. In 1970 Seppo Linnainmaa, a Finnish master's student, described the reverse mode of automatic differentiation, with no networks in sight. In 1974 Paul Werbos proposed training networks this way, in his Harvard thesis, and few noticed. In 1986 David Rumelhart, Geoffrey Hinton and Ronald Williams showed in Nature that networks trained by back-propagating errors learn useful features in their hidden units, and the field woke up. By 1989 Yann LeCun's networks at Bell Labs were reading handwritten zip codes. Hidden layers could be trained. The next question: what can they represent?
5One layer can do anythingUndergraduate3 min
Backpropagation can train any layer. So what can layers represent? Start with one unit, as modern networks build it. It takes some numbers, multiplies each by a weight and adds them up, plus a constant, exactly like Part 6's logistic regression, and then bends the result: anything below zero becomes zero. That bend, the rectified linear unit or ReLU, replaced the smooth S-shaped curves around 2010. Along any one input, a unit is a hinge: flat, then rising.
Add hinges together, each with its own position and slope, and you can draw a curve. Two hinges make a crude zigzag. Four. Eight. Sixteen. Sixty-four, and the typical miss is down to 0.0014.
How fast does the miss shrink? Joining the dots at the hinges gives straight chords, and over a piece of width h a chord misses a smooth curve by at most h squared over eight, times the curve's bending. With n hinges spread over the interval, h is six over n plus one. So the miss falls like one over n squared: double the hinges, and it quarters. Least squares can only do better than joining the dots. On log-log axes that's a line of slope minus two, and the measured slope is -2.01.
Here's another way to see it. Take three hinges: one up, one down twice as steeply, and one up again. Their sum is a bump: zero, up, down, and zero again. Put a bump at each of a row of points, each as tall as the curve is there, and add them up: you get the curve, joined dot to dot. Any continuous curve can be drawn this way, as finely as you like. In more dimensions the bumps take more units each, but the idea survives.
That's the universal approximation theorem, proved in 1989 by George Cybenko for S-shaped units, and by Kurt Hornik, Maxwell Stinchcombe and Halbert White in general. In 1993 Moshe Leshno and colleagues pinned it down: any continuous activation works, as long as it is not a polynomial. It says a network can represent the answer. It doesn't say how many units that takes, or whether training will find them, or whether what's learned from examples holds up on new ones, the subject of Part 8. The first question has a surprising answer.
6Escaping the curse of dimensionalityResearch4 min
One layer can draw anything; how many units does it take? A table does the same job with one entry per point of a grid, and joining the dots in one dimension is exactly a layer of hinges. But a grid with m points along each axis has m to the d points in d dimensions. Turn it around: with n points to spend, the spacing scales as n to the minus one over d for large grids, and the miss shrinks like n to the minus two over d. In a hundred dimensions, halving the miss takes two to the fiftieth times as many points. That's the curse of dimensionality, Richard Bellman's phrase.
In 1993 Andrew Barron showed that networks escape this, for a large class of functions, and the reason fits on one screen. Take a smooth bump, a Gaussian, in d dimensions. It is exactly an average of cosine waves, one for each direction omega, weighted by its Fourier transform. Draw n directions at random and average just those n waves: a network with n units, each a wave in one direction. At any point, that's an average of n independent draws, so its squared error is the variance of one draw, divided by n. And a cosine lies between minus one and one, so the expected squared error is at most one over n. Average over inputs under any fixed probability distribution, and the same bound holds, with no d anywhere. If random units do that well on average, some particular choice of n units does at least as well in mean squared error under that input distribution, in any dimension. The argument is Bernard Maurey's, from probability.
Here it is, computed: empirical root mean squared error on uniform test inputs. First the grid, in one, two, four and eight dimensions: the lines flatten, with slopes of , , and , close to minus two over d. In eight dimensions, points still miss by . Now n random cosine units, in one, four, sixteen and sixty-four dimensions. The four lines lie on top of each other, with slopes between and : the miss falls like one over the square root of n, whatever the dimension. In sixty-four dimensions, units miss by .
Barron's theorem says this for ordinary S-shaped units, for every function whose Fourier transform, weighted by frequency, has a finite total, C f: the squared miss is at most two r C f, squared, over n. He also showed what a fixed basis can't do. For uniform inputs on a cube and a fixed spectral bound, any n functions chosen before you see f have a worst-case squared error bounded below by a constant times n to the minus two over d. The network escapes because it chooses the directions of its units to suit f. The catch: for rough, wiggly functions C f can be astronomically large, and the theorem says nothing about whether gradient descent will find the units. Still, it was the first hint of why networks work in high dimensions.
7What depth addsMaster's3 min
If one layer can do anything, why stack them? Here's the answer in one picture. Two units make a tent: up from zero to one, and back down. Feed the tent into another tent, and the line is folded twice: four pieces. Three layers, eight pieces. Five layers, thirty-two. Each layer doubles the pieces, while one wide layer gets only one more piece per unit. Matus Telgarsky turned this into a theorem in 2016: some functions that a deep, narrow network computes exactly need exponentially many units if the network is shallow.
In two dimensions the same trick folds the plane. Here's a square with a picture on it: an F, so you can tell its mirror images apart. A ReLU layer can compute two times the absolute value of x, minus one: that folds the square in half along the middle, and stretches the half back to full size. Now colour each point of the input by where it lands: two mirrored copies of the picture. Fold again, along the other direction: four. Then eight, sixteen, thirty-two. Each layer doubles the number of linear pieces, and whatever the rest of the network draws on the folded square is drawn in every piece at once, mirrored. A deep network can reuse what it has built.
Let's count pieces properly. Each unit of a first layer is a line in the plane: on one side it's off, on the other it's on. n lines in general position cut the plane into at most one, plus n, plus n choose two pieces, the classic count that Thomas Zaslavsky made general for hyperplanes in 1975. Count them directly for random lines, and they match. Growth like n squared, in the plane; like n to the d in d dimensions. Deep networks can do far better: Guido Montufar and colleagues showed in 2014 that the maximum grows exponentially with depth, as the folds suggest.
But that's what depth can do, with weights chosen by hand. What does a random network do? Here are forty-eight units cutting the plane, arranged in one layer, then two, three, four and six. The number of pieces . Boris Hanin and David Rolnick proved in 2019 that, at initialization, polynomial bounds hold for the expected local density of activation regions, with neuron count raised to the input dimension and constants controlled by their assumptions. Their experiments found comparable region counts before and during training. Our displayed counts average three initializations on a three-hundred-and-twenty-square grid; the maps show seed zero on a two-hundred-square grid, so these are sampled counts rather than exact global region counts. Our spiral network started with pieces and ended with : . Depth helps in subtler ways, by making useful functions easy for training to reach.
8The second winter, and the revivalUndergraduate3 min
Through the nineties, backpropagation worked for networks with one or two hidden layers. Deeper ones barely trained. In 1991 Sepp Hochreiter, a student in Munich, worked out why. The gradient that reaches an early layer is a product of one factor for every layer above it, and those factors are rarely close to one. Here is a fifty-layer network of S-shaped units, set up the usual way of the time, with a gradient sent down from the top. Each layer multiplies it by the slope of a sigmoid, at most a quarter, and by the weights: about 0.1 times smaller per layer. By the first layer it's ten to the minus 42. The early layers might as well be frozen.
Meanwhile, other methods were winning. In 1995 Corinna Cortes and Vladimir Vapnik introduced the support vector machine: convex, so training always found the best answer, with a theory of generalization behind it. Networks kept a few strongholds: the LSTM of 1997, built to carry gradients through time, and Yann LeCun's convolutional networks, which by the late nineties were reading handwriting and bank checks. But for most of the field, deep networks were hard to train and harder to analyse, and attention moved to kernels and graphical models. For networks, it was a second winter.
A small community kept going, supported from 2004 by a Canadian research program led by Geoffrey Hinton. In 2006 he and his colleagues found a way to train deep networks. Don't train them all at once. First let one layer learn, without labels, to model the data. Freeze it, and let the next layer learn to model the first layer's outputs; and so on up the stack. Then fine-tune everything together with backpropagation, starting from these sensible weights instead of random ones. They called it a deep belief net, and with work by Yoshua Bengio's group and others the same year, the name deep learning stuck.
Then, within a few years, the pretraining turned out not to be needed. Graphics cards made training many times faster, and in 2010 Dan Ciresan and colleagues set a record on handwritten digits with plain deep networks, trained by plain backpropagation. Better starting weights, from Xavier Glorot and Yoshua Bengio, and the ReLU, kept signals alive. In 2012 deep networks took over speech recognition and, with AlexNet, image recognition: Part 10's story. In 2018 Bengio, Hinton and LeCun shared the Turing Award. The rest of this part takes the fixes one at a time, with their mathematics: initialization, the edge of chaos, residual streams, and normalization.
9Initialization, derivedMaster's3 min
Before training, the weights are random. But random how? What matters is their spread: how far the random starting weights stray from zero. Send a signal through fifty layers and track its size. Draw the weights a little too small, and each layer shrinks the signal by a fixed factor. After fifty layers, it's about 30 million times smaller: gone. A little too big, and it explodes, to about 10 million. Only one size keeps it steady, layer after layer. And gradients, flowing backwards, vanish or explode the same way.
The right size follows from one line of probability. A unit adds up its n inputs, each times a weight. If the weights are independent with mean zero, the variances of the terms add: the sum's variance is n times the weights' variance times the inputs' typical square. For tanh units near zero, the output is about the input, so to keep the variance the same from layer to layer, the weights' variance should be one over n in. Going backwards, the gradient is summed over the units it feeds, through the transposed matrix: that asks for one over n out. Xavier Glorot and Yoshua Bengio, in 2010, took the compromise: two over the sum. Yann LeCun had recommended one over n in, for the forward pass, back in 1998.
A ReLU changes the bookkeeping. Here is what the units of a middle layer receive, before the bend, in the steady network: a symmetric bell. The ReLU throws away the negative half, so the mean square of its output is exactly half the variance of its input. To make up for it, double the weights' variance: two over n. That's He initialization, from Kaiming He and colleagues in 2015, and it's the steady line of a minute ago.
Here is the inside of a fifty-layer tanh network, as a landscape. Each ridge is the histogram of one layer's outputs, from the first layer at the front to the fiftieth at the back. Here the weights are Gaussian, with the same variance as the old uniform rule, one over three n. The outputs shrink layer after layer, from a typical size of to about ten to the minus : the ridges collapse into a spike at zero. With Glorot and Bengio's variance, one over n, they stay spread out, narrowing slowly, to by the last layer. Make the weights too big, and the units saturate: the outputs pile up at minus one and plus one. Yet the gradient doesn't die: the gradient arriving at the first layer is times the size of the one at the top. It explodes, and the next chapter explains why.
10The edge of chaosResearch4 min
Why is there one right size? In 2016 and 2017 Ben Poole, Sam Schoenholz, Surya Ganguli, Jascha Sohl-Dickstein and colleagues answered with physics: mean-field theory. Make the network very wide. Then each unit's weighted sum, over random weights, is a Gaussian, and a single number describes a whole layer: the variance of its sums, q. One layer maps q to the next: square the tanh, average over the Gaussian, scale by the weight variance, add the bias variance. Plot that map against the diagonal, and iterate it: the staircase converges to a fixed point, here q star equals 0.57. Lengths settle down within a few layers, whatever the input. The interesting question is what happens to two inputs.
Send two different inputs through, and follow their correlation, c, layer by layer. Identical inputs stay identical, so c equals one is always a fixed point. Whether it attracts or repels depends on the map's slope there, called chi one. With small weights, chi one is , less than one: the ordered phase. Every pair of inputs is pulled together, until the network gives every input the same output. With big weights, chi one is : the chaotic phase. Nearby inputs are pushed apart, to a correlation of , and the network scrambles everything it sees. In between, chi one equals one exactly: the edge of chaos, where correlations change slowly and information about the input survives the trip. The dots are a real network of width a thousand, and the theory tracks it. And chi one also scales the expected squared gradient, layer by layer, in this mean-field limit; the RMS gradient factor is its square root. Below one it vanishes, above one it explodes, as you just saw.
Here is the whole picture for tanh networks: chi one, for every spread of the weights and of the biases. Blue is order, pink is chaos, and the yellow line between them is the edge. Now look where it meets the bottom, where the biases are zero: at a weight variance of 1.00 over n. That's exactly Glorot's rule from the last chapter. For ReLU units the same calculation gives chi one equals sigma w squared over two, so the edge sits at two over n: He's rule. The initialization rules weren't just tidy bookkeeping. They put the network on the edge of chaos.
How deep can a network be and still train? The theory gives a depth scale, xi c: how many layers a correlation survives before it's forgotten. It's infinite exactly at the edge. Schoenholz and colleagues found that networks train when they're shallower than about six depth scales. We tried it: tanh networks from five to a hundred layers deep, at twelve weight variances, each trained the same way on the same small task. Bright means it learned; dark means it stayed at chance. Pushed further, the idea trained convolutional networks ten thousand layers deep in 2018, with nothing but a careful initialization. Part 12 returns to it, for transformers.
11The residual streamMaster's4 min
Good initialization gets a signal through at the start, but training can still go wrong in a deep stack. In December 2015, Kaiming He and colleagues published a fix so simple it's now everywhere. Instead of each layer replacing what came before, let it add to it. The layers become small corrections to a stream of numbers flowing straight through: the residual stream. By the chain rule, the derivative of each block is the identity plus the residual derivative, an extra term. The skip path passes its gradient contribution back unchanged, like a plain wire, helping gradients reach the first layer. The other branches can still amplify or cancel that contribution, so the skip is an aid rather than a guarantee. Every transformer in this series is built this way.
Here it is on the spirals, with forty layers of thirty-two units. The plain stack . The same forty layers with residual connections . Same width, same optimizer, same number of steps, but different initialization: the residual branch starts smaller. This comparison changes both the skip connection and initialization.
Why does the plain stack never learn? Look inside both of them as they train: on top, what each one says about every point of the plane; below, the norm of the weight gradient in each of its forty layers, on a log scale. At the start, the plain stack's gradients shrink layer by layer on the way down: the first layer gets more than times less than the last. The residual stack's gradients are all about the same size, within a factor of , because each block adds to a stream the gradient flows straight back along. So as training runs, the residual stack's answer bends to follow the spirals, and the geometric mean of its weight-gradient norms , as there is less and less left to fix. The plain stack's answer stays one flat colour, the same everywhere, and its gradients only fade further.
There's another way to see what the stream does. The last layer is the first plus everything the blocks added. Its derivative is a product of identity-plus-a-little factors, and multiplying it out gives two to the L terms: one for every path through the network, from the path that skips every block to the one that goes through all of them. A residual network is a crowd of networks of every depth, sharing weights, and Andreas Veit and colleagues found that most of the gradient flows through the short ones. The idea had ancestors: the LSTM's constant error carousel in 1997, and the highway networks of Rupesh Srivastava, Klaus Greff and Juergen Schmidhuber, months before ResNet. ResNet won ImageNet with a hundred and fifty-two layers. And GPT-2 scaled residual-layer weights at initialization by one over the square root of the number of residual layers, accounting for accumulation along the stream.
12NormalizationMaster's4 min
The second fix rescales the numbers inside the network as it trains. In 2015 Sergey Ioffe and Christian Szegedy introduced batch normalization. Take a batch of examples, and for each feature, subtract its average over the batch and divide by its spread; then let the network learn its own scale and shift. It let them train image networks much faster, though the reason they gave, reducing internal covariate shift, was later disputed: in 2018 a team at MIT argued it mostly makes the loss landscape smoother. But a batch norm makes each example depend on the others in its batch, and at test time it needs averages saved from training. In 2016 Jimmy Ba, Jamie Kiros and Geoffrey Hinton proposed layer normalization: the same arithmetic, across the features of a single example. Every transformer uses a version of that.
Here is what layer normalization does to one vector. Shift its numbers so they average zero, then squash them so their spread is one. In 2019 Biao Zhang and Rico Sennrich asked whether the shift is needed at all. Their RMSNorm only divides by the root mean square, the typical size of the numbers. Before the learned gain, and ignoring the small epsilon used in practice, it sends every nonzero vector, long or short, onto the same sphere, keeping only its direction. It's cheaper, works as well, and is what Llama, Qwen and DeepSeek use.
What does normalization do to the gradient? Take RMSNorm without its gain, set epsilon to zero, and assume nonzero inputs. Its derivative, by the quotient rule, is a constant times the identity minus the projection onto h's own direction. So stretching h changes nothing, and the gradient never points along h: the idealized layer only cares about direction. Real implementations add epsilon, so that radial invariance is approximate. For nonconstant inputs, LayerNorm's derivative also removes the all-ones direction, since shifting every number at once changes nothing either. Measured with autograd at d equals : RMSNorm's Jacobian has equal singular values and zero; LayerNorm's, and , exactly as derived. And the constant in front is one over the vector's size: double h, and the gradient halves. Weights that grow large get proportionally small updates. The normalization stabilizes itself, and it interacts with weight decay in ways Part 11 takes up.
Where does the normalization go? The 2017 Transformer normalized after adding each block's output to the stream: post-norm. GPT-2, in 2019, moved it to the branch, before each block, leaving the stream itself as a clean running sum: pre-norm. In 2020 Ruibin Xiong and colleagues showed why it matters: with post-norm, the gradients at the start of training are uneven across the layers, so it needs a learning-rate warm-up. In our own -block model, the last block's starting gradient is times the first block's with post-norm, and times with pre-norm. The story isn't over: OLMo 2, at the end of 2024, normalizes each block's output instead, and a 2025 paper from Kaiming He, Yann LeCun and colleagues replaces normalization with a scaled tanh.
13The modern blockEngineering4 min
Inside today's blocks, the bend itself has changed. The S-shaped sigmoid and tanh of the eighties and nineties flatten out at both ends, which helped gradients vanish. The ReLU doesn't, on the positive side, but its slope is exactly zero for every negative input, so a unit that stops firing stops learning. In 2016 Dan Hendrycks and Kevin Gimpel derived a smooth version from a coin flip: keep the input x with the probability that a standard Gaussian falls below it. Averaged over the coin, that's x times Phi of x, the GELU, used in BERT and GPT-2. Its cousin, x times the sigmoid of x, called SiLU or Swish, came from reinforcement learning and from an automated search in 2017. Both are smooth, both dip slightly below zero, and both pass a little gradient for negative inputs.
The bigger change is the gate. A ReLU unit, as a surface over two inputs, is a fold: flat on one side, a ramp on the other. In 2016 Yann Dauphin and colleagues used gated units, which multiply one projection of the input by another. Here is the simplest: SiLU of one input, times the other. It's a saddle, a product: it can switch a feature on or off depending on something else. In 2020 Noam Shazeer tried variants inside the transformer's feed-forward layer, and SwiGLU won: SiLU of one projection, times a second projection, then a third matrix back down. His paper ends by attributing its success, as all else, to divine benevolence. Three matrices instead of two, so to keep the parameter count, the hidden width shrinks from four times the model width to eight thirds. In the published configurations: GPT-2's plain MLP is four times its width; Llama 2's gated one, 11,008, is eight thirds of 4,096 rounded up to a multiple of 256; later models go wider.
Now assemble the block. The residual stream runs straight up. A branch takes an RMS-normalized copy, runs attention, the subject of Part 13, and adds the result back. A second branch takes another normalized copy, runs the gated MLP, and adds that back. Stack it, here thirty-two times, and that's the body of Llama 3, and, with small changes, of Qwen, DeepSeek and the rest. Counting from Llama 3 8B's published configuration: each block has 41.9 million weights in attention and 176.2 million in the MLP, so 81 percent of the block is the gated MLP. Thirty-two blocks and the embeddings come to 8.03 billion: the eight billion of its name.
Does each piece earn its place? We built the block up one piece at a time, as a character model on the thirty novels: blocks deep, each version trained for steps on the same data, from the same seed.
14Kolmogorov-Arnold networksResearch3 min
There's another way to build any function, and it's older than the perceptron. In 1900 David Hilbert asked, as the thirteenth of his famous problems, whether the solutions of a seventh-degree equation could be written using only functions of two variables. In 1957 Andrey Kolmogorov and his nineteen-year-old student Vladimir Arnold answered with something far stronger. Every continuous function of n variables on a cube is a sum of 2n plus one functions of one variable, each applied to a sum of n more functions of one variable. The only function of several variables you ever need is addition. Network researchers noticed it in the eighties, and argued: in 1989 Federico Girosi and Tomaso Poggio called it irrelevant, because the inner functions can be wildly irregular; in 1991 Vera Kurkova answered that smooth approximate versions work, with error bounds.
In April 2024 Ziming Liu, Max Tegmark and colleagues turned the theorem into an architecture. An ordinary network puts a number on every edge and a fixed bend at every node. A Kolmogorov–Arnold network puts a learnable curve on every edge, a smooth spline on a grid of points, and only adds at the nodes. Our experiment also applies tanh to each hidden sum, keeping the next layer's inputs between minus one and one. Unlike the theorem's version, the layers can be stacked as deep as you like. They reported that small KANs fit scientific formulas more accurately than much larger MLPs, that their error falls faster as they grow, and that you can read the learned curves and recover the formula.
Let's try it, on the example from their paper: e to the sine of pi x, plus y squared. Here is a KAN with two inputs, five hidden nodes and one output: fifteen curves, all of them learned. Watch them as it trains.
Then came the debate. That's the kind of task the paper chose. In July 2024 Runpeng Yu, Weihao Yu and Xinchao Wang compared the two fairly, at equal numbers of parameters and operations, on images, text, audio and tables. MLPs generally won. KANs won on symbolic formulas, and forgot more of an old task when taught a new one. The KAN authors' sequel that August leaned into science: finding formulas and conserved quantities. And inside today's language models, the published configurations still show gated MLPs. A theorem from 1957 found a niche, not a revolution.
15A neural language modelEngineering2 min
Now let's use a network for the task that runs through this whole series: guess the next character. In 2003 Yoshua Bengio, Rejean Ducharme, Pascal Vincent and Christian Jauvin published an influential neural language model, for words. Here is its design, for characters. Take the last characters. Each character becomes a vector of numbers, looked up in a table that is itself learned. The vectors go through one hidden layer of tanh units. And out comes a score for every possible next character, turned into probabilities by Part 1's softmax. Every number in it is learned together, by backpropagation.
Train it on Part 1's thirty novels, by gradient descent, with Part 1's cross-entropy as the loss. Below the curve, what it writes at each moment of training, always from the same prompt and the same random draws.
Bengio's team found that their best results came from combining the network with a counting model: averaging the two predictions. Here the weight is chosen on the first two hundred thousand validation characters, scoring positions 24 through 199,999, counted from zero. It is not chosen on the passage.
And the vectors the network scores each next character with, which nobody designed, have organized themselves. Seen along their two main directions, from Part 7, characters that behave alike sit together: lowercase letters with lowercase letters, capitals with capitals, digits with digits, and punctuation in its own corner. It's Part 3's word vectors again, learned this time as a side effect of predicting.
Here are two separate result groups. Our network and its mixture score the same 21,382 targets. The historical Kneser–Ney and infinity-gram mixture score 21,399 targets. The starting positions differ, so these groups do not establish a ranking against each other. The network sees only twenty-four characters, with one hidden layer.
Here's what it writes, from Part 5's prompt and three others: English-shaped, word-shaped, and not yet making sense.
Recap, problems, and where this comes backAll tracks2 min
Let's take stock. A unit is a weighted sum and a threshold, and the perceptron learns one from its mistakes, provably, whenever a line separates the data. One layer can't do XOR; two can, and backpropagation trains them, in one sweep backwards. One hidden layer can approximate any curve, and for smooth enough functions the number of units doesn't explode with the dimension. Depth folds space into exponentially many pieces. Weights must start on the edge of chaos, two over n for ReLUs, or signals vanish or explode, and residual streams and normalization keep gradients flowing through many layers.
All of this comes back. Weight sharing over space and time gives the convolutional and recurrent networks of Part 10. How to set the scale of weights and learning rates as networks grow is the subject of Parts 11 and 12. The residual stream is the backbone of the transformer in Part 13, and what we read when we look inside models, in Part 30. Normalization comes back inside attention. The gated MLP, multiplied, becomes the experts of Part 16. And learned embeddings, of characters here, become embeddings of tokens, images and sounds.
Here are six problems to try, from the perceptron's learning rate to the Jacobian of RMSNorm. Pause here and work through them; full solutions are in this part's notes.
Next time: seeing and remembering. A network that slides one small filter over an image, sharing its weights everywhere; 2012, when one of them won ImageNet by a wide margin; networks with loops that remember, the LSTM, and the first attention mechanism; and a character LSTM on our scoreboard.
Simon Prince's Understanding Deep Learning is the clearest modern textbook, and free to read. Thanks for watching, and see you in Part 10.
Where it goes next. Weight sharing over space and time gives the convolutional and recurrent networks of Part 10. How to scale weights and learning rates as networks grow is the subject of Parts 11 and 12. The residual stream is the backbone of the transformer in Part 13 and what Part 30 reads inside models; the gated MLP, multiplied, becomes the experts of Part 16; learned embeddings of characters become embeddings of tokens, images and sounds.
Key results
The part's results in one place, for revision.
Try it
Lab 9 · Backpropagation on XOR, checked three ways
Compute the nine gradients of a 2-2-1 tanh network by the series' autodiff, by the delta equations and by finite differences; then train on XOR from twenty random starts and count how many find a solution.
python -m videos.ai.labs 9
needs numpy, scipy, matplotlib · download lab09.py ·
source on GitHubnine gradients: autodiff against the delta equations largest difference 1.4e-17
nine gradients: autodiff against finite differences largest difference 1.3e-10
starts that solve XOR 10 of 20
final loss of the solved starts at most 0.0062 nats
final loss of the stuck starts at least 0.349 nats
best of 68,921 single units (lines) on XOR 75% of the four points
The chain rule run backwards gives the same nine numbers as differencing the loss; with them a hidden layer of two units can learn XOR, though not from every start, and no single unit can.
The code (126 lines; it asserts its own result)
"""Lab 9: backpropagate through a 2-2-1 network three ways, then train it on XOR from twenty random starts."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, sigmoid
TITLE = "Backpropagation on XOR, checked three ways"
GOAL = ("Compute the nine gradients of a 2-2-1 tanh network by the series' autodiff, by the delta equations and by finite "
"differences; then train on XOR from twenty random starts and count how many find a solution.")
TASKS = [
"Give the hidden layer 4 units instead of 2. How many of the twenty starts get stuck now?",
"Replace tanh by relu in the hidden layer (in both forward passes and in the delta equations). Do the three gradients still agree, and how many starts solve XOR?",
"Remove the hidden layer and train the single unit on AND, OR and XOR. Which of the three can it learn, and why?",
]
X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
Y = np.array([0.0, 1.0, 1.0, 0.0])
def init(rng, hidden=2):
return dict(W1=rng.normal(0, 1.0, (2, hidden)), b1=rng.normal(0, 0.5, hidden), W2=rng.normal(0, 1.0, (hidden, 1)), b2=np.zeros(1))
def forward(p, x=X):
h = np.tanh(x @ p["W1"] + p["b1"])
return h, 1 / (1 + np.exp(-((h @ p["W2"])[:, 0] + p["b2"][0])))
def loss_np(p):
q = np.clip(forward(p)[1], 1e-12, 1 - 1e-12)
return float(-(Y * np.log(q) + (1 - Y) * np.log(1 - q)).mean())
def grad_autodiff(p):
"""The loss and its gradients by the series' reverse-mode autodiff."""
t = {k: Tensor(v, requires_grad=True) for k, v in p.items()}
q = sigmoid((Tensor(X) @ t["W1"] + t["b1"]).tanh() @ t["W2"] + t["b2"])
y = Y[:, None]
loss = -((q.log() * y) + ((1 - q).log() * (1 - y))).mean()
loss.backward()
return float(loss.data), {k: t[k].grad.copy() for k in p}
def grad_delta(p):
"""The delta equations by hand: delta2 = q - y at a sigmoid output with cross-entropy, delta1 = W2 delta2 (.) tanh'."""
h, q = forward(p)
d2 = (q - Y) / len(X)
d1 = np.outer(d2, p["W2"][:, 0]) * (1 - h ** 2)
return dict(W1=X.T @ d1, b1=d1.sum(0), W2=(h.T @ d2)[:, None], b2=np.array([d2.sum()]))
def grad_numeric(p, eps=1e-6):
g = {k: np.zeros_like(v) for k, v in p.items()}
for k, v in p.items():
for idx in np.ndindex(v.shape):
up, down = ({kk: vv.copy() for kk, vv in p.items()} for _ in range(2))
up[k][idx] += eps
down[k][idx] -= eps
g[k][idx] = (loss_np(up) - loss_np(down)) / (2 * eps)
return g
def run(seed=0):
rng = np.random.default_rng(seed)
flat = lambda g: np.concatenate([g[k].ravel() for k in ("W1", "b1", "W2", "b2")])
p = init(rng)
g_ad, g_bp, g_fd = flat(grad_autodiff(p)[1]), flat(grad_delta(p)), flat(grad_numeric(p))
err_bp, err_fd = np.abs(g_ad - g_bp).max(), np.abs(g_ad - g_fd).max()
starts, steps, lr = 20, 600, 1.0
curves, solved, nets = [], [], []
for _ in range(starts):
p = init(rng)
losses = []
for _ in range(steps):
loss, g = grad_autodiff(p)
losses.append(loss)
for k in p:
p[k] -= lr * g[k]
curves.append(losses)
solved.append(bool(((forward(p)[1] > 0.5) == (Y > 0.5)).all()))
nets.append(p)
solved = np.array(solved)
final = np.array([c[-1] for c in curves])
# one unit, no hidden layer: try every line w1 x1 + w2 x2 + b > 0 on a grid of weights
w = np.linspace(-2, 2, 41)
w1, w2, b = np.meshgrid(w, w, w, indexing="ij")
fires = w1[..., None] * X[:, 0] + w2[..., None] * X[:, 1] + b[..., None] > 0
best_line = (fires == (Y > 0.5)).mean(-1).max()
lab = labs.Lab()
lab.row("nine gradients: autodiff against the delta equations", f"largest difference {err_bp:.1e}")
lab.row("nine gradients: autodiff against finite differences", f"largest difference {err_fd:.1e}")
lab.row("starts that solve XOR", f"{solved.sum()} of {starts}")
lab.row("final loss of the solved starts", f"at most {final[solved].max():.4f} nats" if solved.any() else "none solved")
lab.row("final loss of the stuck starts", f"at least {final[~solved].min():.3f} nats" if (~solved).any() else "none stuck")
lab.row("best of 68,921 single units (lines) on XOR", f"{best_line:.0%} of the four points")
lab.note = ("The chain rule run backwards gives the same nine numbers as differencing the loss; with them a hidden "
"layer of two units can learn XOR, though not from every start, and no single unit can.")
assert err_bp < 1e-12 and err_fd < 1e-7, "three ways to the same gradient"
assert solved.any(), "a hidden layer can represent and learn XOR"
assert np.median(final[solved]) < 0.05, "the solved starts drive the loss toward zero"
assert solved.all() or np.median(final[~solved]) > 0.3, "the stuck starts sit on a plateau with a point wrong"
assert best_line <= 0.75, "no line separates XOR"
fig, ax = labs.figure(2, size=(11, 4.2))
for c, ok in zip(curves, solved):
ax[0].plot(np.arange(1, steps + 1), c, color=labs.GOLD if ok else labs.RED, lw=1.1, alpha=0.8)
ax[0].plot([], [], color=labs.GOLD, label=f"solved ({solved.sum()})")
ax[0].plot([], [], color=labs.RED, label=f"stuck ({(~solved).sum()})")
ax[0].set(xscale="log", yscale="log", title="Twenty starts on XOR", xlabel="gradient-descent step", ylabel="cross-entropy (nats)")
ax[0].legend(loc="lower left")
best = nets[int(np.argmin(final))]
u = np.linspace(-0.4, 1.4, 121)
gx, gy = np.meshgrid(u, u)
q = forward(best, np.column_stack([gx.ravel(), gy.ravel()]))[1].reshape(gx.shape)
ax[1].contourf(gx, gy, q, levels=np.linspace(0, 1, 11), cmap="cividis", alpha=0.9)
ax[1].contour(gx, gy, q, levels=[0.5], colors=[labs.INK], linewidths=1.5)
ax[1].scatter(X[:, 0], X[:, 1], c=[labs.GOLD if t else labs.BLUE for t in Y], s=120, edgecolors=labs.BG, linewidths=1.5, zorder=3)
ax[1].set(title="One solved network (white: output 0.5)", xlabel="input 1", ylabel="input 2", aspect="equal")
ax[1].grid(False)
lab.fig = fig
return lab
Now change it
- Give the hidden layer 4 units instead of 2. How many of the twenty starts get stuck now?
- Replace tanh by relu in the hidden layer (in both forward passes and in the delta equations). Do the three gradients still agree, and how many starts solve XOR?
- Remove the hidden layer and train the single unit on AND, OR and XOR. Which of the three can it learn, and why?
Problems, with solutions
Try each problem before opening its solution.
1. The learning rate doesn't matter. Show that the perceptron started from w₀ = 0 makes exactly the same mistakes with the update w ← w + η y x, for any η > 0, as with η = 1.
Solution
By induction, the weights with rate η are η times the weights with rate 1: both start at 0, and if w^(η) = η w^(1) then sign(w^(η)·x) = sign(w^(1)·x), so the same examples are mistakes and the updates η y x and y x keep the proportion. The rate only rescales w, and the sign of w·x never sees the scale.
2. XOR with two ReLUs. Find weights for a 2–2–1 ReLU network that computes XOR exactly on {0, 1}².
Solution
h₁ = max(0, x₁ + x₂), h₂ = max(0, x₁ + x₂ − 1), y = h₁ − 2h₂. For (0, 0): 0. For (0, 1) and (1, 0): h₁ = 1, h₂ = 0, so 1. For (1, 1): h₁ = 2, h₂ = 1, so 0. The hidden layer folds the line x₁ + x₂ at 1, the tent of chapter seven.
3. How fast sigmoid gradients vanish. For sigmoid units, show σ′ ≤ ¼. If every weight matrix has operator norm at most 1, show that ‖δ^l‖ shrinks by at least a factor of 4 per layer.
Solution
σ′ = σ(1 − σ), and a product of two numbers with sum 1 is at most (½)² = ¼. From δ^l = (W^{l+1})ᵀδ^{l+1} ⊙ σ′(z^l), ‖δ^l‖ ≤ ‖W^{l+1}‖ · max|σ′| · ‖δ^{l+1}‖ ≤ ¼‖δ^{l+1}‖, so ‖δ^l‖ ≤ 4^{−(L−l)}‖δ^L‖: at least a factor of 4 per layer, 10⁻¹² after twenty layers. Larger weights can offset it, which is what initialization is about.
4. He's rule. For z ~ N(0, q), show E[max(0, z)²] = q/2, and deduce Var(W) = 2/n.
Solution
By symmetry, ∫₀^∞ z² φ(z) dz is half of ∫ z² φ(z) dz = q. For z_i = Σ_j W_ij a_j with independent weights of mean 0 and a_j = max(0, z_j^{prev}), Var(z) = n Var(W) E[a²] = n Var(W) q_prev / 2, which equals q_prev exactly when Var(W) = 2/n.
5. Depth counts pieces. Show that the k-fold composition of the tent map t(x) = 1 − |2x − 1| on [0, 1] has 2^k linear pieces, while one hidden layer of m ReLUs on ℝ has at most m + 1.
Solution
t maps [0, ½] and [½, 1] each linearly onto [0, 1]. If t^k has 2^k pieces, each mapping its interval monotonically onto [0, 1], then on each piece t^{k+1} = t ∘ t^k breaks at the one point where t^k = ½, giving two pieces that each map onto [0, 1]: 2^{k+1}. A one-layer network c + Σ a_i max(0, w_i x + b_i) is linear except at the m kinks −b_i/w_i, so it has at most m + 1 pieces, and needs m ≥ 2^k − 1 units to equal t^k; k layers of 2 units do it.
6. RMSNorm's Jacobian. For y = √d h / ‖h‖, show ∂y/∂h = (√d/‖h‖)(I − ĥĥᵀ), with ĥ = h/‖h‖. What does this imply about the gradient with respect to h?
Solution
∂(h/‖h‖)/∂h = I/‖h‖ − h hᵀ/‖h‖³ = (I − ĥĥᵀ)/‖h‖. The matrix is symmetric and sends h to 0, so the gradient Jᵀg = Jg is orthogonal to h: RMSNorm's input never gets a gradient along itself, and doubling h halves the gradient.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| artificial neuron, unit | 人工神经元,单元 |
| McCulloch–Pitts unit, threshold | 麦卡洛克–皮茨单元,阈值 |
| Hebb's rule | 赫布规则 |
| perceptron, Mark I Perceptron | 感知机,Mark I感知机 |
| association unit, response unit | 联想单元,响应单元 |
| ADALINE, least mean squares (LMS) | ADALINE,最小均方 |
| margin, convergence theorem | 间隔,收敛定理 |
| linearly separable | 线性可分 |
| XOR, parity, connectedness | 异或,奇偶性,连通性 |
| hidden layer, hidden unit | 隐藏层,隐藏单元 |
| backpropagation, delta (δ) | 反向传播,delta(δ) |
| forward pass, backward pass | 前向传播,反向传播 |
| finite differences | 有限差分 |
| reverse-mode automatic differentiation | 自动微分的反向模式 |
| universal approximation theorem | 万能近似定理 |
| hinge, bump | 铰链,鼓包 |
| rectified linear unit (ReLU) | 线性整流单元(ReLU) |
| curse of dimensionality | 维数灾难 |
| Barron's bound | 巴伦界 |
| linear region (piece) | 线性区域(小块) |
| depth separation | 深度分离 |
| folding | 折叠 |
| vanishing / exploding gradients | 梯度消失 / 梯度爆炸 |
| deep belief net, greedy layer-wise pretraining | 深度信念网络,逐层贪心预训练 |
| initialization (Glorot / Xavier, He) | 初始化(格洛罗初始化,何恺明初始化) |
| mean-field theory | 平均场理论 |
| length map, correlation map | 长度映射,相关映射 |
| ordered phase, chaotic phase, edge of chaos | 有序相,混沌相,混沌的边缘 |
| depth scale (ξ) | 深度尺度(ξ) |
| residual connection, residual stream | 残差连接,残差流 |
| highway network | 高速公路网络 |
| batch normalization, layer normalization, RMSNorm | 批归一化,层归一化,RMSNorm |
| pre-norm, post-norm, warm-up | 前置归一化,后置归一化,预热 |
| internal covariate shift | 内部协变量偏移 |
| Jacobian, singular value | 雅可比矩阵,奇异值 |
| GELU, SiLU (Swish) | GELU,SiLU(Swish) |
| gating, gated linear unit (GLU), SwiGLU | 门控,门控线性单元(GLU),SwiGLU |
| feed-forward network (MLP) | 前馈网络(MLP) |
| Kolmogorov–Arnold representation theorem | 柯尔莫哥洛夫–阿诺德表示定理 |
| Kolmogorov–Arnold network (KAN), spline | 柯尔莫哥洛夫–阿诺德网络(KAN),样条 |
| neural language model, embedding | 神经语言模型,嵌入 |
| Hilbert's thirteenth problem | 希尔伯特第13问题 |
About this partfrom its README
Part 9 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan
and the syllabus). How neural networks came to be, from the first artificial neuron to the block
inside today's language models: the perceptron and its convergence proof, what one layer cannot do and the winter that
followed, backpropagation, what one and many layers can represent, why deep networks were so hard to train and the
fixes (initialization, the edge of chaos, residual streams, normalization), modern activations and gating,
Kolmogorov–Arnold networks, and the first neural language model on the series' scoreboard. Every network here is
trained on this computer, by compute.py (PyTorch on the CPU, or the series' own autodiff from Part 4).
- How we got here. 1943 to 2012 on one strip, with the two winters shaded (schematic): McCulloch & Pitts, Rosenblatt, Minsky & Papert, backpropagation, LeCun's zip codes, deep belief nets, AlexNet. Then two interleaved spirals learned by a 2 → 32 → 32 → 32 → 2 ReLU network, replayed through twelve checkpoints with its decision regions, its linear pieces (thousands of them) and its accuracy curve.
- 1. The first neurons. McCulloch & Pitts (1943): threshold units compute AND, OR, NOT, so networks of them compute any logical formula; Hebb's postulate (1949, quoted from p. 62); Rosenblatt's perceptron (1958: simulated on an IBM 704; the New York Times of 8 July 1958); the Mark I Perceptron (1960: 400 photocells, 512 association units, 8 response units, motor-driven potentiometers); Widrow & Hoff's ADALINE and the LMS rule (1960) derived as stochastic gradient descent on the squared error.
- 2. The perceptron learns. The rule w ← w + y x on mistakes and its geometry; trained live on 50 separable points (13 mistakes over 5 passes); Novikoff's theorem (1962) proved on screen: k ≤ (R/γ)², with R and the best margin γ computed and drawn on the data (bound 334); the bound against reality on six data sets of shrinking margin, 20 orders each (the worst run uses at most 16% of it); what it doesn't promise (the widest margin: Part 6's SVM).
- 3. XOR, and the first winter. XOR is not linearly separable (four inequalities, a contradiction); the perceptron cycles forever on it; Minsky & Papert's Perceptrons (1969), parity and connectedness, and their "intuitive judgment that the extension is sterile" (pp. 231–232); Rosenblatt's death (1971), Fukushima's neocognitron (1980), Hopfield (1982). A 2–2–1 tanh network trained on XOR with the series' own autodiff, replayed: the input square's decision region and the hidden layer's bent grid, where the four points become separable; 7 of 20 random starts solve it, the rest stop in a local minimum with one point wrong.
- 4. Backpropagation. Credit assignment; the delta equations derived (δ^L = ∇L ⊙ φ′, δ^l = (W^{l+1})ᵀδ^{l+1} ⊙ φ′, ∂L/∂W^l = δ^l a^{l−1 ᵀ}); values forward and errors backward as pulses; the cost (backward ≈ 2× forward, ~6 operations per weight per example, Part 12's C ≈ 6ND); the XOR network's nine gradients three ways (our autodiff, the hand-written delta equations, finite differences) agreeing to 4·10⁻¹⁷ and 5·10⁻¹⁰; Linnainmaa (1970), Werbos (1974), Rumelhart, Hinton & Williams (1986), LeCun et al. (1989).
- 5. One layer can do anything. A unit as a hinge; a curve from 2 to 64 hinges by least squares; the miss falls like n⁻² (the chord bound h²/8·max|f″| derived; measured slope −2.01); three hinges make a bump, bumps make any curve; the universal approximation theorem (Cybenko 1989; Hornik, Stinchcombe & White 1989; Leshno, Lin, Pinkus & Schocken 1993) and what it doesn't say.
- 6. Escaping the curse of dimensionality. A grid needs m^d points: miss ∝ n^{−2/d}; Maurey's argument derived (a Gaussian bump is an average of cosine units; n random units miss by ≤ 1/√n in any dimension); computed: grid slopes −2.0, −1.0, −0.57, −0.34 in d = 1, 2, 4, 8, against random-unit slopes −0.48 to −0.49 in d = 1 to 64; Barron's theorem (1993), his lower bound n^{−1/d} for fixed bases, and the catch.
- 7. What depth adds. The tent map composed k times (2^k pieces from 2k units); Telgarsky's depth separation (2016); the plane folded by ReLU layers (alternate folds 2|t| − 1, 1 → 32 linear pieces, an F mirrored into every piece); one layer of n units cuts the plane into ≤ 1 + n + C(n,2) pieces (Zaslavsky 1975), counted for n = 1…6; Montúfar et al. (2014); 48 random units in 1 to 6 layers give about the same number of pieces (Hanin & Rolnick 2019); the spiral network's pieces before and after training.
- 8. The second winter, and the revival. Vanishing gradients (Hochreiter 1991; Bengio, Simard & Frasconi 1994) measured through 50 sigmoid layers with the 1990s initialization; SVMs (1995), LSTM (1997), LeNet (1998); CIFAR's program (2004); deep belief nets (Hinton, Osindero & Teh 2006) as greedy layer-wise pretraining (schematic); GPUs (Raina et al. 2009; Cireşan et al. 2010, plain backpropagation), Glorot & Bengio (2010), ReLUs, speech and AlexNet (2012), the 2018 Turing Award.
- 9. Initialization, derived. 50 layers of 256 ReLUs: weights 0.7× too small shrink the signal about thirty million times, 1.4× too big grow it about ten million times; Var(z) = n·Var(W)·E[a²] derived: LeCun's 1/n_in, the backward 1/n_out, Glorot's 2/(n_in + n_out); ReLU keeps half: He's 2/n; a 3D ridge plot of a 50-layer tanh network's activation histograms through depth for the old U[−1/√n, 1/√n], Glorot's 1/n and 4/n.
- 10. The edge of chaos. Mean-field theory (Poole et al. 2016; Schoenholz et al. 2017): the length map and its fixed point (cobweb); the correlation map and χ₁; ordered, critical and chaotic phases, against a real network of width 1,000; the phase diagram over (σ_w², σ_b²) for tanh, whose edge meets σ_b = 0 at σ_w² = 1.00 (Glorot), and χ₁ = σ_w²/2 for ReLU (He); the depth scale ξ_c and trainability, computed: tanh networks of depth 5 to 100 at 12 weight variances, 300 RMSProp steps each, whose trainable region narrows toward the edge with depth and agrees with Schoenholz et al.'s L ≲ 6ξ_c on 86% of the grid; ten-thousand-layer CNNs (Xiao et al. 2018).
- 11. The residual stream. h + f(h); the identity in every block's Jacobian; 40 plain layers against 40 residual layers on the spirals; inside both as they train (answers and per-layer gradients, replayed); the product (I + J_L)⋯(I + J_1) expanded into 2^L paths (Veit, Wilber & Belongie 2016); highway networks (2015), ResNet's 152 layers, GPT-2's 1/√N.
- 12. Normalization. BatchNorm (Ioffe & Szegedy 2015) and the covariate-shift debate (Santurkar et al. 2018); LayerNorm (Ba, Kiros & Hinton 2016); RMSNorm (Zhang & Sennrich 2019) as projection onto a sphere; the Jacobians derived ((√d/‖h‖)(I − ĥĥᵀ); LayerNorm also removes the all-ones direction) and measured by autograd (singular values 15 equal + 1 zero; 14 + 2); scale invariance; post-norm (2017) against pre-norm (GPT-2, Xiong et al. 2020) in our 24-block model: starting gradients by block and held-out bits; OLMo 2's output norm (2024) and Dynamic Tanh (2025).
- 13. The modern block. Sigmoid, tanh, ReLU, GELU (Hendrycks & Gimpel 2016, derived from a Gaussian coin) and SiLU (Elfwing et al.; Ramachandran et al. 2017); gating (Dauphin et al., 2016) as a 3D surface; SwiGLU (Shazeer 2020) and the 8d/3 width; published configurations (GPT-2 4d; Llama 2 7B 11,008 = 8/3·4,096 rounded to 256; Llama 3 8B 14,336; Qwen3-8B 12,288); the block assembled, Llama 3 8B counted from its configuration (41.9M attention + 176.2M MLP weights per block, 8.03B in all); an ablation in a 24-block character model on the novels, 1,200 steps each, same data and seed: plain 4.46 bits/char (stuck), + residual 2.95, post-LN 4.45 (stalls without warm-up), pre-LN 3.02, pre-RMSNorm 3.01, + SwiGLU 2.88 (best).
- 14. Kolmogorov–Arnold networks. Hilbert's 13th problem (1900); Kolmogorov and Arnold (1957); Girosi & Poggio's "irrelevant" (1989) and Kůrková's "relevant" (1991); KANs (Liu et al. 2024); a [2, 5, 1] KAN and an MLP of the same size trained on exp(sin πx + y²) (test error 0.017 for 135 parameters against 0.040 for 151), the KAN's fifteen learned curves replayed (the closest match a sine and a square with correlations 0.997 and 0.987); KANs and MLPs by size; Yu, Yu & Wang's fairer comparison (2024), KAN 2.0, and what frontier models use.
- 15. A neural language model. Bengio, Ducharme, Vincent & Jauvin's design (2003) for characters (24 characters of context, learned 32-number vectors, 1,024 tanh units, direct connections; 1.09 million weights), trained on Part 1's books for 24,000 steps of 512 positions, replayed: the bits-per-character curve with what it writes at nine checkpoints (real words among its words: 0% at the start, 28% by step 1,000, 70% at the end). It reaches 2.38 bits per character on the passage: within 0.05 of Part 1's best counting model (2.32) and short of Part 7's Kneser–Ney (order 7, 2.04). Mixed with Kneser–Ney (the network's weight, 0.13, chosen on held-out text) it reaches 1.99, the best machine on the board; the output layer's character vectors; the scoreboard's new rows.
- Recap in eight computed pictures, where it comes back, six problems, Part 10's teaser, references.
Run from the repo root:
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- History: McCulloch–Pitts (1943); Rosenblatt's Mark I perceptron (1958); Minsky–Papert and XOR (1969); backprop (Rumelhart, Hinton, Williams 1986); deep belief nets (2006).
- Perceptron and Novikoff's convergence proof.
- Universal approximation built from ReLU bumps; Barron's dimension-free rate.
- Depth separation by sawtooth composition (2^L pieces); linear regions counted.
- Xavier/He derived; mean-field signal propagation, the edge of chaos; gradients through 50 layers.
- Residuals; BatchNorm, LayerNorm, RMSNorm Jacobians; pre- vs post-norm.
- Activations: GELU, SiLU, SwiGLU gating.
- The modern block.
- KANs and the Kolmogorov–Arnold theorem (the 2024 debate).
- Bengio 2003: the neural n-gram, scoreboard row.
Visuals: FoldPlane; activation histograms as a 3D ridge plot through depth.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 学习率无关紧要。 证明:感知机从 w₀ = 0 出发,用更新 w ← w + η y x(任意 η > 0)犯的错误,和 η = 1 时完全一样。
解答
用归纳法:学习率为η时的权重,等于学习率为1时的权重的η倍。两者都从0出发;若 w^(η) = η w^(1),则 sign(w^(η)·x) = sign(w^(1)·x),所以判错的是同样的例子,而更新 η y x 和 y x 保持这个比例。学习率只是缩放w,而w·x的符号看不到尺度。
2. 用两个ReLU做异或。 给一个2–2–1的ReLU网络找出权重,使它在 {0, 1}² 上精确地算出异或。
解答
h₁ = max(0, x₁ + x₂),h₂ = max(0, x₁ + x₂ − 1),y = h₁ − 2h₂。(0, 0):0。(0, 1)和(1, 0):h₁ = 1,h₂ = 0,得1。 (1, 1):h₁ = 2,h₂ = 1,得0。隐藏层在x₁ + x₂ = 1处把直线折了一下,正是第7章的帐篷。
3. sigmoid的梯度消失得有多快。 证明sigmoid满足 σ′ ≤ ¼。如果每个权重矩阵的算子范数都不超过1,证明‖δ^l‖每往下一层,至少缩小为原来的4分之1。
解答
σ′ = σ(1 − σ),两个和为1的数之积至多是 (½)² = ¼。由 δ^l = (W^{l+1})ᵀδ^{l+1} ⊙ σ′(z^l),得 ‖δ^l‖ ≤ ‖W^{l+1}‖ · max|σ′| · ‖δ^{l+1}‖ ≤ ¼‖δ^{l+1}‖,所以 ‖δ^l‖ ≤ 4^{−(L−l)}‖δ^L‖:每层至少缩小4倍,20层后是10⁻¹²。 更大的权重可以抵消它,这正是初始化要处理的事。
4. 何恺明的规则。 对 z ~ N(0, q),证明 E[max(0, z)²] = q/2,并推出 Var(W) = 2/n。
解答
由对称性,∫₀^∞ z² φ(z) dz 是 ∫ z² φ(z) dz = q 的一半。对 z_i = Σ_j W_ij a_j,权重独立、均值为0, a_j = max(0, z_j^{prev}),有 Var(z) = n Var(W) E[a²] = n Var(W) q_prev / 2,它等于 q_prev 当且仅当 Var(W) = 2/n。
5. 深度数出小块。 证明[0, 1]上的帐篷映射 t(x) = 1 − |2x − 1| 复合k次后有2^k个线性段,而ℝ上一个由m个ReLU组成的隐藏层至多有m + 1段。
解答
t把[0, ½]和[½, 1]各自线性地映到[0, 1]上。若t^k有2^k段,每段都单调地映满[0, 1],那么在每一段上,t^{k+1} = t ∘ t^k 在t^k = ½的那一点断开,得到两段,各自映满[0, 1]:共2^{k+1}段。单层网络 c + Σ a_i max(0, w_i x + b_i) 除了m个折点−b_i/w_i之外 都是线性的,所以至多m + 1段;要等于t^k,需要 m ≥ 2^k − 1 个单元,而k层、每层2个单元就够了。
6. RMSNorm的雅可比矩阵。 对 y = √d h / ‖h‖,证明 ∂y/∂h = (√d/‖h‖)(I − ĥĥᵀ),其中 ĥ = h/‖h‖。这对关于h的梯度意味着什么?
解答
∂(h/‖h‖)/∂h = I/‖h‖ − h hᵀ/‖h‖³ = (I − ĥĥᵀ)/‖h‖。这个矩阵是对称的,并且把h送到0,所以梯度 Jᵀg = Jg 与h正交: RMSNorm的输入永远得不到沿它自身方向的梯度,而h加倍时,梯度减半。
Build the film
python -m videos.ai.ai9.compute # the part's numbers, into .cache/ai9
python tools/build.py ai9 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai9 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai9. Setup: see the course page. Source of these notes: the README and the scenes' narration.