Volume 1 · An interactive history
From Neuron to Transformer
Eighty years of artificial intelligence, told through the mathematics that made each step possible. Every idea here is something you can run, break, and rebuild in the page.
What it means for a machine to learn
The figure above started as a network with random numbers for weights. It knew nothing about spirals. A few thousand small corrections later it draws a boundary that winds between two interleaved arms. Nobody wrote the rule for that boundary. The network found it by repeatedly measuring how wrong it was and nudging each number in the direction that made it less wrong.
That loop is the core of nearly everything in this volume. Almost every modern AI system, from a handwriting reader to a chatbot, is a function with adjustable parameters, a way to score its mistakes, and a procedure for adjusting the parameters to reduce the score. In symbols:
Read it as: find the parameters \(\theta\) that make the model \(f_\theta\) produce outputs close to the right answers \(y_i\), averaged over \(n\) examples, where "close" is measured by a loss function \(\mathcal{L}\). The history of AI is largely the history of three questions about this equation. What shape should \(f\) take? How do we measure the loss? How do we search for good \(\theta\) when there are billions of them?
The story did not run in a straight line. Two schools competed for most of the twentieth century. The symbolic school held that intelligence is the manipulation of explicit rules and symbols, written down by people. The connectionist school held that it emerges from many simple units whose connections are learned from data. Funding and prestige swung between them, twice collapsing into periods now called AI winters. The connectionists eventually won the argument about perception and language, but only after computers became roughly a billion times faster and the internet supplied the data.
The chapters follow the chronology. Each one introduces the mathematical idea that unlocked its era, then gives you a bench to experiment on. The year in the margin marks when the idea first appeared in print.
- Parameter
- An adjustable number inside a model, also called a weight. The models in this volume range from 3 parameters to hundreds of billions.
- Loss
- A single number that measures how wrong the model is on some data. Training means making it smaller.
- Gradient
- The vector of partial derivatives of the loss with respect to each parameter. It points uphill; learning steps go the other way.
The logical neuron
In 1943 the neurophysiologist Warren McCulloch and the self-taught logician Walter Pitts published A Logical Calculus of the Ideas Immanent in Nervous Activity. Their claim was bold for its time: a brain cell could be modeled as a simple on/off switch, and networks of these switches could compute any proposition of logic.
Their model neuron receives binary inputs \(x_i \in \{0,1\}\). Each input has a weight \(w_i\), positive for excitatory connections and negative for inhibitory ones. The neuron adds up its weighted inputs and fires if the sum reaches a threshold \(\theta\):
With the right weights and threshold, a single unit behaves as an AND gate, an OR gate, or a NOT gate. Since any logical expression can be built from those, a network of these units can in principle compute anything a digital computer can. John von Neumann cited the paper in his 1945 design report for the EDVAC, one of the first stored-program computers. The model neuron and the digital computer were conceived side by side.
What the 1943 neuron could not do was learn. Every weight had to be set by hand. Six years later the psychologist Donald Hebb proposed a mechanism in The Organization of Behavior (1949): when one cell repeatedly helps fire another, the connection between them strengthens. "Cells that fire together wire together" became the slogan, and the idea that learning lives in connection strengths has organized the field ever since.
Try it below. Adjust the two weights and the threshold and watch which logical function the unit computes. A two-input unit has sixteen possible truth tables. See how many you can reach.
A threshold unit computing logic
Click an input circle to toggle it between 0 and 1. Dashed amber lines carry negative (inhibitory) weights.
| x₁ | x₂ | Σ | y |
|---|
Can machines think?
Alan Turing opened his 1950 paper Computing Machinery and Intelligence with that question, then immediately set it aside as too vague to answer. In its place he proposed a game. An interrogator converses by text with a hidden human and a hidden machine. If the interrogator cannot reliably tell which is which, Turing argued, we have no principled reason to deny the machine intelligence.
The "imitation game", now called the Turing test, is often remembered as the paper's point. The more prophetic section comes near the end, titled "Learning Machines". Turing suggested that rather than programming an adult mind directly, it might be easier to build a child mind and educate it. He predicted that by about the year 2000, machines with around 109 bits of storage would fool an average interrogator 30% of the time after five minutes. His storage figure was close to the mark. The conversational ability arrived about two decades late.
We may hope that machines will eventually compete with men in all purely intellectual fields.A. M. Turing, Mind, 1950
The naming of the field
In the summer of 1956, John McCarthy, Marvin Minsky, Nathaniel Rochester, and Claude Shannon gathered researchers at Dartmouth College for a two-month workshop. Their funding proposal, written the year before, contains the first use of the phrase artificial intelligence and an ambitious premise: "every aspect of learning or any other feature of intelligence can in principle be so precisely described that a machine can be made to simulate it."
The most impressive exhibit was the Logic Theorist, by Allen Newell, Herbert Simon, and Cliff Shaw. It proved 38 of the first 52 theorems in Whitehead and Russell's Principia Mathematica, one of them more elegantly than the original. It worked by search: represent the problem as symbols, apply rules to generate new expressions, and use heuristics to decide which branches to explore. This became the template for the symbolic school.
Search as intelligence
Symbolic AI treats a problem as a graph of states. Solving it means finding a path from the start state to a goal. The difficulty is that these graphs grow exponentially. A game with branching factor \(b\) searched to depth \(d\) has about \(b^d\) positions; chess has \(b \approx 35\), so looking ten moves ahead means roughly \(2.8 \times 10^{15}\) positions. Heuristics, rules of thumb that estimate which states are promising, were the symbolic school's answer. The A* algorithm (Hart, Nilsson, and Raphael, 1968) formalized this by expanding the state with the lowest
where \(g(n)\) is the cost so far and \(h(n)\) is an estimate of the cost remaining. If \(h\) never overestimates, A* is guaranteed to find the cheapest path. Route planners still use descendants of it today.
Meanwhile, a quieter line of work pointed elsewhere. In 1959 Arthur Samuel at IBM described a checkers program that improved by playing against itself, and he coined the term machine learning for it. Samuel's program tuned the weights of a scoring function from experience. It eventually beat respectable amateur players, and in its 1962 televised match it defeated a self-described checkers master.
- Turing proposes the imitation game and speculates about learning machines.
- Minsky and Dean Edmonds build SNARC, a 40-neuron learning machine from vacuum tubes and a surplus autopilot motor.
- Dartmouth workshop. The Logic Theorist proves theorems from Principia Mathematica.
- McCarthy invents Lisp, which becomes the language of AI research for three decades.
- Samuel's self-improving checkers program; the phrase "machine learning" enters print.
- Joseph Weizenbaum's ELIZA imitates a psychotherapist with simple pattern-matching rules. Users confide in it anyway.
The perceptron learns from its mistakes
Frank Rosenblatt, a psychologist at the Cornell Aeronautical Laboratory, took the McCulloch–Pitts neuron and added the missing piece: a rule for adjusting the weights automatically. His perceptron was first simulated on an IBM 704 in 1957 and then built in hardware as the Mark I Perceptron, whose 400 photocells formed a 20×20 pixel "retina" wired through a layer of fixed random connections to units with motor-driven potentiometers as adjustable weights.
The press was not restrained. A 1958 New York Times story reported that the Navy expected the machine to "be able to walk, talk, see, write, reproduce itself and be conscious of its existence." The actual capability was more modest and more interesting: given labeled examples, it found a linear boundary separating two classes, on its own.
The learning rule
Label the classes \(y = +1\) and \(y = -1\). The perceptron predicts with the sign of a weighted sum:
The boundary between the classes is the set of points where \(\mathbf{w}\cdot\mathbf{x} + b = 0\): a line in two dimensions, a plane in three, a hyperplane in general. The weight vector \(\mathbf{w}\) is perpendicular to it and points toward the positive side. Learning is almost embarrassingly simple. Go through the examples. When one is misclassified, move the boundary toward it:
Adding \(y_i\mathbf{x}_i\) rotates \(\mathbf{w}\) toward a misclassified positive example or away from a misclassified negative one. The learning rate \(\eta\) sets the step size. Correct examples cause no change at all.
The perceptron learning rule, one correction at a time
A guarantee, and its fine print
In 1962 Albert Novikoff proved the perceptron convergence theorem. Suppose every example lies within distance \(R\) of the origin and some boundary separates the classes with a margin of at least \(\gamma\) on each side. Then the perceptron makes at most
mistakes before it finds a separating boundary, regardless of the order of examples or the dimension of the space. The proof is short: each mistake increases \(\mathbf{w}\cdot\mathbf{w}^\star\) by at least \(\gamma\) while \(\|\mathbf{w}\|^2\) grows by at most \(R^2\), and those two rates are only compatible for a limited number of steps.
The fine print is the word separable. If no straight line divides the classes, the guarantee is void and the weights never settle. Around the same time, Bernard Widrow and Ted Hoff at Stanford built ADALINE, which minimized squared error instead of counting mistakes. Their least-mean-squares rule, \(\mathbf{w} \leftarrow \mathbf{w} + \eta (y - \mathbf{w}\cdot\mathbf{x})\mathbf{x}\), is an early form of gradient descent, and it is still used in adaptive filters that cancel echo on phone lines.
One line is not enough
In 1969 Marvin Minsky and Seymour Papert published Perceptrons, a rigorous mathematical analysis of what single-layer networks can and cannot compute. Its most famous result is also its simplest. The exclusive-or function, which outputs 1 when exactly one of its two inputs is 1, cannot be computed by any perceptron.
The proof takes four lines. Suppose weights \(w_1, w_2\) and bias \(b\) worked. The four cases of XOR require:
Adding the middle two gives \(w_1 + w_2 + 2b \ge 0\), so \(w_1 + w_2 + b \ge -b \gt 0\), which contradicts the last line. Geometrically, the two positive points sit on one diagonal of a square and the two negative points on the other. No straight line can put both diagonals on opposite sides. Try it.
XOR in input space, and after one hidden layer
Two hidden threshold units move (0,1) and (1,0) onto the same spot. Now one line, h₁ + h₂ = 1.5, separates the classes. XOR = AND(OR, NAND).
Minsky and Papert knew that multilayer networks could compute XOR, as the right panel shows. Their pessimism was about learning: nobody had a rule for training the hidden layer, and they doubted one would generalize. The book's influence was enormous. Funding for neural network research largely dried up, and Rosenblatt, its most prominent champion, died in a boating accident in 1971.
The first AI winter
The broader field soon hit trouble too. Early machine translation had promised much during the Cold War; the 1966 ALPAC report concluded it was slower, less accurate, and twice as expensive as human translation, and US funding was cut. In Britain, the 1973 Lighthill report told Parliament that AI had failed to achieve its "grandiose objectives" because of the combinatorial explosion: search methods that worked on toy problems drowned in the exponential growth of real ones. UK funding collapsed. DARPA, under new rules requiring research with direct military application, shifted away from open-ended AI work. The mid-1970s became the first AI winter.
Rules, experts, and the second winter
The symbolic school regrouped around a narrower ambition. Instead of general intelligence, capture the knowledge of a human specialist in a narrow domain as hundreds or thousands of if–then rules. These expert systems became AI's first commercial success.
MYCIN, developed at Stanford in the early 1970s, diagnosed bacterial blood infections and recommended antibiotics using about 600 rules like this one, paraphrased:
Each rule carried a certainty factor, and MYCIN combined them with an ad hoc calculus. In a blinded evaluation its recommendations were judged acceptable about as often as those of infectious-disease faculty. It was never used clinically, partly because of liability questions and partly because entering the data took too long.
XCON (originally R1), deployed at Digital Equipment Corporation from 1980, configured VAX computer orders. By the mid-1980s it had grown to around 2,500 rules and was credited with saving the company tens of millions of dollars a year. Corporations formed AI departments. Japan launched its Fifth Generation Computer Systems project in 1982 to build massively parallel logic-programming machines, and the US and UK responded with their own programs. Specialized Lisp machines from Symbolics and LMI sold as AI workstations.
Why it stalled
Expert systems were brittle. They failed abruptly at the edge of their rules, with no notion that they were out of their depth. Every new case meant interviewing experts and writing more rules, and rules interacted in ways nobody could predict as systems grew. This "knowledge acquisition bottleneck" was the real limit. The systems could not learn.
In 1987 the market for Lisp machines collapsed as cheaper general-purpose workstations from Sun and others caught up. The Fifth Generation project ended in 1992 without reaching its goals. Through the late 1980s and early 1990s, "AI" became a term companies avoided. This was the second AI winter.
Underneath the commercial story, the probabilistic view was gaining ground. Judea Pearl's Probabilistic Reasoning in Intelligent Systems (1988) introduced Bayesian networks, which replaced certainty factors with a principled way to reason under uncertainty using Bayes' rule:
And in 1986, in the middle of the expert-system boom, a short paper in Nature revived the connectionist program.
Backpropagation: credit assignment by the chain rule
The obstacle Minsky and Papert identified was the training of hidden units. If the output is wrong, which of the thousands of weights deeper in the network deserve the blame, and by how much? This is the credit assignment problem. Its solution turned out to be the chain rule from first-year calculus, applied systematically.
Two changes make it work. First, replace the hard threshold with a smooth function such as the logistic sigmoid \(\sigma(z) = 1/(1+e^{-z})\), so that small weight changes produce small output changes and derivatives exist. Second, choose a differentiable loss. Then every weight has a well-defined partial derivative \(\partial \mathcal{L}/\partial w\): how much the loss would change if that weight changed slightly.
Take a single neuron with loss \(\mathcal{L} = \tfrac12(a - y)^2\), where \(a = \sigma(z)\) and \(z = w_1x_1 + w_2x_2 + b\). The chain rule factors the derivative into local pieces:
Backpropagation computes these products efficiently. Run the network forward, storing every intermediate value. Then walk backward from the loss, multiplying each node's incoming gradient by its local derivative and passing the result to its inputs. Every gradient in the network costs about as much to compute as one forward pass, whether there are ten weights or ten billion.
Forward and backward through a computation graph
The general recursion
For a layered network with pre-activations \(\mathbf{z}^{(l)} = W^{(l)}\mathbf{a}^{(l-1)} + \mathbf{b}^{(l)}\) and activations \(\mathbf{a}^{(l)} = f(\mathbf{z}^{(l)})\), define the error signal \(\boldsymbol{\delta}^{(l)} = \partial\mathcal{L}/\partial\mathbf{z}^{(l)}\). Backpropagation is two equations:
The error flows backward through the transposed weights, gated at each layer by the slope of the activation function. That gating will matter a great deal in Chapter 10.
The idea had been found more than once. Seppo Linnainmaa described reverse-mode automatic differentiation in his 1970 master's thesis; Paul Werbos proposed applying it to neural networks in his 1974 dissertation. The 1986 paper by David Rumelhart, Geoffrey Hinton, and Ronald Williams, Learning representations by back-propagating errors, made it famous by showing that hidden units learn useful internal features on their own. In one example, a network trained on family trees discovered hidden units encoding nationality and generation without being told those concepts existed.
Gradient descent and its refinements
Knowing the gradient tells you which way is downhill. Gradient descent takes a step that way:
In practice the gradient is estimated on a small random mini-batch of examples rather than the full dataset, which is called stochastic gradient descent (SGD). The step size \(\eta\) is the most important setting in all of deep learning. Too small and training crawls; too large and it overshoots and diverges.
Plain gradient descent struggles in long, narrow valleys, which are common in real loss surfaces. The gradient points mostly across the valley rather than along it, so the optimizer zigzags. Momentum (Polyak, 1964) fixes this by accumulating a velocity that averages out the zigzag. Adam (Kingma and Ba, 2014) also rescales each coordinate by a running estimate of its gradient's magnitude, so that steep and shallow directions move at similar speeds:
Three optimizers race down the same loss surface
| Optimizer | Step | Loss |
|---|
Click anywhere on the map to start all three from that point. Darker blue is lower loss; the cross marks the global minimum.
What a network can represent
With backpropagation, multilayer networks could be trained. But how much could they express? In 1989 George Cybenko, and independently Kurt Hornik, Maxwell Stinchcombe, and Halbert White, proved a striking answer: a network with a single hidden layer can approximate any continuous function on a bounded region as closely as you like, given enough hidden units.
The intuition is constructive. Each hidden unit contributes a soft step along some direction. Two opposite steps make a bump. Enough bumps, scaled and placed, can trace any shape, the way a histogram approximates a curve.
The theorem is often misread. It says a good approximation exists; it says nothing about whether gradient descent will find it, how many units you need (it can be exponentially many), or whether the result will generalize to new data. In practice, depth turned out to matter more than width: deep networks can represent many functions with exponentially fewer units than shallow ones, because each layer builds features out of the previous layer's features.
The playground below lets you feel these trade-offs. Each small square on the right shows what one neuron in the first hidden layer responds to. Watch them specialize as training proceeds.
Network playground
Convolution: seeing with shared weights
A fully connected network treats an image as an unordered list of pixels. It has no idea that neighboring pixels are related or that a cat in the corner is still a cat. A 256×256 image fed into a layer of 1,000 neurons already needs 65 million weights, and each must learn separately what an edge looks like at its particular location.
Neuroscience suggested a better design. In the 1950s and 60s, David Hubel and Torsten Wiesel found that neurons in the cat visual cortex respond to edges at particular orientations within small patches of the visual field, and that later stages combine these into more complex patterns. Kunihiko Fukushima built that hierarchy into his Neocognitron in 1980. In 1989, Yann LeCun and colleagues at Bell Labs combined the architecture with backpropagation to read handwritten ZIP codes for the US Postal Service.
The key operation is the convolution. A small grid of weights, the kernel, slides across the image. At each position it computes a weighted sum of the pixels underneath:
(Strictly this is cross-correlation, since the kernel is not flipped, but every deep-learning library calls it convolution.) The same nine weights are used at every position. This weight sharing builds in translation equivariance: a feature detector that learns to find a vertical edge finds it anywhere. A 3×3 kernel has 9 weights no matter how large the image is.
A 3×3 kernel sliding over a 16×16 image
A convolutional network stacks these layers. Each layer applies dozens or hundreds of kernels in parallel, producing a stack of feature maps; a nonlinearity follows; and periodically a pooling step downsamples by taking the maximum or average over small windows. Early layers detect edges, middle layers detect textures and parts, and late layers respond to whole objects. Each layer's receptive field covers a larger region of the original image than the last.
LeCun's LeNet-5, described in the landmark 1998 paper Gradient-Based Learning Applied to Document Recognition, had about 60,000 parameters. Deployed by NCR in bank check readers, it processed a substantial fraction of checks written in the United States around the turn of the millennium. It was one of the first neural networks to do economically important work at scale, during a decade when most of the field had moved on to other methods.
Margins, kernels, and the statistical turn
Through the 1990s neural networks had a reputation as finicky: many local minima, many hyperparameters, little theory. A rival approach offered clean mathematics and convex optimization with a single global optimum. For roughly fifteen years it dominated machine learning.
Vladimir Vapnik and Alexey Chervonenkis had been developing statistical learning theory since the 1960s in the Soviet Union. Its central question is generalization: when does low error on training data guarantee low error on new data? Their answer bounds the gap using the capacity of the model class, measured by the VC dimension \(h\). With probability at least \(1-\delta\) over \(n\) training samples,
True risk is at most training risk plus a penalty that grows with capacity and shrinks with data. This formalizes Occam's razor and the danger of overfitting: a model flexible enough to memorize the training set may learn nothing that transfers.
The support vector machine
The perceptron stops at any separating line. Vapnik asked for the best one: the line with the largest margin to the nearest points on either side. With labels \(y_i\in\{-1,+1\}\), Corinna Cortes and Vapnik's 1995 soft-margin formulation is
The margin width is \(2/\|\mathbf{w}\|\), so minimizing \(\|\mathbf{w}\|\) maximizes it, and the slack variables \(\xi_i\) let a few points violate it at cost \(C\). The problem is convex. The solution depends only on the few training points that touch the margin, the support vectors.
The most elegant trick came in the dual form of the problem, where data appear only through dot products \(\mathbf{x}_i\cdot\mathbf{x}_j\). Replace each dot product with a kernel function \(k(\mathbf{x}_i, \mathbf{x}_j) = \phi(\mathbf{x}_i)\cdot\phi(\mathbf{x}_j)\) and the SVM finds a linear boundary in the feature space \(\phi\), which may be enormous or even infinite-dimensional, without ever computing \(\phi\). The radial basis kernel
corresponds to an infinite-dimensional \(\phi\). This is the same move as the hidden layer in Chapter 4, lifting the data into a space where a line suffices, except that the lift is fixed by the choice of kernel rather than learned. That difference proved decisive. Kernel methods are only as good as their kernel, and for images and language nobody could design kernels as good as features a deep network learns for itself.
The same era produced other durable tools: decision-tree ensembles such as AdaBoost (Freund and Schapire, 1995) and random forests (Breiman, 2001), graphical models, and the hidden Markov models that ran most speech recognizers until about 2012. For tabular data, gradient-boosted trees remain hard to beat today.
Memory, and the vanishing gradient
Language, speech, and music arrive as sequences, and their meaning depends on order and context. A recurrent neural network (RNN) handles sequences by keeping a hidden state \(\mathbf{h}_t\) that it updates at each step, so information from earlier inputs can influence later outputs:
Training unrolls the network through time, so a sequence of length 100 becomes a 100-layer network with shared weights, and backpropagation runs through all of it. Sepp Hochreiter, in his 1991 diploma thesis, and Yoshua Bengio, Patrice Simard, and Paolo Frasconi, in 1994, identified the problem this creates. The gradient reaching step \(t-k\) is a product of \(k\) Jacobians:
If the factors are typically smaller than 1, the product shrinks exponentially and the network cannot learn long-range dependencies: the gradient vanishes. If they are larger than 1 it explodes. For the sigmoid, \(\sigma'\) never exceeds 0.25, so vanishing is almost guaranteed.
Hochreiter and Jürgen Schmidhuber's 1997 Long Short-Term Memory fixed this with a separate memory cell \(\mathbf{c}_t\) updated additively, not by repeated multiplication through a squashing function. Learned gates decide what to forget, what to write, and what to output:
Along the cell path, \(\partial\mathbf{c}_t/\partial\mathbf{c}_{t-1} = \mathbf{f}_t\). When the forget gate stays near 1, gradients pass back through many steps nearly undiminished. (The forget gate itself was added by Felix Gers, Schmidhuber, and Fred Cummins in 2000.) The comparison below uses the typical size of each factor to show how quickly the signal decays.
How much gradient survives k steps back
LSTMs became the workhorse for sequences. By the mid-2010s they powered speech recognition on phones, Google Translate (from 2016), and handwriting recognition. Their weakness was structural. Each step depends on the previous one, so training cannot be parallelized across the sequence, and information from far back must survive being squeezed through the hidden state at every step in between. Chapter 13 describes the architecture that removed both limits.
Data, GPUs, and the ImageNet moment
By 2010 every ingredient of modern deep learning had existed for over a decade except two: data and compute at sufficient scale. Then both arrived at once.
The data came from Fei-Fei Li's ImageNet project, which used Amazon Mechanical Turk workers to label over 14 million images into more than 20,000 categories. From 2010, the annual ImageNet Large Scale Visual Recognition Challenge (ILSVRC) asked entrants to classify 1.2 million training images into 1,000 categories, scored by top-5 error: the fraction of test images whose true label was not among the model's five guesses.
The compute came from video games. Graphics processors (GPUs) perform thousands of simple arithmetic operations in parallel, which is exactly what multiplying matrices requires. NVIDIA's CUDA platform (2007) made them programmable for general computation.
In 2012, Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton entered a convolutional network trained on two consumer NVIDIA GTX 580 GPUs over about six days. AlexNet had eight learned layers and about 60 million parameters. It cut the top-5 error from 26% to 15.3%, while the second-best entry scored 26.2%. In a field used to gains of one or two points a year, this was a shock. Within two years nearly every competitive entry was a deep CNN.
ILSVRC winning top-5 classification error, 2010–2017
The tricks that made depth work
AlexNet and its successors relied on a handful of simple ideas that remain standard.
- ReLU activations. \(\mathrm{ReLU}(z) = \max(0, z)\) has slope exactly 1 for positive inputs, so gradients do not shrink through active units. AlexNet trained several times faster with it than with tanh.
- Dropout (Hinton et al., 2012; Srivastava et al., 2014). During training, randomly zero each unit with probability \(p\). The network cannot rely on any single unit, which acts like training a huge ensemble of thinned networks and sharply reduces overfitting.
- Data augmentation. Random crops, flips, and color shifts multiply the effective size of the training set.
- Batch normalization (Ioffe and Szegedy, 2015). Normalize each layer's inputs to zero mean and unit variance across the mini-batch, then rescale with learned parameters. Training becomes faster and far less sensitive to initialization.
- Residual connections (He et al., 2015). Instead of learning a mapping \(H(\mathbf{x})\) directly, each block learns a correction: \(\mathbf{y} = \mathbf{x} + F(\mathbf{x})\). The identity path gives gradients a direct route backward, the same insight as the LSTM's cell path. ResNet trained networks of 152 layers and beat the human benchmark.
The same year, deep networks transformed speech recognition: a 2012 paper from Hinton's group with Microsoft, Google, and IBM researchers reported large error reductions from replacing older acoustic models with deep networks. In 2016, DeepMind's AlphaGo, combining deep networks with tree search and reinforcement learning, defeated Lee Sedol four games to one at Go, a game long considered decades away from machine mastery. In 2018 Hinton, LeCun, and Bengio received the Turing Award for the conceptual and engineering breakthroughs that made deep neural networks practical.
Meaning as geometry
Images arrive as numbers. Words do not. The traditional representation was a one-hot vector: a vocabulary of 100,000 words becomes 100,000-dimensional vectors with a single 1. Every pair of words is then equally different, so "cat" is as far from "kitten" as from "carburetor".
The fix rests on an old linguistic idea, summarized by J. R. Firth in 1957: "You shall know a word by the company it keeps." Words that appear in similar contexts tend to have similar meanings. In 2013 Tomas Mikolov and colleagues at Google released word2vec, which learns a dense vector of a few hundred numbers for each word by training a shallow network to predict context. The skip-gram variant with negative sampling maximizes, for each word \(w\) and a context word \(c\) observed near it,
pushing vectors of co-occurring words together and pulling \(k\) randomly sampled "negative" words apart. Similarity between words is then measured by the cosine of the angle between their vectors:
The surprise was that the resulting space had linear structure nobody had asked for. Consistent relationships became consistent directions. The vector from man to woman roughly matched the vector from king to queen, so \(\mathbf{v}_{\text{king}} - \mathbf{v}_{\text{man}} + \mathbf{v}_{\text{woman}}\) landed nearest to \(\mathbf{v}_{\text{queen}}\).
Vector arithmetic on word meanings
Embeddings became the standard input layer for language models: a lookup table, learned along with everything else, that maps each token to a vector. The idea generalized well beyond words to products, songs, proteins, and users. Later models would make embeddings contextual, so that "bank" gets a different vector in "river bank" and "bank loan". That required a way for each word to look at the others.
Attention is all you need
In 2014 Ilya Sutskever, Oriol Vinyals, and Quoc Le showed that an LSTM could translate by reading a sentence into a single vector and then generating the translation from it. The single vector was a bottleneck: long sentences lost detail. The same year, Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio let the decoder look back at all the encoder's states, weighting each by relevance. They called the mechanism attention.
In June 2017 eight researchers at Google published Attention Is All You Need, which asked what would happen if you removed recurrence entirely and built the network from attention alone. The result, the Transformer, trained faster and translated better than anything before it. Nearly every frontier language model since is a descendant.
Scaled dot-product attention
Each token's vector is projected three ways by learned matrices: a query \(\mathbf{q}\) (what am I looking for?), a key \(\mathbf{k}\) (what do I contain?), and a value \(\mathbf{v}\) (what do I pass along if selected?). Every token compares its query against every key, turns the scores into weights with a softmax, and takes the weighted average of the values. For all tokens at once, with queries, keys, and values stacked into matrices:
Dividing by \(\sqrt{d_k}\) keeps the dot products from growing with dimension. Without it the softmax saturates, putting nearly all weight on one token, and gradients vanish. The whole operation is a few matrix multiplications, which GPUs do superbly, and every token is processed in parallel. The path between any two tokens is a single step regardless of how far apart they are.
One attention head resolving "it"
The rest of the block
A Transformer layer runs several attention heads in parallel, each with its own projections, so different heads can track different relationships: one might link pronouns to nouns, another verbs to their objects. Their outputs are concatenated and projected back:
Each layer then applies a position-wise feed-forward network, typically expanding to four times the width and back. Both sublayers are wrapped in residual connections and layer normalization, the same tools that made ResNet trainable. A large model stacks dozens of such layers.
Attention by itself has no sense of order: shuffle the tokens and each output is shuffled the same way. The original Transformer added a positional encoding to each token's embedding, built from sinusoids of geometrically increasing wavelengths:
Sinusoidal positional encoding, 64 positions × 64 dimensions
Predict the next word
Labeled data is expensive. Unlabeled text is nearly free: the web holds trillions of words. In 2018 two papers showed how to exploit it. Train a Transformer on a simple self-supervised task over a huge corpus, then fine-tune the pretrained network on whatever task you care about.
OpenAI's GPT (June 2018) used a decoder-only Transformer with a causal mask and trained it to predict each token from those before it. Google's BERT (October 2018) used an encoder that sees the whole sentence and trained it to fill in randomly masked words. BERT swept the language-understanding benchmarks; within a year it was running inside Google Search. But the next-token objective had a property that would prove more important. It turns a language model into a generator.
A language model assigns probability to a sequence by the chain rule of probability, one token at a time:
The loss is the average cross-entropy, measured in nats per token. Its exponential, the perplexity, can be read as the effective number of choices the model is torn between at each step. Getting this number down on diverse text turns out to require modeling grammar, facts, arithmetic, style, and some amount of reasoning, because all of these help predict what comes next.
Tokens
Models read tokens, not words or letters. A word-level vocabulary cannot handle new words or typos; a character-level one makes sequences very long. The usual compromise is byte-pair encoding (BPE), adapted for language by Rico Sennrich and colleagues in 2016 from a 1994 compression algorithm. Start with individual characters. Repeatedly find the most frequent adjacent pair and merge it into a new token. Common words become single tokens; rare words break into reusable pieces.
Learning a byte-pair vocabulary
From probabilities to text
To generate, the model computes a score (a logit) \(z_i\) for every token in its vocabulary, turns the scores into probabilities with a softmax, picks a token, appends it, and repeats. How it picks matters. Always taking the most probable token produces repetitive text. Sampling directly from the distribution produces occasional nonsense from the long tail. Two controls tame this. Temperature \(T\) rescales the logits before the softmax:
\(T < 1\) sharpens the distribution toward the top choice; \(T > 1\) flattens it. Nucleus or top-\(p\) sampling (Holtzman et al., 2019) keeps only the smallest set of tokens whose probabilities sum to at least \(p\), renormalizes, and samples from those.
Choosing the next token
The cat sat on the ____
GPT-2 (February 2019, 1.5 billion parameters) generated paragraphs coherent enough that OpenAI initially withheld the full model, citing misuse concerns. GPT-3 (May 2020, 175 billion parameters) showed something stranger: in-context learning. Given a few examples of a task written into the prompt, such as English–French pairs or questions with answers, it would continue the pattern for a new input with no change to its weights. The ability had not been designed. It appeared with scale.
Scaling laws
In January 2020, Jared Kaplan and colleagues at OpenAI reported that a language model's loss falls as a smooth power law in three quantities: parameters \(N\), training tokens \(D\), and compute \(C\). Across seven orders of magnitude, with other factors not limiting,
On a log-log plot, a power law is a straight line. That made AI progress unusually predictable: small, cheap experiments could forecast the performance of a model a thousand times larger before anyone built it. Architecture details such as depth versus width mattered surprisingly little compared to sheer scale.
Parameter counts of notable models, 1998–2024
Compute-optimal training
Training compute for a dense Transformer is approximately \(C \approx 6ND\) floating-point operations: about 2 per parameter per token for the forward pass and 4 for the backward pass. Given a fixed budget, should you train a bigger model on less data or a smaller one on more?
In 2022, Jordan Hoffmann and colleagues at DeepMind trained over 400 models to answer this, and fitted a parametric form:
\(E\) is the irreducible entropy of natural text; the other two terms are the penalties for finite model size and finite data. Minimizing under the constraint \(C = 6ND\) says parameters and data should grow at nearly the same rate, roughly 20 tokens per parameter. Most earlier large models had been undertrained. Their 70-billion-parameter Chinchilla, trained on 1.4 trillion tokens, outperformed their own 280-billion-parameter Gopher, which used the same compute.
IsoFLOP curves: spending a compute budget
In practice, models are now often trained far past the compute-optimal point. The Chinchilla analysis minimizes the cost of training. A model that will answer billions of queries is cheaper overall if it is smaller and trained longer, since every query pays for every parameter. Meta's Llama 3 8B model, for example, was trained on over 15 trillion tokens, nearly 2,000 tokens per parameter.
From predicting text to following instructions
A pretrained model imitates its training data, and the internet is not a helpful assistant. Ask a raw base model a question and it may answer, or it may continue with five more questions, as if completing a quiz. Turning a predictor into an assistant took a second stage of training aimed at what people actually want.
The first step is supervised fine-tuning (SFT): continue training on tens of thousands of example conversations written or curated by people, demonstrating good answers. The second step is reinforcement learning from human feedback (RLHF), developed by Paul Christiano and colleagues in 2017 for simulated robotics and Atari games and applied to language models through 2019–2022.
A reward model from comparisons
People are bad at assigning absolute scores but good at choosing the better of two answers. So labelers compare pairs of responses \(y_w\) (preferred) and \(y_l\) (rejected) to the same prompt \(x\). A reward model \(r_\phi\) is trained under the Bradley–Terry model of paired comparisons, which says the probability of preferring one answer is a logistic function of the reward difference:
Then the language model, now viewed as a policy \(\pi_\theta\), is optimized with reinforcement learning (usually PPO, Schulman et al., 2017) to produce high-reward responses, with a penalty for drifting too far from the fine-tuned reference model \(\pi_{\text{ref}}\):
The KL term matters. Without it, the policy learns to exploit flaws in the reward model, producing text that scores well but reads badly, an instance of Goodhart's law: when a measure becomes a target, it ceases to be a good measure.
OpenAI's InstructGPT paper (March 2022) reported that labelers preferred outputs from a 1.3-billion-parameter RLHF model over those of the 175-billion-parameter GPT-3. Alignment training could matter more than a hundredfold increase in size. On November 30, 2022, OpenAI released ChatGPT, a model trained with the same recipe, as a free research preview. It reached an estimated 100 million users in about two months, then the fastest adoption of any consumer application on record.
Simpler recipes
Anthropic's Constitutional AI (December 2022) replaced much of the human labeling with AI feedback guided by a written set of principles: the model critiques and revises its own outputs, and preference labels come from a model judging against the constitution. Direct Preference Optimization (DPO; Rafailov et al., 2023) showed that the RLHF objective above has a closed-form optimal policy, which allows skipping the separate reward model and the RL loop entirely:
The model itself acts as an implicit reward model: the log-ratio of its probability to the reference model's plays the role of \(r\). Training is plain supervised learning on preference pairs.
Reasoning, tools, and agents
Through 2023 progress came mainly from scaling pretraining. From 2024 a second axis opened up: spending more computation at the moment of answering, by letting the model think at length before it responds.
The seed was chain-of-thought prompting (Wei et al., 2022). Asking a model to write out intermediate steps before the final answer sharply improved accuracy on arithmetic and logic problems. Each generated token is another forward pass through the network, so a model that writes a long derivation is using far more computation on the problem than one that answers in a word.
Reasoning models, beginning publicly with OpenAI's o1 in September 2024, are trained to do this deliberately using reinforcement learning on problems with checkable answers: math with known solutions, code with unit tests. The model generates many attempts, the verifiable ones are scored, and the policy is updated toward attempts that succeeded. DeepSeek-R1 (January 2025) published such a recipe openly. Its group relative policy optimization (GRPO) scores each of \(G\) sampled answers against the others for the same prompt, avoiding a separate value network:
A notable finding of that work: behaviors such as checking an intermediate result, backtracking, and trying an alternative approach emerged from the reward signal alone, without examples of them. Accuracy on hard benchmarks rises steadily with the length of thinking allowed, giving a test-time scaling law that complements the training-time laws of Chapter 15.
Models that act
Language models can also emit structured requests to call tools: run code, search the web, query a database, operate a browser or a terminal. The results come back into the context window, and the model continues. Looped over many steps, this makes an agent that can carry out multi-step tasks such as fixing a bug across a codebase or researching a question across many sources. Context windows grew from 2,048 tokens for GPT-3 to hundreds of thousands and then millions, letting models work with whole books or repositories at once.
Other threads
- Mixture of experts. Replace each feed-forward block with many expert sub-networks and a router that sends each token to only a few (Shazeer et al., 2017). Total parameters grow while compute per token stays modest.
- Multimodality. CLIP (2021) learned a shared embedding space for images and captions. Current models take images, audio, and video as tokens alongside text.
- Diffusion models (Ho et al., 2020) generate images by learning to reverse a gradual noising process, step by step, from pure noise to a picture. They underlie most image and video generators.
- Science. AlphaFold 2 (2020) predicted protein structures at close to experimental accuracy. In 2024 the Nobel Prize in Chemistry went to Demis Hassabis and John Jumper for it, shared with David Baker for protein design, and the Nobel Prize in Physics went to John Hopfield and Geoffrey Hinton for foundational work on neural networks.
- Open weights. Model families such as Llama, Mistral, Qwen, and DeepSeek published their weights, letting researchers and companies run and adapt capable models on their own hardware.
- AlphaGo defeats Lee Sedol, 4–1.
- The Transformer. Deep RL from human preferences.
- GPT and BERT establish pretraining then fine-tuning.
- GPT-3 and in-context learning. Scaling laws. AlphaFold 2. Diffusion models.
- Chinchilla. InstructGPT. Chain-of-thought prompting. Constitutional AI. ChatGPT.
- GPT-4, Claude, LLaMA and many others; multimodal input becomes standard. DPO.
- Reasoning models trained with RL. Nobel Prizes for Hopfield, Hinton, Hassabis, Jumper, and Baker.
- DeepSeek-R1 publishes an open reasoning recipe. Coding and research agents enter everyday use.
What we still don't know
The mathematics in this volume explains how these systems are trained. It explains much less about what they learn, and many basic questions are open.
- Why does it generalize? Modern networks have far more parameters than training examples would seem to justify, and can memorize random labels, yet they generalize well on real data. Classical bounds like the VC inequality of Chapter 9 predict the opposite. Explanations involving the implicit biases of gradient descent are partial.
- What is inside? Mechanistic interpretability tries to reverse-engineer the algorithms a trained network implements, finding circuits for tasks like copying earlier text and features for concepts that span languages. Most of a large model's computation remains unexplained.
- How far does scaling go? The power laws have held for many orders of magnitude, but high-quality text is finite, and it is unclear which abilities continue to improve with scale and which plateau.
- How do we make it reliable? Models still state falsehoods fluently, can be manipulated through their inputs, and may pursue the letter of an objective rather than its intent. Making systems robustly honest and aligned with human intentions is an active research field with no settled solution.
- What is the right comparison to minds? These systems learn from vastly more text than any human reads, yet still lack much of the sample efficiency and grounding of a child. Whether that gap closes with more of the same or requires new ideas is debated.
The pattern of the past eighty years suggests caution in both directions. Predictions of imminent general intelligence in the 1950s and 1980s proved wrong. So did confident claims that neural networks had hit fundamental limits in 1969 and again in the 1990s. The ideas that eventually worked were usually old ones, waiting for enough data and computation to show what they could do.
Glossary
- Activation function
- The nonlinearity applied after a neuron's weighted sum: step, sigmoid, tanh, ReLU, or GELU. Without it, any stack of layers collapses to a single linear map.
- Attention
- A weighted average of value vectors, with weights from the softmax of query–key dot products. Lets every token read from every other token.
- Backpropagation
- Computing all gradients of a loss by applying the chain rule backward through a network. Reverse-mode automatic differentiation.
- Cross-entropy
- The loss \(-\log p\) of the correct answer. The standard loss for classification and language modeling.
- Convolution
- Sliding a small shared kernel of weights across an input. Builds in locality and translation equivariance.
- Embedding
- A learned dense vector representing a discrete item such as a token.
- Epoch
- One full pass through the training data.
- Fine-tuning
- Continuing to train a pretrained model on a smaller, task-specific dataset.
- Gradient descent
- Repeatedly stepping parameters against the gradient of the loss. "Stochastic" when the gradient is estimated on mini-batches.
- Hyperparameter
- A setting chosen by the practitioner rather than learned, such as the learning rate or number of layers.
- Linearly separable
- Two classes that a single hyperplane can divide. The condition under which a perceptron is guaranteed to converge.
- Logit
- An unnormalized score, turned into probabilities by a sigmoid or softmax.
- Overfitting
- Fitting the training data so closely that performance on new data suffers.
- Perplexity
- The exponential of average cross-entropy per token. Lower means the model is less surprised by the text.
- Pretraining
- Self-supervised training on a large unlabeled corpus, such as predicting the next token.
- Regularization
- Any technique that discourages overfitting: weight decay, dropout, data augmentation, early stopping.
- Reinforcement learning
- Learning a policy that maximizes reward through trial and feedback rather than labeled answers.
- Residual connection
- Adding a block's input to its output, \(\mathbf{y} = \mathbf{x} + F(\mathbf{x})\), so gradients have a direct path through deep networks.
- Softmax
- \(e^{z_i}/\sum_j e^{z_j}\): converts a vector of scores into a probability distribution.
- Token
- The unit a language model reads and writes: a word, part of a word, or a byte.
- Transformer
- A network built from stacked attention and feed-forward blocks with residual connections and normalization.
Primary sources
- McCulloch, W. S. & Pitts, W. (1943). A logical calculus of the ideas immanent in nervous activity. Bulletin of Mathematical Biophysics 5.
- Turing, A. M. (1950). Computing machinery and intelligence. Mind 59.
- McCarthy, J., Minsky, M., Rochester, N. & Shannon, C. (1955). A proposal for the Dartmouth summer research project on artificial intelligence.
- Rosenblatt, F. (1958). The perceptron: a probabilistic model for information storage and organization in the brain. Psychological Review 65.
- Novikoff, A. B. J. (1962). On convergence proofs for perceptrons. Symposium on the Mathematical Theory of Automata.
- Minsky, M. & Papert, S. (1969). Perceptrons. MIT Press.
- Rumelhart, D. E., Hinton, G. E. & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature 323.
- Cybenko, G. (1989). Approximation by superpositions of a sigmoidal function. Mathematics of Control, Signals and Systems 2.
- LeCun, Y. et al. (1989). Backpropagation applied to handwritten zip code recognition. Neural Computation 1.
- Cortes, C. & Vapnik, V. (1995). Support-vector networks. Machine Learning 20.
- Hochreiter, S. & Schmidhuber, J. (1997). Long short-term memory. Neural Computation 9.
- LeCun, Y., Bottou, L., Bengio, Y. & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE 86.
- Krizhevsky, A., Sutskever, I. & Hinton, G. E. (2012). ImageNet classification with deep convolutional neural networks. NeurIPS.
- Mikolov, T. et al. (2013). Distributed representations of words and phrases and their compositionality. NeurIPS.
- Kingma, D. P. & Ba, J. (2014). Adam: a method for stochastic optimization. arXiv:1412.6980.
- Bahdanau, D., Cho, K. & Bengio, Y. (2014). Neural machine translation by jointly learning to align and translate. arXiv:1409.0473.
- He, K. et al. (2015). Deep residual learning for image recognition. arXiv:1512.03385.
- Vaswani, A. et al. (2017). Attention is all you need. NeurIPS.
- Christiano, P. et al. (2017). Deep reinforcement learning from human preferences. NeurIPS.
- Devlin, J. et al. (2018). BERT: pre-training of deep bidirectional transformers for language understanding. arXiv:1810.04805.
- Brown, T. et al. (2020). Language models are few-shot learners. NeurIPS.
- Kaplan, J. et al. (2020). Scaling laws for neural language models. arXiv:2001.08361.
- Hoffmann, J. et al. (2022). Training compute-optimal large language models. arXiv:2203.15556.
- Ouyang, L. et al. (2022). Training language models to follow instructions with human feedback. NeurIPS.
- Bai, Y. et al. (2022). Constitutional AI: harmlessness from AI feedback. arXiv:2212.08073.
- Wei, J. et al. (2022). Chain-of-thought prompting elicits reasoning in large language models. NeurIPS.
- Rafailov, R. et al. (2023). Direct preference optimization: your language model is secretly a reward model. NeurIPS.
- DeepSeek-AI (2025). DeepSeek-R1: incentivizing reasoning capability in LLMs via reinforcement learning. arXiv:2501.12948.