AAI, Built

Act II · Learning from Data

Part 10 of 31

Seeing and Remembering

Undergraduatestarts at this level54 min of film18 chaptersprerequisites: Part 6, Part 7, Part 9

How did machines learn to see an image and to remember a sentence?

The part opens in the late 1950s with Hubel and Wiesel's cat, a cortical cell that fires for an edge at one angle, and then shows the first-layer filters of a network trained here on CIFAR-10 and counts those that pick out one orientation. Vision before deep learning was designed features (Sobel, SIFT, HOG) under a learned linear classifier. Convolution replaces them: shared weights, translation equivariance proved, receptive fields computed layer by layer. LeNet reads digits, ImageNet supplies the data, and AlexNet wins in 2012 with ReLUs, dropout and GPUs; VGG, Inception and ResNet go deeper. The part looks at what the filters learn and how a perturbation of one step along the sign of the gradient fools them. It then turns from space to time: a recurrent network's gradient is a product of Jacobians that vanishes or explodes, the LSTM's cell carries it on a path with derivative diag(f), and a character LSTM takes a row on the scoreboard. It ends with sequence-to-sequence translation, the attention Bahdanau, Cho and Bengio added in 2014, and the linear recurrences and parallel scans of today's recurrent models.

What you need. Part 9's backpropagation, initialization and residual connections; sums over a sliding window.

Mathematics and history
convolution and equivariance, the ImageNet moment, adversarial examples, RNNs, LSTMs, seq2seq, the first attention
Models, data
LeNet, AlexNet, ResNet, a character LSTM

What you will be able to do

Undergraduate

  • Compute a convolution of a small image with a 3 x 3 kernel by hand, and count the weights that sharing saves against a fully connected layer.
  • Tell the story from LeNet to AlexNet to ResNet: what changed in 2012, and which ingredients were already known.
  • Explain what the cell and the gates of an LSTM do, in words and on a drawing.

Master's

  • Prove that convolution commutes with translation, and compute a stack's receptive field from its kernels and strides.
  • Derive the product of Jacobians in backpropagation through time and its bound, and the half-life of an LSTM's cell path.
  • Write one step of an encoder-decoder with additive attention: scores, softmax, context vector.

Research

  • Derive the fast gradient sign method from the linearity argument, and compare FGSM, PGD and adversarial training under one threat model.
  • Show that a linear recurrence is an associative scan, and state what minGRU and xLSTM give up and gain against attention.

Engineering

  • Compute the cost ratio of a depthwise separable convolution, and explain why measured speed-ups differ from the FLOP ratio.
  • Decode from a sequence model greedily and with a beam, and recognise exposure bias and degenerate repetition in the output.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 19 min · Master's 46 min · Research 54 min · Engineering 25 min.

  1. 0The edge that lit a neuronUndergraduate3 min
  2. 1Vision before deep learningUndergraduate3 min
  3. 2ConvolutionUndergraduate3 min
  4. 3Receptive fields, stride and poolingMaster's2 min
  5. 4LeNet and MNISTUndergraduate3 min
  6. 5ImageNet and AlexNetUndergraduate3 min
  7. 6Why AlexNet wonMaster's3 min
  8. 7Deeper: VGG, Inception, ResNetMaster's3 min
  9. 8What the filters learnMaster's3 min
  10. 9Adversarial examplesResearch4 min
  11. 10Cheaper convolutionsEngineering3 min
  12. 11Recurrence and vanishing gradientsMaster's3 min
  13. 12LSTM and GRUMaster's3 min
  14. 13A character LSTMUndergraduate2 min
  15. 14Sequence to sequenceEngineering3 min
  16. 15The birth of attentionMaster's3 min
  17. 16Recurrence returnsResearch3 min
  18. Recap, problems, and what comes nextAll 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.

The edge that lit a neuronUndergraduate3 min

In the late 1950s, at Johns Hopkins, David Hubel and Torsten Wiesel were recording from single neurons in the visual cortex of a cat, while it looked at a screen. Spots of light, their stimulus of the day, did almost nothing. Then, as Hubel told it, while they slid a glass slide into the projector, the faint straight shadow of its edge swept across the screen, and the cell began to fire in a burst. It wanted an edge, at one particular angle, in one particular place.

Decades later, here is a network trained on the computer making this video. It looked at fifty thousand small photographs, times over, for about minutes. These are the filters its first layer grew. of the pick out an edge at one orientation, like Hubel and Wiesel's cell. Nobody told it about edges. It found them because they were useful.

Seeing is half of this part. The other half is remembering. In 2014 networks learned to read a whole sentence and write it in another language. And that year they learned to look back: at each word they wrote, to pick out the words of the input they needed. This is a small one, trained here to write strings backwards; the bright squares are where it looked. This was attention for neural translation.

How did machines learn to see, and to remember? We'll follow the path from Hubel and Wiesel's cells to LeNet, ImageNet, and networks a hundred and fifty layers deep. Then time: recurrent networks, the LSTM, translation, and the attention that grew out of it. And we'll train every kind of network we meet, on this computer, and watch it learn.

This is Part 10 of AI, Built, in the second act, learning from data: after Part 9's networks, and before Part 11's optimizers. Here is the plan: vision before deep learning, and the convolution that replaced it; the deep networks, what they learn, and how to fool them; then memory, from the LSTM to attention, and back.

1Vision before deep learningUndergraduate3 min

In 1962 Hubel and Wiesel sorted the cells they found into two kinds. A simple cell responds to an edge or a bar at one angle, in one small patch of what the eye sees: light on its bright stripe excites it, light beside the stripe holds it back. A complex cell responds to the same angle anywhere in a larger patch, as if it collected several simple cells and fired when any of them did. Detect a feature, then pool over position, and do it again, layer upon layer. That picture won them a Nobel Prize in 1981, and it is almost exactly the design of this part's networks.

Computer vision began the same way, with edges. An edge is where the brightness changes quickly, so take the derivative of the image. In practice, the difference between the pixels on either side, divided by their spacing, across and down. On a handwritten digit, each arrow points uphill in brightness, across the stroke. On a photograph, the length of the gradient, in Irwin Sobel's 1968 version, draws the outline of the horse. For decades every vision system started here.

Then came the descriptors. Cut the image into cells, and in each cell count the edges by their angle, each one weighted by its strength. Here are those counts for our digit: each star is a histogram of nine orientations, the long spokes running along the strokes. David Lowe's SIFT, published in full in 2004, found distinctive points at every scale and described each one with 128 such counts. Navneet Dalal and Bill Triggs's histograms of oriented gradients, in 2005, covered the whole window, normalized block by block, and found pedestrians. Counted like this, an image survives small shifts and changes of lighting.

By 2010 a good vision system was a pipeline. Pixels went in; hand-designed features like SIFT came out, at thousands of places; they were pooled into one long vector and handed to a linear classifier, usually Part 6's support vector machine. People designed the features. Coding could fit dictionaries or mixtures from data; the classifier learned how to predict labels. Systems like this won the first two ImageNet contests, in 2010 and 2011, missing the right answer, in five guesses, about a quarter of the time.

We can measure what the features buy. Train the same linear classifier twice, once on the raw pixels and once on our histograms of oriented gradients. On the digits, the pixels give percent errors; the histograms, , about times fewer. The lesson of the era: The question the rest of this part answers: what if the features were learned too?

2ConvolutionUndergraduate3 min

Suppose a network should find a short stroke in a digit. A fully connected unit weighs every pixel, so to find the stroke anywhere, the network must learn a detector for every place it might be. A convolutional unit looks at a small patch, five pixels by five, and every unit of a map uses the same twenty-five weights, slid across the image. For six maps the size of the digit, fully connected units need 3.7 million weights; local patches without sharing, 122,304; shared, just 156. Sharing is the whole idea: the same pattern can appear anywhere, so look for it the same way everywhere.

Here is the operation. Lay a small grid of weights, the kernel, over a patch of the image; multiply each weight by the pixel under it and add them up. That is one number of the output. Slide the kernel one pixel along and do it again, row by row, until it has visited every position. The output is a feature map: bright wherever the patch looks like the kernel. Strictly, this is a cross-correlation; a mathematician's convolution flips the kernel first, but a learned kernel doesn't care.

Sharing the weights buys a precise property: shift the image, and the feature map shifts with it. Write T s for the shift by s. The convolution of the shifted image at i is a sum of weights times the shifted image. The shifted image at i plus u is the original at i plus u minus s. That sum is the convolution of the original at i minus s. Which is the shifted feature map, for any kernel, learned or not. In two dimensions the argument is the same; it holds exactly when the image wraps around, and away from the border with zero padding.

Let's check it on our digit. Convolve, then shift; or shift the digit by pixels down and to the left, then convolve. With zero padding the maps agree everywhere except a thin band at the border, where the shifted image has lost pixels. A fully connected layer of the same shape has no such identity: its two routes differ by times the size of its output. Equivariance is what weight sharing buys.

3Receptive fields, stride and poolingMaster's2 min

One unit of the first layer sees three pixels by three. A unit of the second layer sees three by three units of the first, and each of those sees its own three by three, so together they cover five by five pixels. A third layer, seven by seven. This is the unit's receptive field: the part of the image that can change it at all. Stacked, the fields make a cone.

We can count the cone exactly. Name the kernel size, the stride, the spacing between neighbouring units in pixels, and the receptive field. A kernel of size k reaches k minus 1 more units of the layer below, j pixels apart: the field grows by k minus 1 times j. A stride multiplies the spacing. Unrolled: one, plus each layer's extra taps times the product of all the strides before it. Every layer after a stride counts for more.

Apply the rule to real networks, layer list by layer list. LeNet-5's last convolution sees pixels square: its whole input. AlexNet's last pooling layer sees pixels, VGG-16's , ResNet-50's : Our own CIFAR network, which we'll meet in Chapter 8, reaches pixels on 32-pixel photographs.

Two more ingredients shrink the maps as they go up. Pooling: in each 2 by 2 block keep only the largest value, and move on by 2. Nudge a feature by a pixel inside its block and the pooled output doesn't change: a little invariance, Hubel and Wiesel's complex cell again. But a stride of 2 breaks the exact equivariance of the last chapter. We shifted the digit by one to four pixels before our first layer and its pooling. In 2019 Aharon Azulay and Yair Weiss showed that a one-pixel shift can change a modern network's answer, and Richard Zhang that blurring before each stride mostly fixes it.

4LeNet and MNISTUndergraduate3 min

The first network built on Hubel and Wiesel's plan came from Japan. In 1980 Kunihiko Fukushima's Neocognitron stacked layers of S-cells and C-cells, after the simple and complex cells, and recognized digits even when they were shifted. But it learned without backpropagation, by rules of its own. In 1989, at Bell Labs, Yann LeCun and his colleagues trained a convolutional network end to end with backpropagation, through the shared weights, on digits from real zip codes: 7,291 for training, with 5 percent errors on the test digits. The same year Alex Waibel's group slid shared weights along time.

By 1998 the design had a name and a benchmark. LeNet-5, from LeCun, Leon Bottou, Yoshua Bengio and Patrick Haffner: two rounds of convolution and pooling, six maps then sixteen, then three fully connected layers down to ten digits. And MNIST, seventy thousand handwritten digits, remixed from two US government collections, one written by Census Bureau employees and one by high-school students. LeNet-5 missed 0.95 percent of the test digits, 0.8 trained on distorted copies, and a system built around it went to work in banks, reading several million checks a day. We built the same layout, with today's ReLU and max pooling.

Now let's watch ours learn. On the left, its test error; on the right, its six first-layer kernels, what they make of one digit, and its answer. At the start the kernels are random noise and the answers are guesses: percent wrong. After passes over the training digits, percent wrong. Nobody designed those kernels: they are whatever made the answers right.

Over three training runs with different random starts, our network gets percent of the test digits wrong, between and : And here are some it got wrong. Several of them would make a person hesitate too.

Is it the convolution that helps, or just the training? Compare it fairly, with a fully connected network of the same size, weights against , trained the same way, three times each. On ordinary test digits: percent wrong for the convolutional network, for the other. Neither is perfectly shift-invariant: the fully connected layers at the top of LeNet see positions. And the cleanest test of the assumption.

5ImageNet and AlexNetUndergraduate3 min

In 2009 Fei-Fei Li, then at Princeton, and her students published ImageNet. The idea was to collect pictures for every noun in WordNet, a dictionary of English organized as a tree of meanings, searched for on the web and checked one by one by people paid through Amazon's Mechanical Turk. From 2010 a yearly contest used a thousand of its classes: 1,281,167 training photographs, with five guesses allowed per test image. Count the numbers a network has to learn from, images times pixel values, and ImageNet's contest is about 4,100 times MNIST: thousands of times bigger, and messier.

The first two contests went to pipelines like the ones in Chapter 1: percent top-5 error in 2010, in 2011. In 2012 the second-best entry, from the University of Tokyo, used SIFT and other features and reached . The winner, entered as SuperVision by Alex Krizhevsky, Ilya Sutskever and Geoffrey Hinton, reached percent, and with extra training images. Almost ten points better than the next entry, in a contest where a year's progress had been a point or two. The network became known as AlexNet. Part 17 will explain how it was trained, on two gaming graphics cards; here, what was inside.

AlexNet was LeNet's design, grown. Five convolutional layers, the first with 96 kernels of eleven by eleven pixels at a stride of four, then three fully connected layers, ending in a thousand-way softmax. Count its weights from the published layer list: 60,965,224. Only 4 percent of them are in the convolutions; the first fully connected layer alone holds 38 million. Now count the arithmetic, per image: 724 million multiply-adds, and 92 percent of those are in the convolutions, because each of their few weights is used at every position. Weights live in the dense layers, work in the convolutions: that split comes back in every network after it.

AlexNet didn't come from nowhere. In 2011 Dan Ciresan and colleagues in Jurgen Schmidhuber's lab had already won contests with convolutional networks on GPUs, beating the average human tester on traffic signs. In 2012 groups at Toronto, Microsoft, Google and IBM reported together that deep networks beat the old models of speech. But ImageNet was the benchmark vision cared about, and the field turned at once: in 2013 nearly every team entered a convolutional network. Bengio, Hinton and LeCun later shared the Turing Award for 2018.

6Why AlexNet wonMaster's3 min

The first difference inside AlexNet is small: the activation. The networks of the 1990s squashed each unit with a tanh or a sigmoid. AlexNet used the rectified linear unit, zero for negative inputs and the input itself otherwise. The reason is in the slopes, which backpropagation multiplies the gradient by at every layer. The sigmoid's is at most a quarter, and both it and tanh flatten to nothing once a unit is pushed far from zero: it saturates and stops learning. The ReLU's slope is one wherever it is on. Krizhevsky measured it on CIFAR-10: a four-layer network with ReLUs reached 25 percent training error 6 times faster than the same network with tanh.

We ran the race ourselves, on the digits: the same six-layer convolutional network, three times with each activation, trained by plain gradient descent with momentum, as AlexNet was. The dashed line is percent training error.

The second ingredient: dropout, from Hinton's group the same year. At every training step, switch off each hidden unit with probability one half, so the network can't lean on a conspiracy of a few; at test time keep them all, scaled to match. It is like averaging a huge family of thinner networks that share weights. AlexNet used it in its two big fully connected layers. We gave a fully connected network just five thousand digits and let it train for sixty passes. Without dropout it learns every training digit, percent wrong on them, while the test error stalls. The gap between training and test shrinks from points to .

The third ingredient was the one ImageNet supplied: data. Train the same LeNet, for the same number of steps, on more and more digits. And there is a cheap way to get more: make it. AlexNet trained on random crops of its photographs and their mirror images, variants of each.

So which ingredient mattered? None of them was new in 2012: rectified units from 2010, dropout from that year, convolutional networks from 1989, GPUs and ImageNet from 2009. What was new was all of them together, at a scale where each one mattered: enough data that sixty million weights couldn't simply memorize it, and enough arithmetic to train them in a week.

7Deeper: VGG, Inception, ResNetMaster's3 min

After 2012 the contest became a race to go deeper. The winning error, year by year: percent for AlexNet's eight layers; in 2013; in 2014, with twenty-two layers; in 2015, with a hundred and fifty-two. In 2014 Andrej Karpathy trained himself on the task and labelled test images by hand: he missed percent. The networks passed him in 2015. By the contest's last year, 2017, the winner missed percent. When Benjamin Recht and colleagues carefully rebuilt a test set, the strongest classifier dropped from 96 to 90 percent top-five accuracy, and from 83 to 72 percent top-one accuracy. The ranking barely changed. Part 31 asks what benchmarks can tell us.

In 2014 Karen Simonyan and Andrew Zisserman at Oxford asked how far depth alone would go, and built networks of sixteen and nineteen layers out of nothing but three-by-three convolutions. Why so small? Two three-by-three layers see five by five pixels, by the rule of Chapter 3. With C channels in and out, they cost eighteen C squared weights, against twenty-five C squared for one five-by-five layer. Three of them see seven by seven, for twenty-seven against forty-nine, and add two more nonlinearities in between. VGG-16 came second in 2014. It was big: 138 million weights and 15.5 billion multiply-adds per image, by our count from its layer list.

The winner of 2014 went another way. Christian Szegedy's team at Google built GoogLeNet from Inception modules: look at the previous layer through several windows at once, and stack the results side by side. What made it affordable: a one-by-one convolution in front of each big one, to cut the number of channels before the expensive step. Twenty-two layers, the best error of the year, and, by its authors' count, a twelfth of AlexNet's weights. Deeper didn't have to mean bigger.

Then depth hit a wall. Kaiming He and his colleagues at Microsoft found a plain network of fifty-six layers doing worse than one of twenty, even on its own training data: not overfitting, just harder to train. Batch normalization, from that year, had helped, but not enough. Their fix: let each pair of layers learn only a correction F of x, added to its input. The block's derivative is the identity plus F's: an identity path that helps gradients reach early layers, as Part 9 showed. A hundred and fifty-two layers won 2015 at percent. Highway networks, months earlier, had built the same path with gates.

8What the filters learnMaster's3 min

CIFAR-10, collected by Krizhevsky in 2009: sixty thousand pictures of thirty-two by thirty-two pixels, in ten classes. Our network for it has an AlexNet-like first layer, 48 kernels of seven by seven pixels in colour, at a stride of two, then three more convolutional layers. Trained on this computer for 10 passes over the fifty thousand training photographs, it labels 82.5 percent of the ten thousand test photographs correctly.

Now replay the training and watch the first layer. At the start, 48 patches of noise, and percent of the answers right: chance. Within steps, more than half right, and the noise has begun to organize.

We can run Hubel and Wiesel's experiment on our own network. Show each filter a striped pattern, a grating, at sixteen angles, and record how strongly it answers at each one. Here are three of the filters, and their answers drawn as a shape around a circle: a long thin shape means the filter cares about one angle and ignores the one at right angles to it, like the cat's cell. Count the filters dominated by brightness whose answer at their best angle is at least three times the answer at right angles: of the , and more respond mostly to colour.

Higher layers combine the edges. To see what a deeper unit wants, the trick from Matthew Zeiler and Rob Fergus in 2013 is to find the inputs that excite it most. In our third layer, each unit sees twenty-one pixels square, and its favourite patches share a texture, a colour boundary, a curve or a corner. The fourth layer sees the whole photograph, and its favourite images begin to share a class: for these four channels, 4, 5, 4 and 4 of the top six images are of one kind. Nobody labelled the channels. The labels only ever reached the very last layer.

9Adversarial examplesResearch4 min

In December 2013 Christian Szegedy and six colleagues reported something strange. For any photograph a network classified correctly, they could find a tiny change, invisible to a person, that made it answer something else. A year later Ian Goodfellow, Jonathon Shlens and Szegedy showed a panda that GoogLeNet called a panda with 57.7 percent confidence. Add a faint pattern, a change of 0.007 in each pixel, and it called it a gibbon, with 99.3 percent. They also gave the explanation.

Their argument is about linearity. Take a linear score, w dot x, and change the input by a small eta. The score changes by w dot eta. If no pixel may change by more than epsilon, the largest change moves every pixel by epsilon in the direction of its weight's sign: epsilon times the sum of the absolute weights. With n inputs whose weights average m, that's epsilon times m times n: a change too small to see in any one pixel adds up, over thousands of pixels, to a large change in the score. Networks of ReLUs are built from linear pieces, so do the same with the network's own gradient: the fast gradient sign method, one gradient, one step.

Try it on our LeNet. This is the sign of the loss's gradient for one test digit: which way each pixel should move to make the network more wrong. Add it, scaled by epsilon. At zero, the network says , percent sure. To a person it is still plainly a seven, in a little fog.

Measure the one-step attack over all ten thousand test digits. At epsilon a quarter, the linear model is wrong on 100 percent of them; Goodfellow's shallow softmax was wrong on 99.9. For LeNet, the error is 84 percent. And one gradient step is a weak attack. Take twenty small steps instead, each projected back into the epsilon box. On the first two thousand test digits with seed zero, at epsilon 0.2 LeNet is wrong on 98 percent. We also evaluate transfer: with attacks made against the fully connected network, LeNet's error is 19 percent; with attacks made against one LeNet, another LeNet's error is 29 percent.

Now try photographs: thirty-two by thirty-two pixels, three colours each. Our CIFAR network, attacked with twenty small steps, changing no pixel by more than two grey levels out of 255: the originals, the change magnified many times, and the result, which looks identical, and which the network calls something else. At two grey levels it's wrong on 74 percent of the test photographs, against 17 percent with no attack at all.

The defence Goodfellow proposed: train on the attacks, making adversarial versions of every batch. We trained three LeNets that way, each for three epochs, with a loss averaged equally over clean and attacked versions of each batch. At epsilon , the error under one-step attacks is percent, compared with for ordinary training. The clean error is percent, against : The problem is still open, and the same search, run over words, breaks language models: Part 31.

10Cheaper convolutionsEngineering3 min

A convolution kernel looks at a small patch, but through every channel of the layer below: k by k by C weights, for each of the C prime output channels. In 2014 Laurent Sifre split it in two. First filter each channel on its own, with one small kernel per channel: depthwise. Then mix the channels at each pixel with a one-by-one convolution: pointwise. Count the multiply-adds. Standard: height times width times C times C prime times k squared. Separable: the depthwise part, H W C k squared, plus the pointwise part, H W C C prime. Their ratio is one over C prime plus one over k squared: for three-by-three kernels and 256 channels, about a ninth of the arithmetic.

Fewer operations should mean faster. We measured both versions on the computer making this video. For 128 channels: Counting operations is not the same as counting time, and efficient networks are designed for the hardware they run on.

In 2017 Andrew Howard's team at Google built a whole network of separable convolutions, for phones: MobileNet. It came within 0.9 points of VGG-16's accuracy on ImageNet with 27 times fewer multiply-adds and 33 times fewer weights, and beat GoogLeNet with fewer of both.

The other trick spreads a kernel out instead of slimming it. A dilated convolution leaves gaps between its taps: one apart in the first layer, two in the next, then four, then eight. The receptive field doubles with every layer: after ten layers of three taps, 2,047 inputs instead of 21, at no extra cost. The idea is old, the algorithme a trous of 1989; DeepMind's WaveNet used it in 2016 to generate speech.

In 2020 a transformer fed an image cut into patches matched the best convolutional networks, and vision transformers soon led the benchmarks: Part 22. In 2022 Zhuang Liu and colleagues at Meta asked how much of the lead was architecture and how much recipe. They took a ResNet-50 at 76.1 percent: the transformers' training recipe alone gave 78.8; depthwise convolutions, wider layers, seven-by-seven kernels and the transformer's layer norm took it to 82.0, above the transformer of the same size, at 81.3, with no attention at all: ConvNeXt. In 2023 DeepMind matched vision transformers with convolutional networks trained on four billion images. At scale, recipe and compute matter more than architecture: Part 12's lesson.

11Recurrence and vanishing gradientsMaster's3 min

Now the other half of this part: sequences. A convolution shares its weights across space. A recurrent network shares them across time. It keeps a hidden state h, a vector, and at each step mixes the old state with the new input through the same two weight matrices, W and U, and a squashing tanh. Unrolled in time, it's a very deep network with one layer per step, all of them sharing weights. Michael Jordan in 1986 and Jeffrey Elman in 1990 made the idea popular in cognitive science.

To train it, unroll it and backpropagate, as Paul Werbos described in 1990: backpropagation through time. For a loss on the final state, the gradient with respect to an early state h k passes through every later state. Each step back multiplies it by that step's Jacobian: the tanh's slopes times the same matrix W, again and again. The slopes are at most one, so the product is at most the largest singular value of W, raised to the number of steps. Below one, the gradient from far back shrinks exponentially; with eigenvalues above one, it can blow up. Sepp Hochreiter worked this out in his 1991 diploma thesis; Yoshua Bengio, Patrice Simard and Paolo Frasconi published it in 1994.

We measured it. Take random recurrent networks, run them on random inputs, and multiply the Jacobians back from the last step. When the largest eigenvalue of W is , the gradient that reaches fifty steps back has shrunk by a factor of ten to the : gone. Either way, a plain recurrent network has a narrow window of time over which it can learn anything, and the window is set by the size of W.

Exploding gradients have a shape. Take the smallest recurrent network, one unit with a weight w and a bias b, run it for fifty steps, and ask its last state to be 0.7. Here is the loss over every w and b, bright where it is high. Where the unit switches from settling high to settling low, the loss jumps: a cliff. Gradient descent from near the edge meets the cliff wall, where the gradient is 2,754, and is thrown off the map. The fix, from Razvan Pascanu, Tomas Mikolov and Bengio in 2013: if the gradient is longer than a threshold, shrink it to that length. Clipped, the same descent ends at a loss of 0.0158. Today's language models are trained with clipping too.

12LSTM and GRUMaster's3 min

The cure came from Hochreiter himself, with Jurgen Schmidhuber, in 1997. If every step multiplies the gradient by something less than one, build a unit where it multiplies by exactly one: a memory cell connected to itself with weight one, and no squashing. An error signal can ride it back across any number of steps without fading: the constant error carousel. Around it, learned gates decide when to write to the cell and when to read it; Gers, Schmidhuber and Fred Cummins later added a forget gate, to clear it.

Here is the cell as it is used today. Running straight through it, the cell state: a conveyor belt of memory. The forget gate, a number between zero and one for every slot, multiplies the belt: one keeps, zero erases. The input gate chooses how much of a new candidate g to add. The output gate chooses how much of the memory to show as the hidden state h. All three are computed from the previous hidden state and the input, so the network learns when to remember, forget and speak.

Why does the gradient survive? Differentiate the cell state with respect to the previous one. Along the belt, it's just the forget gate, a diagonal matrix of numbers between zero and one. Other paths run through the gates and need not be small. Along the direct cell-state path, back across many steps, that contribution is multiplied by the product of the forget gates, which the network learns. The full gradient includes the other paths too. A forget gate held at f halves this direct memory every ln 2 over minus ln f steps. At 0.99, about sixty-nine steps; at exactly one, Hochreiter's original carousel, forever.

In 2014 Kyunghyun Cho and colleagues in Montreal simplified the cell. The gated recurrent unit keeps only the hidden state and two gates: an update gate z that blends the old state with a new candidate, the same carousel wherever z is near zero, and a reset gate. Fewer parts, and about as good, in comparisons by Junyoung Chung and colleagues.

Does the carousel work? A test in the spirit of Hochreiter's: a sequence opens with one marked symbol, one of eight; then come random distractors; at the end the network must say what the first symbol was. We trained a plain recurrent network, an LSTM and a GRU, sixty-four units each, three times each, for sequences of 10, 30 and 100 steps. The gated cells start with their gates set to remember: the chrono initialization of Corentin Tallec and Yann Ollivier.

The results. Here is why. During training, measure how much gradient arrives at each step of the sequence, from the answer at the end.

13A character LSTMUndergraduate2 min

Now the LSTM plays the series' game: guess the next character. Each character becomes a learned vector; one layer of 512 LSTM cells reads them in order; a softmax guesses the next. 1,280,103 weights in all. We train it as Andrej Karpathy's char-rnn did in 2015: cut the thirty novels into 64 long stretches, one reader on each, 128 characters per step, the memory carried on from step to step while the gradient is cut at each step's edge. It read 19.7 million characters, about 83 percent of the books, once, in 144 minutes on this computer.

Here is its training, scored on the passage from The Maltese Falcon, which is not used for weight updates. It starts at bits per character, a guess among symbols, writing noise.

On the scoreboard, a new row. Our character LSTM: What has it learned to remember? Look at single cells, as Karpathy, Justin Johnson and Fei-Fei Li did in 2015. To close the quotation it must remember that one is open, maybe for lines. In 2017 Alec Radford and colleagues at OpenAI trained a bigger one on Amazon reviews and found a single cell that tracked whether a review was positive.

And where is it surprised? Colour each character of the passage's opening by the bits it cost. Over the whole passage, the first letter of a word costs 4.1 bits on average; a letter inside a word, 1.9; a capital letter, 5.3. The remaining letters cost less on average than its first letter in this run. That is Part 1's guessing game, played by a machine that remembers.

14Sequence to sequenceEngineering3 min

By 2014 machine translation was statistical. The best systems, phrase-based, from Part 7, used huge tables of phrase pairs and a dozen separately tuned parts. In September 2014 Ilya Sutskever, Oriol Vinyals and Quoc Le at Google replaced it all with two LSTMs: one reads the English sentence into its memory, the other starts from that memory and writes French. Five of them together scored 34.81 BLEU, beating the phrase-based baseline's 33.3. One trick mattered: reading the source backwards, so its first words, which the translation needs first, are the last ones read. Kyunghyun Cho's group in Montreal built the same design with the GRU.

The design has two halves. The encoder reads the input one symbol at a time, updating its state. Its last state is a single vector that has to stand for the whole sentence. The decoder starts from that vector and writes the output one symbol at a time, each step a softmax over the vocabulary, and each word it writes is fed back in as the next step's input, until it writes an end-of-sentence symbol.

How is the decoder trained? By teacher forcing, from Ronald Williams and David Zipser in 1989: at every step, feed it the true previous word, and ask for the next. At test time there is no true history, only its own: one mistake, and every later step continues from a history it never saw in training.

Writing the most probable output exactly would mean searching every possible sequence. Greedy decoding takes the single best word at each step instead. Beam search keeps a few of the best partial outputs at every step, extends each, and keeps the best of those: a cheap compromise. On our character LSTM, from the same prompt: greedy decoding writes text that costs bits under the model, a beam of eight finds text costing , and a random sample costs .

We built a small encoder-decoder, and gave it a job with no ambiguity: write a string of letters backwards. It trained on strings of to letters, three times from different starts. This model passes input information through the encoder's final state. Here its reversal accuracy falls as inputs grow.

Two years later the idea was in production. Google's neural machine translation system of 2016 stacked eight layers of LSTMs on each side, and in side-by-side ratings by people it cut translation errors by 60 percent on average against Google's own phrase-based system. In September 2016 it took over Google Translate's Chinese to English, about eighteen million translations a day. But GNMT had one more ingredient, the one that removed the bottleneck.

15The birth of attentionMaster's3 min

In September 2014 Dzmitry Bahdanau, a student visiting Bengio's lab, with Cho and Bengio, proposed to drop the single vector. Keep all of the encoder's states, one per input position, and at every step of the decoder score each one: how well does input j fit what the decoder needs next? The score is a tiny network, learned with everything else. A softmax turns the scores into weights that sum to one. And the decoder gets their weighted average, a context vector made fresh for each output. They called the weights an alignment. We call it attention.

Here is one step of our own model, reversing the word attentionworks. It has written skro, and is about to write the next letter. It scores every position of the input, and the softmax puts 76 percent of the weight on one letter, the w at position 10: exactly the one it must copy. The context is that mixture of the encoder's states, mostly that one. Nothing had to squeeze through a single vector: the decoder reached back for what it needed.

Now the fair comparison: the same encoder and decoder, the same training, with and without attention, three times each.

Watch the alignment form during training. Rows are the letters it writes, columns the letters it reads; bright is where it looks. Bahdanau's translations showed the same picture: mostly diagonal, with the word order of French and English, and jumps where the two disagree.

On real translation the gain was large. Bahdanau's encoder-decoder without attention scored 17.82 BLEU on English to French; with attention, 26.75. Trained longer, and counting only sentences without rare words, it reached 36.15, past the phrase-based Moses system's 35.63. And where the one-vector model fell apart on long sentences, the attention model held up at fifty words and more.

Attention is a soft lookup: a query, the decoder's state, compared with keys, the encoder's states, to fetch a mixture of values. The same year, neural Turing machines and memory networks used it to read memories. In 2015 Thang Luong and colleagues replaced Bahdanau's little scoring network with a dot product, and Kelvin Xu and colleagues pointed attention at the parts of a picture to write its caption. By 2016 it was inside Google Translate. And in 2017 a team at Google asked what would happen if they dropped the recurrence altogether and kept only attention. That is the Transformer, and Parts 13 and 14.

16Recurrence returnsResearch3 min

After 2017 the Transformer took over, and the reason was training speed. A recurrent network must compute step t after step t minus one: a thousand-token sequence is a thousand steps in a row, and a GPU with thousands of lanes mostly waits. Attention computes every position at once. But at generation time the bargain reverses. A recurrent network carries a fixed-size memory from token to token; a transformer keeps every past token's keys and values, a cache that grows with the text. So the question came back: can a recurrent network be trained in parallel?

It can, if the recurrence is linear. Suppose the new state is the old one, multiplied elementwise by a, plus b, where a and b depend only on the current input. Then two steps together are again one step of the same form, with a times a prime and a prime b plus b prime. That combining rule is associative: regroup the steps, preserving their time order. Any associative operation over a sequence can be computed by a parallel prefix scan, the algorithm Guy Blelloch made famous in 1990. Combine neighbours, then pairs two apart, then four apart: after log two of T rounds, every position has its state. A thousand steps become ten rounds.

We tried it on the computer making this video. The scan and the step-by-step loop give the same states, to rounding error. The scan trades extra arithmetic for fewer steps in a row, which pays off on hardware with thousands of lanes: on a GPU, Leo Feng and colleagues measured their scanned recurrent networks training times faster than a GRU at length 512, and times faster at length 4,096.

In 2024 Leo Feng, Yoshua Bengio and colleagues asked whether the LSTM and the GRU needed their nonlinear recurrence at all. Take the GRU and let its gate and its candidate see only the current input, not the previous state. What's left is exactly a linear recurrence, so it trains with a scan. They called it minGRU, and found it competitive on their tasks. We trained one, through the scan, beside the others. minGRU joined a family growing since 2016. Quasi-recurrent networks and simple recurrent units moved the matrices out of the recurrence; state-space models, from S4 in 2021 to Mamba in 2023, built linear recurrences that let the input choose what to keep; and in 2024 Hochreiter's own group returned with xLSTM, scaled in 2025 to seven billion parameters. Several of today's open models mix such layers with attention: the transformer's recall, the recurrence's fixed-size memory. That's Part 15.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. A convolution shares one small kernel across the image, so it commutes with shifts. Trained end to end, LeNet grew its own stroke detectors, and because they are close to linear. In time, a plain recurrent network's gradient fades, or explodes, as Jacobians multiply. And attention lets a decoder look back at exactly what it needs.

All of this comes back. Bahdanau's attention becomes the whole of the Transformer, in Parts 13 and 14. The linear recurrences and their scans are Part 15's memory. Clipping and the optimizers that train deep networks are Part 11. Images cut into patches, and convolutions inside the new models, are Part 22. Equivariance, for rotations, molecules and graphs, is Part 25. And adversarial attacks, on language models this time, come back in Part 31.

Here are six problems, from equivariance to the scan. Pause here and work through them; full solutions are in this part's notes.

Every network in this part was trained by some version of going downhill: plain gradient descent with momentum, or Adam. Next time, in Part 11, we take the descent itself apart: how fast it converges and why, what the noise of small batches does, momentum and Adam derived, the newer optimizers that treat weights as matrices, and the learning-rate schedules of today's models.

Goodfellow, Bengio and Courville's book covers both halves of this part, and Szeliski's the vision that came before. Thanks for watching, and see you in Part 11.

Where it goes next. Bahdanau's attention becomes the whole of the Transformer in Parts 13 and 14. The linear recurrences and their scans are Part 15's memory; clipping and the optimizers that train deep networks are Part 11; images cut into patches and convolutions inside the new models are Part 22; equivariance for rotations, molecules and graphs is Part 25; adversarial attacks return, on language models, in Part 31.

Key results

The part's results in one place, for revision.

Translation equivariance\(\displaystyle w\star(T_sx)=T_s(w\star x),\qquad\allowbreak (T_sx)[i]=x[i-s]\)
Receptive field\(\displaystyle r_\ell=r_{\ell-1}+(k_\ell-1)\,j_{\ell-1},\qquad\allowbreak j_\ell=j_{\ell-1}\,s_\ell\)
Fast gradient sign method\(\displaystyle \eta=\varepsilon\,\operatorname{sign}\bigl(\nabla_xJ(\theta,x,y)\bigr)\)
Gradients through time\(\displaystyle \Bigl\|\frac{\partial h_T}{\partial h_k}\Bigr\|\le\sigma_{\max}(W)^{T-k}\)
The LSTM cell\(\displaystyle c_t=f_t\odot c_{t-1}+i_t\odot g_t,\qquad\allowbreak h_t=o_t\odot\tanh(c_t)\)
Additive attention\(\displaystyle \alpha_{ij}=\frac{\exp e_{ij}}{\sum_k\exp e_{ik}},\qquad\allowbreak c_i=\sum_j\alpha_{ij}h_j\)

Try it

Lab 10 · Vanishing and exploding gradients through time

Run a tanh recurrent network for 60 steps, get the gradient of a final-state loss at every earlier step from the series' autodiff, and check it against the product of Jacobians and the bound sigma_max(W)^(T-k), at four spectral radii.

Figure produced by Lab 10: Vanishing and exploding gradients through time
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.ai.labs 10 needs numpy, scipy, matplotlib · download lab10.py · source on GitHub
radius 0.5: gradient at step 0 / at step 60   tanh 2.1e-21   linear 3.5e-19   bound 2.6e-05
radius 0.5: linear network's factor per step  0.501   (spectral radius 0.5)
radius 0.9: gradient at step 0 / at step 60   tanh 1.7e-07   linear 7.3e-04   bound 5.5e+10
radius 0.9: linear network's factor per step  0.901   (spectral radius 0.9)
radius 1.1: gradient at step 0 / at step 60   tanh 4.2e-04   linear 1.2e+02   bound 9.3e+15
radius 1.1: linear network's factor per step  1.101   (spectral radius 1.1)
radius 1.5: gradient at step 0 / at step 60   tanh 3.6e-01   linear 1.5e+10   bound 1.1e+24
radius 1.5: linear network's factor per step  1.502   (spectral radius 1.5)
LSTM cell path, forget gate 0.99: half-life   69.0 steps   (0.99^69 = 0.500)

Each step back multiplies the gradient by W' and by tanh' (at most 1): below radius 1 it vanishes exponentially, above 1 the linear network explodes, and the bound sigma_max^(T-k) always holds.
The code (92 lines; it asserts its own result)
"""Lab 10: backpropagate through time in a recurrent network and watch the gradient vanish or explode with the spectral radius."""

import numpy as np

from videos.coursekit import labs
from explainer.ai.autodiff import Tensor

TITLE = "Vanishing and exploding gradients through time"
GOAL = ("Run a tanh recurrent network for 60 steps, get the gradient of a final-state loss at every earlier step from the "
        "series' autodiff, and check it against the product of Jacobians and the bound sigma_max(W)^(T-k), at four spectral radii.")
TASKS = [
    "Clip the gradient at each step back to norm 1 at radius 1.5. What happens to the direction of the gradient at step 0?",
    "Make W orthogonal (the Q of a QR factorization). What do the linear and the tanh gradient norms do now?",
    "Add a forget gate: c_t = f c_(t-1) + (1 - f) tanh(...). Find the f that gives the cell path a half-life of 30 steps.",
]


def gradients(W, U, xs, v, linear=False):
    """dL/dh_k for k = 0..T, with L = v . h_T, by autodiff: a zero 'probe' is added to every state, and its gradient
    is the gradient at that state."""
    T, n = len(xs), len(v)
    probes = [Tensor(np.zeros(n), requires_grad=True) for _ in range(T + 1)]
    h, states = probes[0], []
    for t in range(T):
        a = Tensor(W) @ h + U @ xs[t]
        h = (a if linear else a.tanh()) + probes[t + 1]
        states.append(h.data.copy())
    (h * v).sum().backward()
    return np.array([p.grad for p in probes]), states


def by_hand(W, states, v):
    """The same gradients from the chapter's product: dL/dh_(k-1) = W' (tanh'(a_k) (.) dL/dh_k)."""
    g, out = v.copy(), [v.copy()]
    for h in reversed(states):
        g = W.T @ ((1 - h ** 2) * g)
        out.append(g.copy())
    return np.array(out[::-1])


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, T = 32, 60
    G = rng.standard_normal((n, n)) / np.sqrt(n)
    G /= np.abs(np.linalg.eigvals(G)).max()  # spectral radius 1
    U, xs, v = rng.standard_normal((n, 4)) / 2, 0.3 * rng.standard_normal((T, 4)), rng.standard_normal(n)
    v /= np.linalg.norm(v)
    radii, steps_back = (0.5, 0.9, 1.1, 1.5), np.arange(T + 1)[::-1]  # steps back from the loss: T at h_0, 0 at h_T
    lab, out, worst_hand, worst_bound = labs.Lab(), {}, 0.0, -np.inf
    for rho in radii:
        W = rho * G
        smax = np.sqrt(np.linalg.eigvalsh(W.T @ W)[-1])
        g_tanh, states = gradients(W, U, xs, v)
        g_lin, _ = gradients(W, U, xs, v, linear=True)
        worst_hand = max(worst_hand, np.abs(g_tanh - by_hand(W, states, v)).max() / np.abs(g_tanh).max())
        nt, nl = np.linalg.norm(g_tanh, axis=1), np.linalg.norm(g_lin, axis=1)
        worst_bound = max(worst_bound, np.max(np.log(nt) - steps_back * np.log(smax)))  # log of norm / bound, at most 0
        slope = np.polyfit(steps_back[:T // 2], np.log(nl[:T // 2]), 1)[0]  # the far half: the transient has died out
        out[rho] = dict(tanh=nt, lin=nl, smax=smax, slope=slope)
        lab.row(f"radius {rho}: gradient at step 0 / at step {T}", f"tanh {nt[0]:.1e}   linear {nl[0]:.1e}   bound {smax ** T:.1e}")
        lab.row(f"radius {rho}: linear network's factor per step", f"{np.exp(slope):.3f}   (spectral radius {rho})")
    half = np.log(2) / -np.log(0.99)
    lab.row("LSTM cell path, forget gate 0.99: half-life", f"{half:.1f} steps   (0.99^69 = {0.99 ** 69:.3f})")
    lab.note = ("Each step back multiplies the gradient by W' and by tanh' (at most 1): below radius 1 it vanishes "
                "exponentially, above 1 the linear network explodes, and the bound sigma_max^(T-k) always holds.")

    assert worst_hand < 1e-10, "autodiff agrees with the product of Jacobians"
    assert worst_bound < 1e-9, "the norm never exceeds sigma_max(W)^(T-k)"
    for rho in radii:
        assert abs(out[rho]["slope"] - np.log(rho)) < 0.12, "a linear network's gradient changes by the spectral radius per step"
        assert out[rho]["tanh"][0] <= out[rho]["smax"] ** T
    assert out[0.5]["tanh"][0] < 1e-8 and out[0.9]["tanh"][0] < 0.2, "below radius 1 the gradient vanishes"
    assert out[1.5]["lin"][0] > 1e6, "above radius 1 the linear network's gradient explodes"
    assert abs(0.99 ** half - 0.5) < 1e-12

    fig, ax = labs.figure(2, size=(11, 4.2))
    for rho, color in zip(radii, (labs.BLUE, labs.TEAL, labs.GOLD, labs.RED)):
        ax[0].semilogy(steps_back, out[rho]["tanh"], color=color, label=f"radius {rho}")
        ax[0].semilogy(steps_back, out[rho]["lin"], color=color, ls="--", lw=1.1)
    ax[0].plot([], [], color=labs.MUTED, label="solid: tanh,  dashed: linear")
    ax[0].set(title="Gradient norm against steps back in time", xlabel="steps back from the loss (T - k)", ylabel="norm of dL/dh_k",
              ylim=(1e-20, 1e12))
    ax[0].legend(loc="lower left", ncol=2)
    r = out[1.1]
    ax[1].semilogy(steps_back, r["smax"] ** steps_back, color=labs.MUTED, ls=":", label=f"the bound, sigma_max = {r['smax']:.2f}")
    ax[1].semilogy(steps_back, r["lin"], color=labs.GOLD, ls="--", label="linear network")
    ax[1].semilogy(steps_back, r["tanh"], color=labs.GOLD, label="tanh network")
    ax[1].semilogy(steps_back, 0.99 ** steps_back, color=labs.GREEN, label="LSTM cell path, forget gate 0.99")
    ax[1].set(title="Radius 1.1: the bound, and a path that does not decay", xlabel="steps back from the loss (T - k)", ylabel="norm, or factor")
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Clip the gradient at each step back to norm 1 at radius 1.5. What happens to the direction of the gradient at step 0?
  2. Make W orthogonal (the Q of a QR factorization). What do the linear and the tanh gradient norms do now?
  3. Add a forget gate: c_t = f c_(t-1) + (1 - f) tanh(...). Find the f that gives the cell path a half-life of 30 steps.

Problems, with solutions

Try each problem before opening its solution.

1. Equivariance, both ways. Show that circular cross-correlation commutes with every shift T_s. Conversely, show that a linear map on ℝⁿ (indices mod n) that commutes with all shifts is a circular cross-correlation.

Solution

With (T_s x)[i] = x[i − s] and (w ⋆ x)[i] = Σ_u w[u] x[i + u], all indices mod n: (w ⋆ T_s x)[i] = Σ_u w[u] x[i + u − s] = (w ⋆ x)[i − s] = (T_s(w ⋆ x))[i]. Conversely, let A be linear with A T_s = T_s A for every s, and let e_0 be the first basis vector. Every x is Σ_j x[j] T_j e_0, so Ax = Σ_j x[j] T_j (A e_0). Write g = A e_0; then (Ax)[i] = Σ_j x[j] g[i − j] = Σ_u x[i + u] g[−u]. That is w ⋆ x with w[u] = g[−u]. (So convolution is not one choice among many shift-equivariant linear layers: it is the only one.)

2. Receptive fields. Prove r_L = 1 + Σ_ℓ (k_ℓ − 1) Π_{i<ℓ} s_i and compute it for AlexNet: conv1 11/4, pool 3/2, conv2 5/1, pool 3/2, conv3–5 3/1, pool 3/2.

Solution

A unit of layer ℓ is a function of k_ℓ adjacent units of layer ℓ − 1, whose centres lie j_{ℓ−1} pixels apart, where j_{ℓ−1} = Π_{i<ℓ} s_i is the product of the strides below. Their fields are each r_{ℓ−1} wide and overlap except for the shifts, so r_ℓ = r_{ℓ−1} + (k_ℓ − 1) j_{ℓ−1}; summing from r_0 = 1 gives the formula. For AlexNet the jumps before each layer are 1, 4, 8, 8, 16, 16, 16, 16, so r = 1 + 10·1 + 2·4 + 4·8 + 2·8 + 2·16 + 2·16 + 2·16 + 2·16 = 1 + 10 + 8 + 32 + 16 + 32 + 32 + 32 + 32 = 195 pixels.

3. Separable convolutions. Derive the cost ratio 1/C′ + 1/k² of a depthwise separable convolution. For k = 3 and C′ = 512, how much cheaper is it? Why can the measured speed-up be smaller?

Solution

A standard layer computes, at each of H·W positions and for each of C′ outputs, a k·k·C dot product: H W C C′ k² multiply-adds. The depthwise step does a k·k product per channel per position, H W C k²; the pointwise step a C-long product per output per position, H W C C′. The ratio is (H W C k² + H W C C′)/(H W C C′ k²) = 1/C′ + 1/k². For k = 3, C′ = 512: 1/512 + 1/9 ≈ 0.113, about 8.8 times cheaper. The depthwise step uses each weight on one channel only, so it does about k² operations per number it reads (arithmetic intensity is low), and on most hardware it runs far below peak, bound by memory bandwidth (Part 17's roofline); the time saved is then less than the arithmetic saved.

4. The fast gradient sign method. For a linear score w·x, show max_{‖η‖∞≤ε} w·η = ε‖w‖₁. With a margin of 3 between two classes and ‖w_y − w{y′}‖₁ = 300, which ε flips the decision?

Solution

w·η = Σ_i w_i η_i ≤ Σ_i |w_i| |η_i| ≤ ε Σ_i |w_i|, with equality when η_i = ε sign(w_i). The decision between y and y′ depends on the difference of their scores, (w_y − w_{y′})·x = 3; the attack η = −ε sign(w_y − w_{y′}) lowers it by ε‖w_y − w_{y′}‖₁ = 300ε, so any ε > 3/300 = 0.01 flips it (ignoring the clipping of pixels to [0, 1]), a change of 1% of the pixel range in every pixel.

5. The memory's half-life. For an LSTM with i_t = 0 and f_t = f, show c_T = f^{T−k} c_k, find the half-life of the memory, and say why the forget gate's bias is often started at 1.

Solution

With no input, c_t = f c_{t−1}, so by induction c_T = f^{T−k} c_k, and the gradient ∂c_T/∂c_k = f^{T−k} I decays the same way. Half of the memory is gone when f^n = 1/2, after n = ln 2/(−ln f) ≈ 0.69/(1 − f) steps for f near 1: 69 steps for f = 0.99. A forget gate is σ(W[h, x] + b_f); with small random weights at initialization it sits near σ(b_f), which is 0.5 for b_f = 0 (a half-life of one step: the network starts out forgetting everything) and σ(1) ≈ 0.73 for b_f = 1 (about 2.2 steps, and larger biases give longer memories). Starting near remembering lets gradients reach back while the gates learn (Gers et al. 2000; Józefowicz et al. 2015).

6. The scan. Show that (a, b) ∘ (a′, b′) = (aa′, a′b + b′) is associative, and that the Hillis–Steele scan finds every h_t of h_t = a_t h_{t−1} + b_t in ⌈log₂ T⌉ rounds.

Solution

Read (a, b) as the affine map h ↦ ah + b; then (a, b) ∘ (a′, b′) is "apply (a, b), then (a′, b′)": h ↦ a′(ah + b) + b′ = (aa′)h + (a′b + b′). Composition of maps is associative, so ∘ is. In round r = 1, 2, …, every position t ≥ d (d = 2^{r−1}) combines its pair with that of t − d. By induction, after round r position t holds the composition of the steps from max(1, t − 2^r + 1) to t: true for r = 0 (each step alone), and round r joins two adjacent blocks of 2^{r−1} steps. After ⌈log₂ T⌉ rounds every block reaches back to step 1, and from h_0 = 0 the b part is h_t. Each round costs O(T), so the work is O(T log T) (Blelloch's work-efficient scan does it in O(T) work and 2 log₂ T rounds).

Notes and sources

Glossary

English 中文
computer vision 计算机视觉
visual cortex, receptive field (of a neuron) 视觉皮层,(神经元的)感受野
simple cell, complex cell 简单细胞,复杂细胞
orientation selectivity, tuning curve, grating 方向选择性,调谐曲线,光栅
colour-opponent cell 颜色拮抗细胞
edge, image gradient, Sobel operator 边缘,图像梯度,索贝尔算子
feature descriptor: SIFT, HOG (histogram of oriented gradients) 特征描述子:SIFT,HOG(方向梯度直方图)
keypoint, cell, block normalization 关键点,单元格,块归一化
hand-made (hand-designed) features, pipeline 手工设计的特征,流水线
Fisher vector, bag of visual words 费舍尔向量,视觉词袋
convolution, cross-correlation, kernel (filter) 卷积,互相关,卷积核(滤波器)
feature map, channel 特征图,通道
weight sharing, locally connected 权值共享,局部连接
translation equivariance, translation invariance 平移等变,平移不变
circular padding, zero padding 循环填充,零填充
receptive field (of a unit), effective receptive field (单元的)感受野,有效感受野
stride, jump (spacing), pooling, max pooling 步长,跳距,池化,最大池化
anti-aliasing, blur pooling 抗混叠,模糊池化
the Neocognitron, S-cells, C-cells 新认知机,S细胞,C细胞
LeNet, MNIST LeNet,MNIST
zip code, check reader 邮政编码,支票识别系统
time-delay neural network (TDNN) 时延神经网络(TDNN)
ImageNet, ILSVRC, top-5 error ImageNet,ILSVRC(ImageNet大规模视觉识别挑战赛),前五错误率
WordNet, Amazon Mechanical Turk WordNet,亚马逊土耳其机器人(众包平台)
AlexNet (SuperVision), CIFAR-10 AlexNet(SuperVision),CIFAR-10
rectified linear unit (ReLU), saturation 修正线性单元(ReLU),饱和
dropout 随机失活(dropout)
data augmentation, random crop, flip 数据增强,随机裁剪,翻转
VGG, GoogLeNet, Inception module, 1 × 1 convolution VGG,GoogLeNet,Inception模块,1 × 1卷积
degradation problem 退化问题
batch normalization 批归一化
residual network (ResNet), highway network 残差网络(ResNet),高速公路网络
activation maximization, saliency map, feature visualization 激活最大化,显著图,特征可视化
adversarial example, perturbation, transferability 对抗样本,扰动,可迁移性
fast gradient sign method (FGSM), projected gradient descent (PGD) 快速梯度符号法(FGSM),投影梯度下降(PGD)
adversarial training, robustness, certified defence 对抗训练,鲁棒性,可认证防御
depthwise convolution, pointwise convolution, depthwise separable 深度卷积,逐点卷积,深度可分离
MobileNet, ConvNeXt, vision transformer (ViT), Swin MobileNet,ConvNeXt,视觉Transformer(ViT),Swin
dilated (atrous) convolution 空洞卷积(膨胀卷积)
recurrent neural network (RNN), hidden state 循环神经网络(RNN),隐状态
backpropagation through time (BPTT), truncated BPTT 随时间反向传播(BPTT),截断的BPTT
vanishing gradient, exploding gradient 梯度消失,梯度爆炸
Jacobian, spectral radius, largest singular value 雅可比矩阵,谱半径,最大奇异值
gradient clipping, cliff 梯度裁剪,悬崖
long short-term memory (LSTM), cell state, constant error carousel 长短期记忆(LSTM),细胞状态,恒定误差传送带
input gate, forget gate, output gate 输入门,遗忘门,输出门
gated recurrent unit (GRU), update gate, reset gate 门控循环单元(GRU),更新门,重置门
half-life (of a memory) (记忆的)半衰期
chrono initialization 时序初始化
character-level language model, char-rnn 字符级语言模型,char-rnn
sequence to sequence (seq2seq), encoder, decoder 序列到序列(seq2seq),编码器,解码器
machine translation, phrase-based, BLEU 机器翻译,基于短语的,BLEU
teacher forcing, exposure bias, scheduled sampling 教师强制,暴露偏差,计划采样
greedy decoding, beam search, beam width 贪心解码,束搜索,束宽
neural text degeneration 神经文本退化
bottleneck 瓶颈
attention, alignment, context vector, additive score 注意力,对齐,上下文向量,加性打分
query, key, value 查询,键,值
neural Turing machine, memory network 神经图灵机,记忆网络
linear recurrence, parallel prefix scan, associative 线性递推,并行前缀扫描,结合律(可结合的)
minGRU, minLSTM, xLSTM, state-space model minGRU,minLSTM,xLSTM,状态空间模型

Names: David Hubel → 大卫·休伯尔; Torsten Wiesel → 托斯滕·威泽尔; Kunihiko Fukushima → 福岛邦彦; Yann LeCun → 杨立昆; Léon Bottou → 莱昂·博图; Patrick Haffner → 帕特里克·哈夫纳; Alex Waibel → 亚历克斯·魏贝尔; David Lowe → 大卫·罗; Fei-Fei Li → 李飞飞; Jia Deng → 邓嘉; Alex Krizhevsky → 亚历克斯·克里热夫斯基; Ilya Sutskever → 伊利亚·苏茨克维; Geoffrey Hinton → 杰弗里· 辛顿; Dan Cireșan → 丹·奇雷尚; Jürgen Schmidhuber → 于尔根·施密德胡伯; Karen Simonyan → 卡伦·西蒙尼扬; Andrew Zisserman → 安德鲁·齐瑟曼; Christian Szegedy → 克里斯蒂安·塞格迪; Kaiming He → 何恺明; Xiangyu Zhang → 张祥雨; Shaoqing Ren → 任少卿; Jian Sun → 孙剑; Ian Goodfellow → 伊恩·古德费洛; Aleksander Madry → 亚历山大·马德里; Andrew Howard → 安德鲁·霍华德; Zhuang Liu → 刘壮; Michael Jordan → 迈克尔·乔丹; Jeffrey Elman → 杰弗里·埃尔曼; Paul Werbos → 保罗·韦尔博斯; Sepp Hochreiter → 塞普·霍赫赖特; Yoshua Bengio → 约书亚·本吉奥; Razvan Pascanu → 拉兹万·帕斯卡努; Felix Gers → 费利克斯·格斯; Kyunghyun Cho → 赵京焕; Andrej Karpathy → 安德烈·卡帕西; Oriol Vinyals → 奥里奥尔·维尼亚尔斯; Dzmitry Bahdanau → 德米特里·巴赫达瑙; Guy Blelloch → 盖伊·布莱洛克. Kept in Latin script (no established Chinese form found): Quoc Le, Junyoung Chung, Thang Luong, Hieu Pham, Kelvin Xu, Leo Feng. Model names stay in Latin script: LeNet, AlexNet, VGG, GoogLeNet, ResNet, MobileNet, ConvNeXt, ViT, Swin, WaveNet, GNMT, QRNN, SRU, S4, LRU, RWKV, Mamba, xLSTM, minGRU, minLSTM.

About this partfrom its README

Part 10 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). The deep-learning turn of 2012 in vision and in sequences: convolution and what it buys, LeNet, ImageNet and AlexNet, the deeper networks that followed, what their filters learn and how easily they are fooled, cheaper convolutions; then recurrent networks and their vanishing gradients, the LSTM and the GRU, a character LSTM on the series' scoreboard, sequence-to-sequence translation, the birth of attention, and the recurrent networks of today. The small networks are trained by compute.py on MNIST, CIFAR-10 and Part 1's thirty novels. Verified cached outcomes can be rendered on another machine; recorded training times and timings of kernels refer to the machine that produced those outcomes. Preserve their source, input and runtime provenance. Numbers about historical systems are the published ones, cited on screen (specs.py).

Cached inputs. Rendering reads verified existing inputs and never starts scientific producers, training, corpus generation or downloads. Supply a version-1 .cache/ai10/scene-inputs.json with an inputs object keyed by logical names such as ai10/charlstm, ai7/kn, ai9/lm, ai1/scoreboard, ai1/raw and ai1/passage. Each cache entry declares kind: "canonical", a json object with repository-relative path and sha256, and an npz object when arrays are required. A text entry instead declares a text object. Canonical paths are .cache/<part>/<name>.json, .npz or .txt. Files and parent directories must be regular, without symlinks.

Alternate scientific inputs require kind: "qualified" and a nonempty qualification explaining their method and provenance. This explicitly selects an alternate input; it does not establish its scientific validity. Keep originals intact and validate each selected source/input/runtime combination separately. No corrected scientific producer, dataset, weights, input manifest or cache is distributed with these scene changes. In particular, a separately evaluated character model must be explicitly adopted rather than silently substituted for an absent canonical outcome. SHA256 checks establish byte identity, not mathematical correctness or producer-contract compatibility. A changed manifest requires a new rendering process.

Source-only tests do not establish visual, audio or synchronization acceptance of a deployed tree. Repeat those checks using the exact selected source, input and runtime combination. In cached renders, “this computer” in timing captions refers to the recorded producing host, which can differ from the rendering host.

  • The edge that lit a neuron. Hubel and Wiesel's cat (late 1950s; J. Physiol. 1959): a cell that fires for an edge at one angle; the 48 first-layer filters of our CIFAR-10 network, and how many of them pick out one orientation; our encoder–decoder's attention while it reverses a string; the path of the part; objectives.
  • 1. Vision before deep learning. Simple and complex cells (Hubel & Wiesel 1962; Nobel 1981); the image gradient and Sobel's operator (1968) computed on a digit and a photograph; SIFT (Lowe 1999, 2004) and histograms of oriented gradients (Dalal & Triggs 2005), HOG computed here; designed features, coding that can learn a dictionary or mixture, pooling, and a learned linear classifier and the first two ImageNet winners (NEC-UIUC 28.2%, XRCE 25.8% top-5; Russakovsky et al. 2015); a linear classifier on raw pixels against the same classifier on our HOG features, MNIST and CIFAR-10, three seeds.
  • 2. Convolution. Weight sharing: six 28 × 28 maps from 3.7 million weights (fully connected), 122,304 (local, unshared) or 156 (shared); the definition (deep learning's cross-correlation); a learned LeNet kernel sweeping out a feature map; translation equivariance proved step by step; checked on our digit: circular padding exact, zero padding exact away from the border, a dense layer of the same shape not at all.
  • 3. Receptive fields, stride and pooling. The cone of a deep unit; r_ℓ = r_{ℓ−1} + (k_ℓ − 1) j_{ℓ−1}, j_ℓ = j_{ℓ−1} s_ℓ derived; computed from the published layer lists for LeNet-5, AlexNet, VGG-16 and ResNet-50; max pooling, and how a stride breaks exact equivariance for odd shifts (computed); Azulay & Weiss (2019), Zhang (2019).
  • 4. LeNet and MNIST. Fukushima's Neocognitron (1980); LeCun et al. (1989): backpropagation through shared weights on 7,291 zip-code digits, 5.0% test error (figures as reproduced by Karpathy 2022); Waibel et al.'s time-delay network (1989); LeNet-5 and MNIST (LeCun, Bottou, Bengio & Haffner 1998: 0.95%, 0.8% with distortions; several million checks a day); our LeNet trained here, three seeds, the first replayed: test error, its six kernels and its feature maps of one digit at eleven checkpoints; digits it gets wrong; LeNet against an MLP of the same size (three seeds): on shifted digits, and with the pixels shuffled by one fixed permutation.
  • 5. ImageNet and AlexNet. Deng et al. (CVPR 2009), WordNet and Mechanical Turk; ILSVRC (1,000 classes, 1,281,167 training images, top-5 error); 2010–2012 results (ISI's Fisher vectors 26.2%, SuperVision 16.4% and 15.3% with extra data); AlexNet's weights and multiply-adds layer by layer, computed from the published architecture (60,965,224 weights; 4% in the convolutions, 92% of the multiply-adds there); the hardware side is Part 17's chapter 4; Cireșan et al.'s GPU networks (traffic signs, IJCNN 2011: 99.46% against 98.84% for people), Hinton et al. (2012) in speech, ILSVRC 2013, the 2018 Turing Award.
  • 6. Why AlexNet won. ReLU (Nair & Hinton 2010; Glorot, Bordes & Bengio 2011) and the slopes of the activations; AlexNet's CIFAR-10 measurement (six times faster to 25% training error); our race of ReLU, tanh and sigmoid in a CNN with five convolutional layers and a linear output (SGD with momentum, three seeds); dropout (Hinton et al. 2012; Srivastava et al. 2014) on 5,000 digits, with and without (three seeds); test error against training-set size (500 to 60,000 digits, equal steps, three seeds) and its power-law slope; shifted copies as augmentation; none of it new, all of it together.
  • 7. Deeper: VGG, Inception, ResNet. The winning top-5 error by year, 2010–2017 (Russakovsky et al. 2015; He et al. 2015; Hu et al. 2017), and Karpathy's 5.1%; VGG (Simonyan & Zisserman 2014): two 3×3 layers for one 5×5, derived, and VGG-16 counted (138 million weights, 15.5 billion multiply-adds); GoogLeNet's Inception module (Szegedy et al. 2014); the degradation problem, batch normalization (Ioffe & Szegedy 2015), residual networks (He, Zhang, Ren & Sun 2015) and highway networks (Srivastava, Greff & Schmidhuber 2015); ImageNetV2 (Recht et al. 2019).
  • 8. What the filters learn. CIFAR-10 (Krizhevsky 2009); our network (48 kernels of 7×7×3 at stride 2, three more layers) trained here, ten epochs; the replay of its first layer, noise to oriented edges and colour-opponent blobs (compare Krizhevsky et al.'s figure 3); Hubel and Wiesel's experiment run on our filters (gratings at 16 angles, orientation selectivity and a brightness-dominated criterion jointly, trained against untrained); top-activating patches and images of deeper channels (Zeiler & Fergus 2013).
  • 9. Adversarial examples. Szegedy et al. (2013); the panda and the gibbon (Goodfellow, Shlens & Szegedy 2014); the linearity argument and the fast gradient sign method derived; our LeNet fooled; error under FGSM and 20-step PGD against ε for a linear model, an MLP and LeNet: FGSM on 10,000 test digits (three MLP/LeNet seeds), PGD on the first 2,000 digits (LeNet seed 0); transfer error on all 10,000 digits. CIFAR-10 examples change each channel by at most 2/255; the noise panel shows the mean RGB change as a heatmap. Adversarial training (fast FGSM with a random start, Wong, Rice & Kolter 2020; Madry et al. 2017) uses three seeds and three epochs, against the ordinary LeNet's six epochs. Learning curves use the first 1,000 digits; final clean/FGSM use 10,000, PGD the first 2,000. The ordinary PGD row is seed 0; the adversarial row averages three seeds. These unmatched budgets do not isolate a cost of robustness. Attacks on language models return in Part 31.
  • 10. Cheaper convolutions. Depthwise separable convolutions (Sifre 2014; Chollet 2016) and their cost ratio 1/C′ + 1/k², derived; measured on this computer against the FLOP ratio; MobileNet (Howard et al. 2017, table 8); dilated convolutions (the algorithme à trous, Holschneider et al. 1989; WaveNet, van den Oord et al. 2016) and their receptive fields; the vision transformer (Dosovitskiy et al. 2020, Part 22), ConvNeXt (Liu et al. 2022: ResNet-50 modernized from 76.1% to 82.0% against Swin-T's 81.3%; 87.8% with ImageNet-22K) and convolutional networks at scale (Smith et al. 2023).
  • 11. Recurrence and vanishing gradients. Jordan (1986), Elman (1990); backpropagation through time (Werbos 1990); the product of Jacobians and its bound σ_max(W)^{T−k} derived (Hochreiter 1991; Bengio, Simard & Frasconi 1994); measured on random tanh and linear RNNs at four spectral radii (twelve networks each); a one-unit RNN's loss cliff and gradient descent across it with and without clipping (after Pascanu, Mikolov & Bengio 2013).
  • 12. LSTM and GRU. The constant error carousel (Hochreiter & Schmidhuber 1997), input and output gates, the forget gate (Gers, Schmidhuber & Cummins 2000); the cell as a conveyor belt: its direct cell-state path has derivative diag(f_t), while other gate paths also contribute to the full derivative; the memory's half-life, derived; the GRU (Cho et al. 2014; Chung et al. 2014); the memory task (remember the first of T = 10, 30, 100 symbols): RNN, LSTM and GRU, three seeds each, the gated cells from the chrono initialization (Tallec & Ollivier 2018; in an earlier run with PyTorch's default gate biases, the LSTM stayed at chance at T = 30 in all three seeds, 12–14%), accuracy during training, and the gradient reaching each time step, replayed.
  • 13. A character LSTM. 512 cells on Part 1's thirty novels, truncated backpropagation through time with 64 readers (after Karpathy 2015); its training replayed with what it writes at each checkpoint; its row on the scoreboard (bits per character on chapter 2 of The Maltese Falcon), beside Part 7's Kneser–Ney and Part 9's neural models as historical references. Their scoring target spans and training settings differ: 21,405 targets for this LSTM, 21,399 for Kneser–Ney, and 21,382 for the Part 9 models, so the rows are not a matched ranking. A cell that tracks quotation marks (Karpathy, Johnson & Fei-Fei 2015; Radford, Józefowicz & Sutskever 2017); the surprise of each character.
  • 14. Sequence to sequence. Phrase-based translation (Koehn, Och & Marcu 2003); Sutskever, Vinyals & Le (2014): 34.81 BLEU against 33.30, reversing the source (25.9 → 30.6); Cho et al. (2014); teacher forcing (Williams & Zipser 1989) and exposure bias; greedy decoding and beam search on our character LSTM, and degeneration (Holtzman et al. 2019); full 120-character scores with explicitly marked excerpts. Our encoder–decoder is evaluated on 100 test strings per length, three seeds; the beam-of-four comparison instead uses 40 strings per length from seed 0. Each additional correct reversal changes accuracy by 2.5 percentage points in that small sample; these observations do not establish a fixed capacity bound for a state vector; GNMT (Wu et al. 2016): 60% fewer errors, Chinese–English in production in September 2016.
  • 15. The birth of attention. Bahdanau, Cho & Bengio (2014): the additive score, the softmax, the context vector; one step of our model; with and without attention at equal training (three seeds), inside and beyond the training lengths; the alignment forming during training; their Table 1 (17.82 → 26.75 BLEU; 36.15 against Moses's 35.63 without unknown words); neural Turing machines and memory networks (2014), Luong et al. and Xu et al. (2015), the Transformer (2017; Parts 13 and 14).
  • 16. Recurrence returns. Attention and recurrence's different training and generation costs (Part 15); linear recurrences and the parallel prefix scan (Blelloch 1990; Martin & Cundy 2018), associativity derived; the scan against the loop, measured here, narrow and wide states; minGRU (Feng et al. 2024) on our memory task beside the others; QRNN, SRU, S4, LRU, RWKV, Mamba, xLSTM (2024; 7B in 2025) and today's hybrids.
  • Recap, where it comes back (Parts 11, 13, 14, 15, 22, 25, 31), the problem set, Part 11's preview (three optimizers in one valley, computed), references.

Source checks from the repository root do not train models or render scenes:

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Vision before deep learning: edges, SIFT and HOG features, hand-made pipelines.
  2. Convolution as weight sharing; translation equivariance proved.
  3. Receptive-field arithmetic, stride, pooling.
  4. LeNet (1989–98) and MNIST; ImageNet (2009) and AlexNet on two GPUs (2012): the moment; VGG, ResNet; ImageNet error by year (cited).
  5. What filters learn (our CNN on the glyph images).
  6. Adversarial examples: FGSM from linearity.
  7. Depthwise and dilated convs, ConvNeXt.
  8. RNNs and BPTT; vanishing gradients via products of Jacobians.
  9. LSTM (1997, the constant error carousel); GRU.
  10. Seq2seq (2014), teacher forcing, beam search; neural machine translation overtakes the statistical systems.
  11. Bahdanau attention (2014): the birth of attention.
  12. A char-LSTM on the thirty novels: scoreboard row.
  13. RNNs return: minLSTM/xLSTM and parallel scans, the bridge to Part 15.

Visuals: a kernel sweeping out a feature map; receptive-field cones in 3D; the LSTM cell as a conveyor belt; gradient norm decaying back through time.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答

1. 两个方向的等变性。 证明循环互相关与每个平移T_s可交换。反过来,证明ℝⁿ上(下标取模n)与所有平移可交换的线性映射一定是循环 互相关。

解答

记 (T_s x)[i] = x[i − s],(w ⋆ x)[i] = Σ_u w[u] x[i + u],下标都取模n: (w ⋆ T_s x)[i] = Σ_u w[u] x[i + u − s] = (w ⋆ x)[i − s] = (T_s(w ⋆ x))[i]。反过来,设A线性,且对每个s都有 A T_s = T_s A, e_0是第一个基向量。每个x都可写成 Σ_j x[j] T_j e_0,所以 Ax = Σ_j x[j] T_j (A e_0)。令 g = A e_0,则 (Ax)[i] = Σ_j x[j] g[i − j] = Σ_u x[i + u] g[−u],这正是 w[u] = g[−u] 的 w ⋆ x。(所以卷积不是众多平移等变线性层中的一种 选择,而是唯一的一种。)

2. 感受野。 证明 r_L = 1 + Σ_ℓ (k_ℓ − 1) Π_{i<ℓ} s_i,并对AlexNet计算:conv1 11/4,池化3/2,conv2 5/1,池化3/2, conv3–5 3/1,池化3/2。

解答

第ℓ层的一个单元是第ℓ − 1层k_ℓ个相邻单元的函数,这些单元的中心彼此相隔j_{ℓ−1}个像素,其中 j_{ℓ−1} = Π_{i<ℓ} s_i 是下面 各层步长的乘积。它们的感受野各宽r_{ℓ−1},除了平移之外彼此重叠,所以 r_ℓ = r_{ℓ−1} + (k_ℓ − 1) j_{ℓ−1};从 r_0 = 1 求和就得到 公式。AlexNet各层之前的跳距依次是1, 4, 8, 8, 16, 16, 16, 16,所以 r = 1 + 10·1 + 2·4 + 4·8 + 2·8 + 2·16 + 2·16 + 2·16 + 2·16 = 195个像素。

3. 可分离卷积。 推导深度可分离卷积的代价比 1/C′ + 1/k²。k = 3、C′ = 512时便宜多少?为什么实测的加速可能更小?

解答

标准卷积在H·W个位置上、对C′个输出各算一个k·k·C的点积:H W C C′ k²次乘加。深度卷积对每个通道、每个位置算一个k·k的乘积, H W C k²次;逐点卷积对每个输出、每个位置算一个长C的乘积,H W C C′次。两者之比是 (H W C k² + H W C C′)/(H W C C′ k²) = 1/C′ + 1/k²。k = 3、C′ = 512时为 1/512 + 1/9 ≈ 0.113,大约便宜8.8倍。深度卷积的每个权重只作用于一个通道,每读一个数只做大约k²次 运算(算术强度低),在多数硬件上它远低于峰值、受内存带宽限制(第17部分的屋顶线),省下的时间就少于省下的算术。

4. 快速梯度符号法。 对线性打分 w·x,证明 max_{‖η‖∞≤ε} w·η = ε‖w‖₁。若两类之间的间隔是3,且 ‖w_y − w{y′}‖₁ = 300, 多大的ε能翻转判决?

解答

w·η = Σ_i w_i η_i ≤ Σ_i |w_i| |η_i| ≤ ε Σ_i |w_i|,取 η_i = ε sign(w_i) 时取等号。y与y′之间的判决取决于两者打分之差 (w_y − w_{y′})·x = 3;攻击 η = −ε sign(w_y − w_{y′}) 把它降低 ε‖w_y − w_{y′}‖₁ = 300ε,所以任何 ε > 3/300 = 0.01 都能翻转它 (不计像素被截到[0, 1]),也就是每个像素改动像素范围的1%。

5. 记忆的半衰期。 对 i_t = 0、f_t = f 的LSTM,证明 c_T = f^{T−k} c_k,求记忆的半衰期,并说明为什么遗忘门的偏置常常从1开始。

解答

没有输入时 c_t = f c_{t−1},归纳得 c_T = f^{T−k} c_k,梯度 ∂c_T/∂c_k = f^{T−k} I 也以同样方式衰减。当 f^n = 1/2, 即 n = ln 2/(−ln f) ≈ 0.69/(1 − f) 步(f接近1时)后,记忆剩下一半:f = 0.99时是69步。遗忘门是 σ(W[h, x] + b_f);初始化时权重 小而随机,它停在σ(b_f)附近:b_f = 0时是0.5(半衰期一步:网络一开始什么都忘),b_f = 1时是σ(1) ≈ 0.73(约2.2步,偏置更大,记忆 更长)。从“记住”附近出发,梯度就能在门学会之前传回去(Gers等,2000;Józefowicz等,2015)。

6. 扫描。 证明 (a, b) ∘ (a′, b′) = (aa′, a′b + b′) 满足结合律,并证明Hillis–Steele扫描在⌈log₂ T⌉轮内求出 h_t = a_t h_{t−1} + b_t 的每一个h_t。

解答

把(a, b)看作仿射映射 h ↦ ah + b;那么 (a, b) ∘ (a′, b′) 就是“先做(a, b),再做(a′, b′)”:h ↦ a′(ah + b) + b′ = (aa′)h + (a′b + b′)。映射的复合满足结合律,所以∘也满足。在第r = 1, 2, …轮,每个位置t ≥ d(d = 2^{r−1})把自己的一对数与位置 t − d的合并。归纳可知,第r轮之后位置t保存的是从 max(1, t − 2^r + 1) 到t各步的复合:r = 0时成立(每步单独),第r轮把两个相邻的、 各含2^{r−1}步的块接起来。⌈log₂ T⌉轮之后,每个块都回溯到第1步,从 h_0 = 0 出发,b那一部分就是h_t。每轮代价O(T),总工作量 O(T log T)(布莱洛克的工作量最优扫描用O(T)工作量、2 log₂ T轮完成)。

Build the film

python -m videos.ai.ai10.compute        # the part's numbers, into .cache/ai10
python tools/build.py ai10                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai10 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/ai/ai10. Setup: see the course page. Source of these notes: the README and the scenes' narration.