Skip to main content

Artificial intelligence: from Turing’s question to large language models

Back to informatics

In 1950 the mathematician Alan Turing began a paper with a short question: **“Can machines think?”** Seventy-odd years later, we can type a question to a program and receive a detailed, fluent answer. What happens inside such a program? Counting which words appear together gives us a small program that guesses the next word, but it remembers little context. Representing words as **lists of numbers** lets us compare them by calculation and combine information from nearby words. This leads to **attention** (letting each word use information from the others in its sentence), an important part of the **Transformer**, a structure widely used in language models. We will also examine its development and training. Generating pictures raises another question: how can a computer turn noise into an image? A method called **diffusion** will show us that process.

You do not need to know programming. We will use addition, multiplication and a few powers, and whenever a new symbol appears we will say what it means before we use it. Every number in the interactive models is actually calculated, so you can check each step yourself.

01

Can machines think?

Turing’s paper, “Computing Machinery and Intelligence”, appeared in the journal Mind in 1950. He noticed straight away a difficulty with his own question. To answer “Can machines think?” we would first have to agree on what “machine” and “think” mean, and people have never fully agreed about that. So he replaced it with a question that could actually be tested.

He called it the imitation game. A person, the interrogator, types questions to two players hidden in another room, one a person and one a machine, and reads their typed answers. The interrogator’s task is to decide which is which. If the machine is taken for the person about as often as a real person would be, Turing argued, we have little reason left to deny that it thinks. Today this game is usually called the Turing test.

Only typed text passes throughInterrogatorA: …B: …Which one is the person?APerson ?Machine ?BPerson ?Machine ?
The imitation game. The interrogator sees only the typed answers of A and B, and does not know which of them is the machine.

Two further ideas in the paper matter for this page. First, Turing made a prediction. In about fifty years, he wrote, machines with enough memory would play the game well. An average interrogator would then have no more than a 70 per cent chance of identifying them correctly after five minutes of questions. Second, he suggested that instead of writing down every rule of an adult mind, we might build a machine that learns, like a child who is taught. Keep this second idea in mind, because it is exactly what modern AI does. Nobody writes the rules of a large language model; its numbers are learned from examples.

Does winning the game prove that a machine thinks? People still argue about it, and this page will not settle the question. What we can do is something more modest and more useful: understand, step by step, what today’s machines actually calculate when they answer us. Then each of us can judge Turing’s question with the mechanism in front of us rather than a mystery.

02

Seventy years in brief

The phrase “artificial intelligence” itself was coined a few years after Turing’s paper, for a summer workshop at Dartmouth College in 1956. Since then the field has moved between two broad ideas. The first is to write the rules ourselves: if a program should diagnose an illness, experts list the symptoms and the rules that connect them. The second is Turing’s learning machine: show the program many examples and let it adjust its own numbers until its answers agree with the examples. Choose an event on the timeline to read what happened and which of the two ideas it belongs to.

1950 · A question or a nameTuring asks “Can machines think?”

Turing proposes the imitation game and suggests building machines that learn.

A question or a nameRules written by peopleLearning from examplesAI winter

A rule-based program follows steps supplied by people; a learned model uses examples to adjust its numerical settings. Both approaches have uses, and a system may combine them. More data and faster calculation helped learning methods handle larger image and language tasks. In 2017, “Attention Is All You Need” introduced the Transformer for machine translation. The small example below opens up its attention calculation so that we can check where each number comes from. Understanding how those numbers combine information will help us examine how a text generator chooses the next token. This is one important family of AI methods, not a definition of all AI.

03

Guessing the next word

Let us begin with the simplest version of what a language model does. Read this unfinished sentence: “The cat sat on the …”. You probably thought of “mat” or “floor”, and certainly not “idea”. You were guessing the next word, and you were guessing from experience, because you have met many sentences like this before. A language model is a program for exactly this task. Given some text, it gives a probability to every possible next word.

A probability here is a number from 00 to 11 that says how often we expect something to happen out of many tries. If a word comes next 1 time in 4, its probability is 1÷4=0.251 \div 4 = 0.25. The probabilities of all the possible next words add up to 11, because exactly one of them must come next.

The most direct way to get such numbers is to count. Below is a tiny collection of sentences, which we call the corpus, the body of text we learn from. Choose a word: the corpus marks every place it occurs, and the table lists each word that follows it there, how many times, and that count divided by the total.

Previous word: the
Next wordCountProbability
cat339≈0.33\tfrac{3}{9}\approx 0.33
dog339≈0.33\tfrac{3}{9}\approx 0.33
fish119≈0.11\tfrac{1}{9}\approx 0.11
mat119≈0.11\tfrac{1}{9}\approx 0.11
rug119≈0.11\tfrac{1}{9}\approx 0.11
Total999=1\tfrac{9}{9}=1

For example, “the” is followed by 9 words in the corpus: “cat” 3 times, “dog” 3 times, and “fish”, “mat” and “rug” once each. So the probability of “cat” after “the” is 3÷9≈0.333 \div 9 \approx 0.33, and the five probabilities add up to 9÷9=19 \div 9 = 1.

Now press “Write a sentence”. The program starts from your word and draws the next word at random, with each word’s chance equal to its probability in the table. Then it treats the new word as the previous word and repeats, until it reaches a full stop. This prediction, choice and append loop is an autoregressive generation method: the next choice uses the text already written. We use this method in the lesson. Other language-model tasks, such as filling a hidden word from both sides, need not generate text this way.

Counting has two serious problems. First, it knows nothing about combinations it has never seen. Our corpus never has “bone” right after “the”, so a counting model says “the cat ate the bone” is impossible, though it is a perfectly good sentence. Second, it looks only one word back. In “She lived in Paris for ten years, so she speaks fluent …”, the best next word, “French”, depends on “Paris”, eight words earlier. One word back we see only “fluent”, which says nothing about which language. We could count longer runs of words, but then almost every run is new, and nearly all the counts are zero.

We need two things. First, a way to say that words are similar, so that “bone” can borrow what we know about “fish”, since both can be eaten. Second, a way to let each word use information from anywhere earlier in the text. The next chapters build both: vectors for similarity, and attention for looking back.

In the corpus, “the” is followed by 9 words, 3 of which are “dog”. What probability does the counting model give “dog” after “the”?

04

Cutting text into small pieces

Before a model can calculate anything, text has to become numbers. The first step cuts the text into pieces called tokens and gives each piece its number in a fixed list, the vocabulary. Why not simply use whole words? Because the list of words never ends: names, typing mistakes, new words, numbers, other languages. Why not single letters? Because then a sentence becomes a very long sequence, and a single letter carries little meaning. Real tokenizers take a middle path: frequent words are one token each, and rarer words are built from a few frequent pieces.

The256un274believ275able276cat257was262play270ing271.294

9 tokens · Grey chips are single bytes (IDs 0–255).

Type into the box and watch the pieces. In “unbelievable”, our small vocabulary has no whole word, so the tokenizer takes the longest piece it knows at each point: “un”, then “believ”, then “able”. Each chip shows the piece and its ID, the token’s number in the vocabulary.

Notice what happens to a character the vocabulary does not contain at all, such as 咪 in 猫咪. It is broken into the bytes a computer uses to store it. A byte is a group of 8 binary digits, so it can take 28=2562^8 = 256 different values. Most Chinese characters are stored as three bytes. Here they are written E5, 92 and AA in base 16. Base 16 uses the digits 0 to 9 and then A to F, so every byte fits into two symbols. IDs 0 to 255 are kept for these 256 bytes, so any text at all can be turned into tokens and nothing is ever “unknown”.

Where does the vocabulary come from? It is learned from text as well. A common method, byte-pair encoding, starts from single characters and repeatedly joins the pair of neighbouring pieces that occurs most often. Step through it below on a tiny corpus of four words, each used a different number of times.

WordTimes usedCurrent pieces
low5low
lower2lower
newest6newest
widest3widest
Merges so far:—
Merge step: 0 / 12

At the first step, the pair e followed by s occurs 6 times in “newest” and 3 times in “widest”, 9 times in all. The pair s followed by t also occurs 9 times, and no pair occurs more often. When two pairs tie, the tokenizer takes the one it met first in the corpus, so “es” becomes a new piece. Then “es” followed by “t” also occurs 9 times, giving “est”. After a few merges, a common ending such as “est” and a common word such as “low” have each become single pieces, while rarer letter groups stay split. Real tokenizers keep merging until the vocabulary holds tens of thousands to a few hundred thousand pieces. As a rough guide, one English token is about three quarters of a word.

05

Turning a piece into numbers

Now each token has an ID. But an ID is only a name. Token 257 (“cat”) is not “close to” token 258 (“dog”) in any useful sense, and token 300 is not more of anything than token 200. We want numbers that carry meaning, so that similar words get similar numbers. The answer is to give each token not one number but a list of numbers.

A list of numbers in a fixed order is called a vector. With two numbers, say (3,2)(3, 2), we can draw it as an arrow from the origin of a grid to the point 3 across and 2 up. With three numbers we can draw an arrow in space. A model keeps one vector for every token in a large table, the embedding table: row 257 holds the vector for “cat”. To obtain a token’s vector, the model looks up that token’s row.

Below are 19 words, each with 8 numbers. So that you can read the numbers, I designed them by hand and gave each position a meaning. Position 1 says how much the word is an animal. Position 2 says how much it is a vehicle, and so on. Choose a word to see its 8 numbers. We can only draw three directions at a time, so the picture shows three of the eight positions. Choose which three, and drag the picture to turn it.

animalvehiclefoodkingboywomanqueenmanbicyclebuscarkittendogcathorsecakebreadapple
Drag to turn ·
Axes shown
The 8 numbers of cat
animal1.01
vehicle0.04
food−0.04
person−0.05
young0.01
female0.05
royal0.00
large0.14

With the axes animal, vehicle and food, the words gather in three groups, one near each axis. Now look at the people: man, woman, king, queen, boy and girl all sit near the middle, piled on top of each other. They are not alike in every way; this particular view simply does not show the directions in which they differ. Change one axis to “person” and another to “female”, and they spread out.

This is the most important habit for thinking about vectors. A picture shows three directions at a time, but the vector has all of them. Two words can look close in one view and be far apart in the full list of numbers.

Real models work in the same way with far more numbers. The original Transformer used 512 numbers per token, and large models today use several thousand; GPT-3 used 12,288. There is one honest difference from my table: in a real model nobody chooses what each position means. The numbers start random and training (chapter 10) adjusts them. Words used in similar ways end up with similar vectors, but a single position rarely means anything as tidy as “animal”. Our labelled positions are a teaching aid that keeps the numbers readable.

06

How alike are two vectors?

We said that similar words should get similar vectors. How do we turn “similar” into a calculation? Start in two dimensions, where we can see everything. Take two vectors a=(a1,a2)\mathbf a = (a_1, a_2) and b=(b1,b2)\mathbf b = (b_1, b_2); the small numbers 1 and 2 only label the first and the second entry. Their dot product multiplies the matching entries and adds the results:

a⋅b=a1b1+a2b2\mathbf a\cdot\mathbf b=a_1b_1+a_2b_2

With more entries we do the same thing: multiply entry by entry and add everything. For example, (3,1)⋅(2,2)=3×2+1×2=8(3, 1)\cdot(2, 2) = 3\times2 + 1\times2 = 8, while (3,1)⋅(−1,3)=3×(−1)+1×3=0(3, 1)\cdot(-1, 3) = 3\times(-1) + 1\times3 = 0, and (3,1)⋅(−2,−1)=(−6)+(−1)=−7(3, 1)\cdot(-2, -1) = (-6) + (-1) = -7.

Why does this measure similarity? Drag the two arrow tips below and watch the readout. When the arrows point roughly the same way, matching entries tend to have the same signs, the products are positive and the sum is large. When they are at right angles, the positive and negative products cancel and the dot product is 00. When one arrow is a negative multiple of the other, each nonzero matching product is negative, so their sum is negative. There is one catch: making an arrow twice as long doubles each of its entries and so doubles the dot product, although its direction has not changed.

ab
Drag the tips of a\mathbf a and b\mathbf b
a\mathbf a
(3.0, 1.0)(3.0,\ 1.0)
b\mathbf b
(2.0, 2.0)(2.0,\ 2.0)
Dot product
3.0×2.0+1.0×2.0=8.003.0\times2.0 + 1.0\times2.0 = 8.00
Lengths
∣a∣=3.16, ∣b∣=2.83|\mathbf a| = 3.16,\ |\mathbf b| = 2.83
Cosine similarity
8.00÷(3.16×2.83)=0.8948.00 \div (3.16\times2.83) = 0.894
Angle between them
θ=26.6∘, cos⁡θ=0.894\theta = 26.6^\circ,\ \cos\theta = 0.894

To compare directions without including the effect of length, we need each arrow’s length. The arrow (a1,a2)(a_1, a_2) is the long side of a right triangle whose other two side lengths are ∣a1∣|a_1| and ∣a2∣|a_2|. By Pythagoras, its length is ∣a∣=a12+a22|\mathbf a| = \sqrt{a_1^2 + a_2^2}. This also equals a⋅a\sqrt{\mathbf a\cdot\mathbf a}, because a⋅a=a1a1+a2a2\mathbf a\cdot\mathbf a = a_1a_1 + a_2a_2. With more entries, we add their squares under the root in the same way. For nonzero vectors, dividing the dot product by both lengths gives the cosine similarity. A zero vector has no direction, so we cannot divide by its zero length. The length rule and the direction comparison are explained below:

Where does the length formula come from?

An arrow travels a units right and b units up. We need its direct start-to-end length c to distinguish direction from overall size. The horizontal and vertical sides are perpendicular, so they form a right triangle with the arrow. Start with positive a and b, and place four copies of that triangle inside the large square below.

Green shows the four triangles; gold shows the middle square. Each outer side joins lengths a and b. Every middle side is a triangle’s hypotenuse, c. Its corners are right angles because the two adjacent acute triangle angles sum to ninety degrees. One triangle has area ab/2ab/2: join it to a flipped copy to make a rectangle with sides a and b.

Now find the gold area by subtracting the four triangles from the outer square. The same area is c squared, so the two ways of counting it must agree.

c2=(a+b)2−4⋅ab2=a2+2ab+b2−2ab=a2+b2\begin{aligned}c^2&=(a+b)^2-4\cdot\frac{ab}{2}\\ &=a^2+2ab+b^2-2ab\\ &=a^2+b^2\end{aligned}
c=32+42=25≈5.000c=\sqrt{3^2+4^2}=\sqrt{25}\approx5.000

A length is nonnegative, so take the nonnegative square root. For negative coordinates, use absolute coordinate values as side lengths; squaring gives the same formula. If one side is zero, the arrow is just the other side. If both are zero, its length is zero. That zero vector has no direction, and its length cannot be used as a divisor in the next comparison.

cosine similarity=a⋅b∣a∣ ∣b∣\text{cosine similarity}=\frac{\mathbf a\cdot\mathbf b}{|\mathbf a|\,|\mathbf b|}

Dividing a vector by its length shrinks or stretches it to length 11 without turning it, so this number depends only on directions. It is 11 when the arrows point the same way, 00 at right angles and −1-1 when they point in opposite directions, whatever their lengths. The readout also shows that it equals the cosine of the angle between the arrows; the derivation below explains why, with nonzero vectors throughout.

Derivation: why the cosine similarity equals the cosine of the angle

First a fact about angles. Put two points on a circle of radius 11 around the origin, at angles α\alpha and β\beta measured from the horizontal axis. Their coordinates are (cos⁡α,sin⁡α)(\cos\alpha, \sin\alpha) and (cos⁡β,sin⁡β)(\cos\beta, \sin\beta); this is what cosine and sine mean for a point on that circle. The squared distance between them, by Pythagoras, is (cos⁡α−cos⁡β)2+(sin⁡α−sin⁡β)2(\cos\alpha - \cos\beta)^2 + (\sin\alpha - \sin\beta)^2. Expanding and using cos⁡2+sin⁡2=1\cos^2 + \sin^2 = 1 for each point, this is 2−2(cos⁡αcos⁡β+sin⁡αsin⁡β)2 - 2(\cos\alpha\cos\beta + \sin\alpha\sin\beta).

Now turn the whole circle backwards by α\alpha. The distance between the two points does not change, but now one is at angle 00, the point (1,0)(1, 0), and the other at angle β−α\beta - \alpha. The same calculation gives a squared distance of 2−2cos⁡(β−α)2 - 2\cos(\beta - \alpha). The two results describe the same distance, so cos⁡(β−α)=cos⁡αcos⁡β+sin⁡αsin⁡β\cos(\beta - \alpha) = \cos\alpha\cos\beta + \sin\alpha\sin\beta.

Finally, write a=∣a∣(cos⁡α,sin⁡α)\mathbf a = |\mathbf a|(\cos\alpha, \sin\alpha) and b=∣b∣(cos⁡β,sin⁡β)\mathbf b = |\mathbf b|(\cos\beta, \sin\beta). Then a⋅b=∣a∣∣b∣(cos⁡αcos⁡β+sin⁡αsin⁡β)=∣a∣∣b∣cos⁡(β−α)\mathbf a\cdot\mathbf b = |\mathbf a||\mathbf b|(\cos\alpha\cos\beta + \sin\alpha\sin\beta) = |\mathbf a||\mathbf b|\cos(\beta - \alpha), and β−α\beta - \alpha is the angle between the arrows. Dividing by ∣a∣∣b∣|\mathbf a||\mathbf b| gives the cosine of that angle. In three dimensions the two arrows lie in one flat plane through the origin and the same argument works in that plane. Beyond three dimensions we cannot draw the angle at all, so it is defined by this formula, which agrees with the drawn angle whenever we can draw it.

Now apply this to our 8-number word vectors. Choose a word in the model below: the list ranks every other word by cosine similarity calculated with all eight numbers, not only the three in the picture. “cat” and “dog” point almost the same way; “cat” and “truck” do not.

animalvehiclefoodkingboywomanqueenmanbicyclebuscarliondogcathorsecakebreadapple
Drag to turn ·
Axes shown
The 8 numbers of cat
animal1.01
vehicle0.04
food−0.04
person−0.05
young0.01
female0.05
royal0.00
large0.14
Most similar to cat
  1. dog0.963
  2. lion0.810
  3. horse0.792
  4. puppy0.742
  5. kitten0.711

Vectors also allow arithmetic. Take king, subtract man and add woman: king−man+woman\text{king} - \text{man} + \text{woman}. Subtracting man removes what king shares with man, being a person and being of a certain size, and leaves mainly “royal”; adding woman then puts back “person” and the size, together with “female”. The result lies closest to queen. Learned word vectors show the same effect, but only approximately, which is why we look for the nearest word rather than an exact match.

Which pair of vectors has dot product 0?

07

Attention: pieces that look at each other

We now have a vector for every token. But the vector from the table is always the same, wherever the token appears. Look at the sentence “The cat sat because it was tired.” The table gives “it” the same vector in every sentence, yet here “it” means the cat. To understand the sentence, the vector for “it” must take in information from “cat”. In “The road was closed because it was flooded”, the same “it” would need information from “road” instead. So each token needs a way to look at the other tokens and decide which of them matter to it. This is what attention does.

Attention works like a search. Each token makes three new vectors from its own numbers:

  • a **query**, which describes what this token is looking for;
  • a **key**, which describes what this token offers to others who are looking;
  • a **value**, the information this token passes on to whoever attends to it.

For “it”, the query says roughly “I am looking for a thing I could refer to”, and the key of “cat” says “I am a thing”. A query that matches a key well gives a large dot product, the measure of similarity from the previous chapter. So the plan is: compare the query of “it” with the key of every token it can see, and let the best matches pass on the most information.

How does a token make these vectors? In our example each token has 4 numbers, in the order [thing, pointing word, action, description]. A query and a key each have 2 numbers, so that we can draw them as arrows. To turn 4 numbers into 2, the model keeps a table of numbers called a matrix, WQW_Q for queries. It has one row for each of the 4 features, and each row holds 2 numbers: what that feature adds to the query. To make the query of a token, multiply each row by the token’s number for that feature, then add the four results. The numbers of “it” are (0.2,1,0,0)(0.2, 1, 0, 0), so its four rows are multiplied by 0.20.2, 11, 00 and 00:

q=0.2(0,0.8)+1(2.2,0)+0(1.2,0)+0(1.2,0.4)=(0,0.16)+(2.2,0)=(2.2,0.16)\begin{aligned}\mathbf q&=0.2(0,0.8)+1(2.2,0)\\ &\quad+0(1.2,0)+0(1.2,0.4)\\ &=(0,0.16)+(2.2,0)\\ &=(2.2,0.16)\end{aligned}

In the same way a second matrix, WKW_K, makes the keys, and a third, WVW_V, makes the values. The key of “cat”, whose numbers are (1,0,0,0.1)(1, 0, 0, 0.1), is 1×(2,0)+0.1×(0,0.4)=(2,0.04)1\times(2, 0) + 0.1\times(0, 0.4) = (2, 0.04): mostly “I am a thing”. Each output number is the dot product of the token’s 4 numbers with one column of the matrix, which is why this operation is called multiplying a vector by a matrix.

The score between “it” and “cat” is the dot product of the query of “it” with the key of “cat”, divided by d\sqrt d, where d=2d = 2 is the number of entries in each query and key. We will explain the division in a moment.

score(it,cat)=qit⋅kcatd=2.2×2+0.16×0.042≈4.40641.4142≈3.12\begin{aligned}\text{score}(\text{it},\text{cat})&=\frac{\mathbf q_{\text{it}}\cdot\mathbf k_{\text{cat}}}{\sqrt d}\\ &=\frac{2.2\times2+0.16\times0.04}{\sqrt2}\\ &\approx\frac{4.4064}{1.4142}\approx3.12\end{aligned}

Scores can be any numbers, positive or negative. We want weights instead: numbers that are positive and add up to 11, so that each one says what share of the attention a token receives. The softmax function turns scores into weights in two steps. Step 1: raise ee to the power of each score. Here e≈2.718e \approx 2.718 is a fixed number. A power with a whole number is repeated multiplication, for example e3=e×e×ee^3 = e\times e\times e. For scores that are not whole numbers, the powers are filled in smoothly between these. A calculator gives, for example, e0.32≈1.38e^{0.32} \approx 1.38. Two facts matter: ese^s is positive for every score ss, and a larger score gives a larger ese^s, so the order of the scores is kept.

Step 2: divide each result by the total of all of them. Dividing every share by the same total makes the shares add up to 11, just as dividing counts by their total did in chapter 3. Written with the scores s1,…,sns_1, \ldots, s_n of the nn tokens that can be seen, the weight of token jj is

wj=esjes1+es2+⋯+esnw_j=\frac{e^{s_j}}{e^{s_1}+e^{s_2}+\cdots+e^{s_n}}

For “it”, the tokens it may see are The, cat, sat, because and it itself, with scores 0.320.32, 3.123.12, 0.230.23, 0.450.45 and 1.561.56. Step 1 gives about 1.381.38, 22.5522.55, 1.251.25, 1.581.58 and 4.744.74, whose total is about 31.5031.50. Step 2: “cat” receives 22.55÷31.50≈0.7222.55 \div 31.50 \approx 0.72 of the attention of “it”, and “it” itself about 4.74÷31.50≈0.154.74 \div 31.50 \approx 0.15.

One useful property: adding the same number cc to every score changes no weight. Each ee-power becomes es+c=ec⋅ese^{s+c} = e^c\cdot e^s, so the same factor ece^c appears in every term and in the total, and it cancels in the division.

Finally, each token’s output is the weighted average of the value vectors: multiply each visible token’s value by its weight and add them up. For “it”, 0.720.72 of the result comes from the value of “cat”, so the new vector of “it” carries mostly the information of “cat”. In the model, the value arrows are laid tip to tail, each shrunk by its weight, and the last tip is the output.

outputit=0.04 vThe+0.72 vcat+0.04 vsat+0.05 vbecause+0.15 vit\begin{aligned}\text{output}_{\text{it}}&=0.04\,\mathbf v_{\text{The}}+0.72\,\mathbf v_{\text{cat}}\\ &\quad+0.04\,\mathbf v_{\text{sat}}+0.05\,\mathbf v_{\text{because}}\\ &\quad+0.15\,\mathbf v_{\text{it}}\end{aligned}

One more rule. When a model writes text, a token may look only at itself and the tokens before it, because the later ones have not been written yet. Their scores are left out; we can think of them as a score of −∞-\infty, whose ee-power is 00. This is called a causal mask. Switch it off in the model to see what an encoder, which reads a whole finished text at once, would do.

Choose the token that looks. The left picture shows its query (gold) and the keys of the tokens it can see (grey). The bars show the scores and the softmax weights. The right picture lays the weighted values tip to tail to make the output (gold). The grid below holds every token’s weights at once: row = the token looking, column = the token looked at.

Token that looks
query · keys
The0.320.04
cat3.120.72
sat0.230.04
because0.450.05
it1.560.15
washidden by the mask
tiredhidden by the mask
ScoreWeight

Score(it,cat)=2.20×2.00+0.16×0.041.41=3.12\text{Score}(\text{it},\text{cat}) = \dfrac{2.20\times2.00 + 0.16\times0.04}{1.41} = 3.12

values × weights → output (0.80, 0.21)
All weights (row looks at column)
Thecatsatbecauseitwastired
1.00
0.470.53
0.160.710.13
0.140.520.180.16
0.040.720.040.050.15
0.100.440.090.100.190.09
0.070.430.100.080.150.090.07

Why divide by d\sqrt d? A dot product adds up dd products. In a real model each query and key has 64 or 128 numbers, and adding many products tends to give large scores. Large differences between scores make softmax put nearly all the weight on one token. Then learning stalls. A token with weight close to 00 hardly affects the result, so it hardly receives any correction (chapter 10). Suppose the entries behave like random numbers of typical size 11. Then the dot product of dd of them has a typical size of about d\sqrt d. Dividing by d\sqrt d brings the scores back to a typical size of about 11. Switch the division off in the model: the weight of “cat” for “it” rises from 0.720.72 to 0.860.86, and the other weights shrink.

Derivation: why the typical size of a dot product is d\sqrt d

Let the dot product be S=x1y1+x2y2+⋯+xdydS = x_1y_1 + x_2y_2 + \cdots + x_dy_d, where every entry is an independent random number with average 00 and average square 11. To measure the typical size of SS we look at the average of S2S^2, then take its square root.

Expanding S2S^2 gives dd squared terms (xiyi)2(x_iy_i)^2 and many cross terms 2xiyixjyj2x_iy_ix_jy_j with i≠ji \ne j. Each squared term averages to 1×1=11\times1 = 1, because xix_i and yiy_i are independent. Each cross term contains, for example, xix_i, which is independent of everything else in that term and averages to 00, so the whole cross term averages to 00.

So the average of S2S^2 is d×1=dd\times1 = d, and the typical size of SS is d\sqrt d. Dividing by d\sqrt d makes the average square of the score 11, whatever dd is. Learned queries and keys are not exactly such random numbers, so this is a guide for choosing the scale, not an exact law.

One head forms one weighted combination of values at each position. Its role need not be one fixed, human-readable relationship. A Transformer runs several heads side by side, each with its own three matrices, and joins their outputs. Switch to Head B: with different matrices, the same tokens now look for the most recent action rather than the thing being referred to. The original Transformer used 8 heads in each layer, and large models use dozens. Nobody tells a head what to look for; like the word vectors, its matrices are learned, and only some heads turn out to have a tidy meaning.

If every attention score in a row is increased by 55, what happens to the softmax weights?

08

Building a Transformer

Attention lets tokens exchange information. A Transformer layer surrounds it with a few simpler steps, and the whole model is a stack of identical layers, each with its own learned numbers. Choose each part of the diagram to see what it does and why it is there.

Multi-head attention

Several heads (chapter 7) let each token gather information from the tokens it can see.

Follow one normalisation, entry by entry

After addition, entries may share a large offset or be widely spread. Removing their common offset centres them around zero. Adjusting their spread changes how far apart they are. We use just two entries below, and each step keeps earlier results so we can trace every new value. For now, the final learned scale is 1 and the offset is 0.

0 / 3
x=(−1, 3)x=(-1,\,3)

A real layer may then multiply entries by learned scales and add learned offsets. After that, the mean and variance need not be zero and one. We have unpacked this operation’s arithmetic, not claimed that normalisation guarantees successful learning.

Why are positions needed? Attention combines tokens through dot products and weighted averages, and neither of these cares where a token stands. If we shuffle the sentence, the outputs are just shuffled in the same way. In the demonstration below both sentences contain the words dog, bites and man, and we run Head A from chapter 7 over all three tokens, with no mask. Compare the output for “dog” in the two sentences.

dog bites man
dogbitesman
Output for “dog” = (0.477, 0.577)
man bites dog
manbitesdog
Output for “dog” = (0.477, 0.577)
Output for “dog”: identical

Without positions the two outputs are exactly equal, so the model could not tell who bit whom. With a position vector added to each token, one fixed pattern for each place in the sentence, the outputs differ, and later layers can use the difference.

The original paper built its position vectors from sine and cosine waves of different lengths. Many models today instead turn each query and key by an angle that depends on the token’s position (rotary position embedding), so that a dot product depends on how far apart two tokens are.

In the 2017 paper the Transformer was built for translation, for example from English into German. It had two halves. The encoder read the whole English sentence at once, with no mask. The decoder wrote the German sentence one token at a time, with a causal mask. In each layer it also attended to the encoder’s output, in order to see the English sentence. This is called cross-attention. The base model had 6 layers in each half, 512 numbers per token, 8 heads and about 65 million learned numbers, and it trained in about 12 hours on 8 GPUs. Its larger version set new records for English–German and English–French translation. The GPT family of language models keeps only the decoder half, without cross-attention: it reads the text so far and writes the next token.

Optional: the one-line formula in the paper

The paper writes chapter 7 in a single line, Attention⁡(Q,K,V)=softmax⁡ ⁣(QKT/d)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(QK^{\mathsf T}/\sqrt d\right)V. Here QQ is a table whose rows are the queries of all the tokens, and KK and VV are the tables of keys and values. KTK^{\mathsf T}, read “KK transposed”, is KK with its rows turned into columns.

Multiplying the table QQ by the table KTK^{\mathsf T} produces, in row ii and column jj, the dot product of query ii with key jj: all the scores at once. Softmax is applied to each row, giving the grid of weights in our model. Multiplying that grid by VV forms, for each row, the weighted sum of the values: all the outputs at once. Nothing new happens in this line; it is our calculation for every token together, which is exactly what a GPU does fastest.

09

Choosing the next piece

Let us return to “The cat sat on the …”. After the last layer the model holds one vector h\mathbf h for the last token. To score each candidate next token it takes the dot product of h\mathbf h with that token’s vector: a large score means h\mathbf h points the way the candidate does. These raw scores are called logits. In our toy, vectors have 4 numbers for [something to sit on, indoors, soft, food], h=(2.2,1,0.8,−1)\mathbf h = (2.2, 1, 0.8, -1), and “mat” has the vector (1.1,0.8,0.9,0)(1.1, 0.8, 0.9, 0). So the logit of “mat” is 2.2×1.1+1×0.8+0.8×0.9+(−1)×0=2.42+0.8+0.72+0=3.942.2\times1.1 + 1\times0.8 + 0.8\times0.9 + (-1)\times0 = 2.42 + 0.8 + 0.72 + 0 = 3.94.

Softmax, the same function attention used, turns the logits into probabilities. Then the model must choose. Always taking the most likely token sounds sensible, but it makes text repetitive and dull, and every answer to the same question identical. So models usually sample: they draw a token at random, each token’s chance being its probability. Press “Draw one” a few times, then “Draw 100”, and compare how often each word was drawn with its probability.

The cat sat on the ____

Next wordLogitProbabilityTimes drawn
mat3.9434.0%0
sofa3.5823.7%0
chair3.2216.6%0
floor3.0413.8%0
roof1.763.8%0
table2.266.3%0
car0.621.2%0
moon−1.440.2%0
banana−1.580.1%0
idea−1.780.1%0

p(mat)=e3.94/1.0∑jezj/1.0=51.4151.1=0.340p(\text{mat}) = \dfrac{e^{3.94/1.0}}{\sum_j e^{z_j/1.0}} = \dfrac{51.4}{151.1} = 0.340

Top-kk
Top-pp

0 draws. Green bars: probability. Thin gold bars: share actually drawn.

The temperature TT divides every logit before softmax. With T=1T = 1 nothing changes. To see what TT does, compare two candidates with logits z1z_1 and z2z_2. The ratio of their probabilities is ez1/T÷ez2/Te^{z_1/T} \div e^{z_2/T}, because the total in softmax is the same for both and cancels, and this equals e(z1−z2)/Te^{(z_1 - z_2)/T}. For “mat” and “sofa”, with logits 3.943.94 and 3.583.58, the ratio is e0.36≈1.43e^{0.36} \approx 1.43 at T=1T = 1 and e0.72≈2.05e^{0.72} \approx 2.05 at T=0.5T = 0.5. So a temperature below 11 stretches the differences and favours the likely tokens even more; as TT approaches 00 the model almost always takes the top token. A temperature above 11 shrinks the differences, and unusual words appear more often.

pj=ezj/Tez1/T+⋯+ezn/Tp1p2=ez1/Tez2/T=e(z1−z2)/T\begin{gathered}p_j=\frac{e^{z_j/T}}{e^{z_1/T}+\cdots+e^{z_n/T}}\\ \frac{p_1}{p_2}=\frac{e^{z_1/T}}{e^{z_2/T}}=e^{(z_1-z_2)/T}\end{gathered}

Two more controls cut off the long tail of unlikely tokens before drawing. Top-kk keeps only the kk most likely tokens. Top-pp keeps the most likely tokens until their probabilities add up to at least pp, so it keeps few tokens when the model is confident and more when it is unsure. In both cases the kept probabilities are divided by their new total, so that they add up to 11 again.

Having drawn a token, the model appends it to the text and runs again to choose the next one: exactly the loop of the counting model in chapter 3, only with much better probabilities. A long answer is thousands of these steps, and each step is a full pass through every layer.

With a temperature very close to 00, what does sampling do?

10

Where do the numbers come from?

All the numbers we have met, the embedding table, the matrices of every head and the feed-forward matrices, are called parameters. GPT-3 has 175 billion of them. Where do their values come from? They start as small random numbers, and training adjusts them with a very simple task. Take real text, hide the next token, and let the model predict it. Then nudge every parameter so that the correct token would have been a little more likely.

To nudge in the right direction we need one number that says how wrong the prediction was. If the model gave the correct token probability pp, we use the loss −ln⁡p-\ln p. Here ln⁡\ln is the natural logarithm, which undoes raising ee to a power: ln⁡p\ln p is the power to which ee must be raised to give pp. When p=1p = 1 the loss is −ln⁡1=0-\ln 1 = 0; when p=0.5p = 0.5 it is about 0.690.69; when p=0.01p = 0.01 it is about 4.64.6. The loss is small when the model was confidently right and grows without limit as the correct token’s probability approaches 00.

Why a logarithm? The probability the model gives a whole text is the product of the probabilities of its tokens, one after another. The logarithm of a product is the sum of the logarithms. Write a=exa = e^x and b=eyb = e^y. Then ab=ex⋅ey=ex+yab = e^x\cdot e^y = e^{x+y}, so ln⁡(ab)=x+y=ln⁡a+ln⁡b\ln(ab) = x + y = \ln a + \ln b. Therefore the loss of a whole text is simply the sum of the losses of its tokens, and each token can be treated as its own small example.

Now the nudge. For each parameter, calculus gives its slope: how fast the loss changes when that parameter increases by a tiny amount, which is its derivative. For a differentiable loss with a nonzero gradient, a sufficiently small step against that gradient lowers the loss locally; an arbitrarily large step has no such guarantee. This is called gradient descent, and the size of the step is set by the learning rate η\eta (eta). To see the arithmetic, our small experiment adjusts the three output logits themselves, not every internal parameter. For these logits the slope has a remarkably simple form: for the correct token it is p−1p - 1, and for every other token it is that token’s probability pp. Writing y=1y = 1 for the correct token and y=0y = 0 for the others, one step is

zj  ←  zj−η (pj−yj)z_j\;\leftarrow\;z_j-\eta\,(p_j-y_j)

So a step raises the correct token’s logit by η(1−p)\eta(1 - p) and lowers each wrong token’s logit by ηp\eta p. Step the training below; the correct answer is “mat”. At the start the logits are 0.50.5, 0.80.8 and 0.20.2, so p(mat)≈0.32p(\text{mat}) \approx 0.32 and the loss is about 1.131.13. After one step with η=1\eta = 1, the logit of mat rises by 1×(1−0.32)=0.681\times(1 - 0.32) = 0.68 to 1.181.18, while sofa and moon fall by their probabilities, 0.440.44 and 0.240.24. Each step makes the correct answer more likely, by less and less as pp approaches 11. A larger learning rate moves faster, but in a real model with billions of parameters too large a step overshoots and the loss jumps about, so the rate is chosen with care.

Next wordLogit zzppp−yp-ychange −eta(p−y)-\\eta(p-y)
mat · correct answer0.500.32−0.68+0.68
sofa0.800.440.44−0.44
moon0.200.240.24−0.24
Learning rate η\eta
Step
0 / 12
Loss −ln⁡p(mat)-\ln p(\text{mat})
−ln⁡0.324=1.128-\ln 0.324 = 1.128

Derivation: where the slope p−yp - y comes from

Write the logits as z1,…,znz_1, \ldots, z_n and the total of their ee-powers as S=ez1+⋯+eznS = e^{z_1} + \cdots + e^{z_n}. If token cc is correct, pc=ezc/Sp_c = e^{z_c}/S, so the loss is −ln⁡pc=−(ln⁡ezc−ln⁡S)=−zc+ln⁡S-\ln p_c = -\left(\ln e^{z_c} - \ln S\right) = -z_c + \ln S. We used ln⁡(a/b)=ln⁡a−ln⁡b\ln(a/b) = \ln a - \ln b and ln⁡ez=z\ln e^z = z.

Now change one logit zjz_j. The term −zc-z_c changes at rate −1-1 if j=cj = c and at rate 00 otherwise, which is −yj-y_j. For ln⁡S\ln S we use the chain rule: the derivative of ln⁡u\ln u is 1/u1/u, and SS changes at rate ezje^{z_j} when zjz_j changes, because the derivative of eze^z is eze^z. So ln⁡S\ln S changes at rate ezj/S=pje^{z_j}/S = p_j. Adding the two parts, the slope of the loss with respect to zjz_j is pj−yjp_j - y_j.

Earlier parameters affect the final loss through intermediate calculations. Backpropagation reuses the chain rule to combine these local rates efficiently; it is not a separate source of correct answers. The small example below multiplies two local rates so we can see why an earlier parameter receives its change. Next-token prediction is one training objective. Instruction examples, preference feedback and other objectives can be added later, so we should not infer that everything an assistant does came only from this one objective.

How does an earlier parameter receive a change?

Use a chain we can calculate completely: the input is 2, the parameter is w and the prediction is 2w2w. We want 3. Call the error a=2w−3a=2w-3, and square it to obtain the loss L(w)=(2w−3)2L(w)=(2w-3)^2, so positive and negative errors cannot cancel. Change only w and follow its effect through to the loss.

If w increases by h, the error increases by 2h. Substitute that into the square, subtract using ordinary algebra, then divide by h. Only then let h approach zero. This gives the slope we need here.

L(w+h)−L(w)=(a+2h)2−a2=4ah+4h2L(w+h)−L(w)h=4a+4h(h≠0)L′(w)=4a=4(2w−3)\begin{gathered}L(w+h)-L(w)\\ =(a+2h)^2-a^2\\ =4ah+4h^2\\ \frac{L(w+h)-L(w)}h=4a+4h\\ (h\ne0)\\ L^{\prime}(w)=4a=4(2w-3)\end{gathered}

We can also split the chain: the error changes twice as fast as w. The square’s local rate with respect to the error is 2a, because ((a+t)2−a2)/t=2a+t((a+t)^2-a^2)/t=2a+t. Multiplying the two rates gives 2×2a=4a2\times2a=4a. Backpropagation combines such local relationships in order; this short chain makes the multiplication visible.

η is the step size you choose. Try 0.1, then reset the weight and try 0.3. Both move against the slope, but the larger step overshoots and increases the loss. A sufficiently small step depends on the function; an arbitrary step is not guaranteed to work. The minimum is at w=1.5w=1.5, where the error is exactly zero. The readout rounds to three decimal places, so it uses ≈ for approximate equality. Each update still uses unrounded values; treating the displayed approximations as exact inputs can give a different final digit.

w≈0.000L≈9.000L′≈−12.000\begin{aligned}w&\approx0.000\\ L&\approx9.000\\ L^{\prime}&\approx-12.000\end{aligned}
wnext=w−ηL′(w)≈0.000−0.1×(−12.000)≈1.200Lnext≈0.360\begin{aligned}w_{\rm next}&=w-\eta L^{\prime}(w)\\ &\approx0.000-0.1\times(-12.000)\\ &\approx1.200\\ L_{\rm next}&\approx0.360\end{aligned}
11

Where the Transformer came from

Before 2017 the standard tool for language was the recurrent neural network, or RNN. It reads a sentence one token at a time, like a person reading with a finger under the line, and carries a single memory vector forward. At each step it combines the memory with the new token’s vector to make the next memory. After the last token, the memory is supposed to hold the whole sentence.

This design has two weaknesses. Information from an early token must survive every later step before it can be used at the end, and it fades along the way, much like a message passed along a line of people. The LSTM (1997) added gates, learned switches that decide what to keep, what to forget and what to add, which helped the memory last longer but did not remove the problem. The second weakness is speed. Step 50 needs the memory from step 49, so the steps cannot be calculated at the same time, while GPUs are fastest when they do thousands of calculations at once.

In 2014, translation systems called sequence-to-sequence models used one RNN to read the English sentence into a memory vector and a second RNN to write the French sentence from it. Squeezing a whole sentence into one vector was a bottleneck, and long sentences came out badly. The same year Bahdanau, Cho and Bengio let the writing RNN look back, at every step, at all of the reading RNN’s memories, with weights calculated from how well each memory matched what it needed. That was attention, added as a helper to an RNN.

The Transformer’s authors asked what would happen if attention did all the work and the step-by-step memory were removed altogether. That is the meaning of the title “Attention Is All You Need”. Every token can reach every earlier token in a single step, and, when the entire training sequence is already supplied, many positions can be calculated in parallel while the mask hides later answers. During ordinary autoregressive generation, the next token still depends on the token just chosen, so those new choices occur sequentially. Compare the two designs below: choose the length of the text and see how many steps information from the first token needs to reach the last.

Steps from first to last token
8−1=78 - 1 = 7
Steps that must happen one after another
88
Comparisons per head
—

Attention is not free. With the causal mask, token number ii compares itself with ii tokens, so a text of nn tokens needs 1+2+⋯+n1 + 2 + \cdots + n comparisons in each head of each layer.

1+2+⋯+n=n(n+1)21+2+\cdots+n=\frac{n(n+1)}{2}

To add this up, write the sum twice, once forwards and once backwards, and add the two lines term by term: 1+n1 + n, 2+(n−1)2 + (n - 1), and so on, each pair making n+1n + 1. There are nn pairs, so twice the sum is n(n+1)n(n + 1), and the sum is n(n+1)/2n(n + 1)/2. For 1,000 tokens that is 1000×1001÷2=500 5001000\times1001\div2 = 500\,500 comparisons, and doubling the length roughly quadruples the work. This is why long texts are expensive, and why much later research went into making attention cheaper. The time complexity lesson explains this kind of growth.

12

From the Transformer to today’s large models

Within a year, two uses of the Transformer appeared. GPT (OpenAI, 2018) kept the decoder and learned to predict the next token using a large collection of books. This is called pre-training. Further training on small labelled sets for particular tasks is called fine-tuning. BERT (Google, 2018) kept the encoder and learned to fill in hidden words using text on both sides, which suited tasks such as search and classification. Both showed that training on large amounts of raw text could learn language patterns useful for several tasks.

Then came growth. GPT-2 (2019) had 1.5 billion parameters; GPT-3 (2020) had 175 billion and was trained on about 300 billion tokens. GPT-3 showed something new: without any further training, it could do a task after seeing a few examples written into the prompt, such as a few English–French pairs followed by a new English sentence. In 2020 researchers measured that the loss falls smoothly and predictably as parameters, data and computation grow together; these are called scaling laws. In 2022 the Chinchilla study found that many models were too large for the amount of text they had seen. A good balance is roughly 20 training tokens per parameter. Chinchilla had 70 billion parameters and was trained on 70 billion×20=1400 billion70\text{ billion}\times20 = 1400\text{ billion} tokens, that is 1.4 trillion.

The chart shows published sizes. Each grid line up the side is ten times the one below it. We need such a scale because the sizes range from 65 million to 671 billion, about four steps of ten, and on an ordinary scale every model before 2020 would be squashed flat against the bottom. Choose a point to read its details. Several of the strongest models never published their size, so they are not shown rather than guessed.

GPT-3 · 2020 · Parameters: 175 billion

A model trained only to continue text is not yet an assistant: asked a question, it might reply with more questions. Two further stages of training turned it into one. In instruction tuning, the model is trained on examples of requests together with good responses written by people. In reinforcement learning from human feedback (RLHF), people compare pairs of the model’s answers. A second model learns to predict which answer people prefer. The language model is then adjusted to give answers that this second model scores highly. InstructGPT (2022) showed that people preferred the answers of a model trained this way with 1.3 billion parameters to those of the original 175-billion-parameter GPT-3. ChatGPT, released in November 2022, brought the result to the public. Anthropic, the company that trains Claude, introduced a related method, Constitutional AI, in which the model also critiques and revises its own answers against a written list of principles.

Since then the basic machine has remained the Transformer, while many of its parts have been improved.

Mixture of experts

The feed-forward step is split into many smaller networks, the experts, and a small router sends each token to only a few of them. The model can hold a great many parameters while each token uses only some: DeepSeek-V3 (2024) has 671 billion parameters but uses 37 billion for each token.

Longer context

The amount of text a model can attend to has grown from 2,048 tokens for GPT-3 to hundreds of thousands. Some models now reach a million or more. Cheaper ways of computing attention and better ways of encoding position made this possible.

More than text

Pictures, sound and video are cut into small patches and turned into vectors, so the same attention can mix them with words.

Reasoning

Since 2024 some models are trained, by reinforcement learning on problems whose answers can be checked, to write out long chains of intermediate steps before answering. This greatly improves their results in mathematics and programming.

Tools and agents

Models are trained to call search engines, run code and operate software, so that they can carry out tasks of many steps.

The best-known families today include GPT (OpenAI), Claude (Anthropic), Gemini (Google), Llama (Meta), DeepSeek and Qwen (Alibaba). Some publish their parameters for anyone to download; others do not publish even their size.

It is worth being clear about what has not changed. A model still produces one token at a time from probabilities learned from its training text. It can state false things fluently, which is called hallucination, because a likely continuation is not always a true one. Its knowledge stops at its training data unless it is given tools such as search. And how far its calculations amount to “thinking” is exactly Turing’s question, which is still open.

13

Diffusion: drawing by removing noise

We have followed a text generator that chooses one token after another. Next we study a different method for generating images: diffusion. First we need to know what a picture is to a computer: a grid of pixels, each holding a number for its brightness (three numbers, for red, green and blue, in a colour picture). A small 28×2828\times28 grey picture is just 28×28=78428\times28 = 784 numbers.

Now add noise. To every pixel add a random number drawn from the bell-shaped normal distribution, where most draws are close to 00 and a few are larger. Do it gradually over many steps, while multiplying the original brightness numbers by a smaller factor, without changing the image dimensions, and the picture fades into pure noise. After step tt the pixels are

xt=αˉt x0+1−αˉt εx_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\varepsilon

Here x0x_0 is the original picture, ε\varepsilon (epsilon) is the noise, and αˉt\bar\alpha_t (read “alpha bar t”) is the share of the original that survives: it starts at 11 and falls to almost 00. So the picture is a mixture of two ingredients, the original weighted by αˉt\sqrt{\bar\alpha_t} and the noise weighted by 1−αˉt\sqrt{1 - \bar\alpha_t}. Move the slider to add noise; the readout follows one pixel through the formula. Why square roots? Their squares add up to exactly 11: (αˉt)2+(1−αˉt)2=αˉt+1−αˉt=1\left(\sqrt{\bar\alpha_t}\right)^2 + \left(\sqrt{1 - \bar\alpha_t}\right)^2 = \bar\alpha_t + 1 - \bar\alpha_t = 1. This choice keeps variance equal to 1 only under a stated model: the clean-data variable and independent noise both have variance 1. It does not mean that the visible contrast of every fixed photograph stays unchanged. For a fixed clean pixel, only the noise is random, with variance 1 minus alpha-bar. The derivation below separates these cases and explains why squares appear.

share surviving αˉt\bar\alpha_t
1.0001.000
αˉt, 1−αˉt\sqrt{\bar\alpha_t},\ \sqrt{1-\bar\alpha_t}
1.000, 0.0001.000,\ 0.000
One pixel: x0, εx_0,\ \varepsilon
0.85, −0.860.85,\ -0.86
xtx_t
1.000×0.85+0.000×(−0.86)=0.8501.000\times0.85 + 0.000\times(-0.86) = 0.850

Adding noise is easy and needs no learning. The clever part is running it backwards. We train a neural network on millions of pictures with a simple task: given a noisy picture xtx_t and the step tt, guess the noise ε\varepsilon that was added. This task is easy to set up, because we made the noisy picture ourselves and know the right answer. Once the network can guess the noise, we can also guess the clean picture by rearranging the formula above:

x^0=xt−1−αˉt ε^αˉt\hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\hat\varepsilon}{\sqrt{\bar\alpha_t}}

The little hats mean “estimated”. To get this, subtract 1−αˉt ε\sqrt{1 - \bar\alpha_t}\,\varepsilon from both sides of the forward formula, which leaves αˉt x0\sqrt{\bar\alpha_t}\,x_0 on the right, then divide both sides by αˉt\sqrt{\bar\alpha_t}.

To make a new picture, start from pure noise and walk the steps backwards. At each step, guess the clean picture and work out the noise that this guess implies. Then put the two back together at the next, slightly lower noise level. Use the forward formula with αˉt−1\bar\alpha_{t-1} in place of αˉt\bar\alpha_t. Early on the guesses are vague averages; as the noise falls they sharpen, and at the last step αˉ0=1\bar\alpha_0 = 1, so the result is the final guess itself. This version of the walk is called DDIM; the original method, DDPM, also adds a little fresh noise at each step.

xt−1=αˉt−1 x^0+1−αˉt−1 ε^x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\,\hat\varepsilon

A whole picture has too many numbers to draw as one point, so the model below uses the smallest possible “pictures”: single points with 22 numbers. The training data are 240 points along a heart. On the left tab, add noise and watch the heart dissolve into a round cloud. On the right tab, generate: 500 points of pure noise walk back onto the heart. Choose one point to follow its path and the guess made at each step.

training pointsxtx_t (training points)
share surviving αˉt\bar\alpha_t
1.0001.000

Our small model does not need a trained network because it knows all 240 training points. Its guess of the clean point is a weighted average of these points. As in attention, softmax turns scores into weights. A training point dd receives a score for how well it explains the noisy point xtx_t. How do we calculate that score? The forward process shrinks dd to αˉt d\sqrt{\bar\alpha_t}\,d, which is where this clean point would be before noise was added. The squared distance from xtx_t to that position measures their difference: a shorter distance gives a better match. Dividing by twice the noise share, 2(1−αˉt)2(1 - \bar\alpha_t), and adding a minus sign makes shorter distances give higher scores:

sd=−∣xt−αˉt d∣22(1−αˉt)s_d=-\frac{\left|x_t-\sqrt{\bar\alpha_t}\,d\right|^2}{2\left(1-\bar\alpha_t\right)}

Why divide by the noise share? Early in generation the noise share 1−αˉt1 - \bar\alpha_t is large, so even far-off training points get scores close to the best one; many points share the weight and the guess is a blurry average. Near the end the noise share is tiny, the nearest point wins almost all the weight, and the guess becomes sharp. This is the same softmax-weighted average as in attention, with the noisy point as the query and the training points as both keys and values. The optional note derives the score.

Derivation: why the squares count, and where the toy’s scores come from

The spread of a random number is measured by its variance: the average of its squared distance from its average. Take x=aX+bYx = aX + bY, where XX and YY are independent with average 00. The average of x2x^2 is a2×(average of X2)+2ab×(average of XY)+b2×(average of Y2)a^2\times(\text{average of }X^2) + 2ab\times(\text{average of }XY) + b^2\times(\text{average of }Y^2). Independence and average 00 make the average of XYXY equal to 00, so the variance of xx is a2var⁡X+b2var⁡Ya^2\operatorname{var}X + b^2\operatorname{var}Y. With pixel values scaled to variance 11 and noise of variance 11, the weights a=αˉta = \sqrt{\bar\alpha_t} and b=1−αˉtb = \sqrt{1 - \bar\alpha_t} give variance αˉt+(1−αˉt)=1\bar\alpha_t + (1 - \bar\alpha_t) = 1 at every step.

Now the scores. If the clean point was dd, then xt−αˉt d=1−αˉt εx_t - \sqrt{\bar\alpha_t}\,d = \sqrt{1 - \bar\alpha_t}\,\varepsilon, so the noise must have been ε=(xt−αˉt d)/1−αˉt\varepsilon = \left(x_t - \sqrt{\bar\alpha_t}\,d\right)/\sqrt{1 - \bar\alpha_t}. We assume independent standard-normal noise coordinates. Their probability density is proportional to e−∣ε∣2/2e^{-|\varepsilon|^2/2}, where the squared length sums the squared noise coordinates. Density describes the relative chance of landing in equally small neighbourhoods, not a positive probability at one exact real number. Substituting the required noise gives a likelihood proportional to e−∣xt−αˉt d∣2/(2(1−αˉt))e^{-|x_t - \sqrt{\bar\alpha_t}\,d|^2/(2(1 - \bar\alpha_t))}, which is ee raised to the score.

Before seeing xtx_t, every training point was equally likely. By Bayes’ rule, the probability that xtx_t came from dd is then its likelihood divided by the total of all the likelihoods: exactly softmax of the scores. The guess with the smallest average squared error is the average of the possible clean points weighted by these probabilities, which is the formula the toy uses.

Why average the possible clean points?

The point model above begins by treating each stored clean point as equally likely. For the current noisy observation, a clean point receives more weight if its noise model gives that observation greater density. The shared prior probability and Gaussian density constant cancel between numerator and denominator, leaving each exponential score divided by their sum.

pi=esi∑jesj,∑ipi=1p_i=\frac{e^{s_i}}{\sum_j e^{s_j}},\qquad\sum_i p_i=1

Those weights do not yet tell us which number to output. We must state the objective: which guess minimises average squared error? Start with one coordinate. The candidate clean values are did_i, their weights are pip_i, their weighted mean is μ=∑ipidi\mu=\sum_i p_i d_i, and our guess is u.

Split the difference from guess to candidate into guess-to-mean and mean-to-candidate. After expanding the square, the cross term vanishes: the definition of the mean makes the weighted deviations sum to zero.

∑ipi(μ−di)=μ∑ipi−∑ipidi=μ−μ=0\begin{aligned}\sum_i p_i(\mu-d_i)&=\mu\sum_i p_i-\sum_i p_id_i\\ &=\mu-\mu=0\end{aligned}
∑ipi(u−di)2=(u−μ)2+∑ipi(μ−di)2\begin{gathered}\sum_i p_i(u-d_i)^2\\ =(u-\mu)^2+\sum_i p_i(\mu-d_i)^2\end{gathered}

The second term on the right does not change with u. The first is a nonnegative square, equal to zero at u=μu=\mu. Therefore the weighted mean is the best guess under squared error. In two dimensions, add the two coordinate errors and apply the same reasoning to each. This generally differs from choosing the single most probable point: the result depends on our stated squared-error objective.

Our toy explicitly stores a finite set of 240 clean points and computes its estimate from them. As its noise level becomes very small, its weights concentrate near those stored points, so its output tends towards this finite set. A real diffusion model instead learns a function from examples; that function can generalise to new combinations, but it can also memorise or reproduce training material. A finite network size does not rule out memorisation. Our small point experiment demonstrates its chosen empirical distribution, not a guarantee of originality or an account of every image model.

How does a prompt such as “a cat on a mat, oil painting” steer the picture? The text is first turned into vectors by a Transformer. At every step the denoising network attends to those vectors through cross-attention, as in the translation Transformer. So its guesses are pulled towards pictures that match the words. To save work, Stable Diffusion (2022) runs the whole process on a compressed version of the picture rather than on every pixel. This is called latent diffusion. Many newer image and video models use a Transformer as the denoising network itself. So the two halves of this page meet: attention and diffusion now work together.

In the forward process, what is αˉt\bar\alpha_t at the very start, t=0t = 0?

14

Back to Turing’s question

Let us return to Turing. In 1950 he suggested a test based only on conversation, and a machine that learns rather than one programmed rule by rule. Today’s language models are learning machines of exactly that kind. They hold a table of vectors, attention that lets tokens consult one another, and small networks inside each token. Billions of parameters are adjusted so they predict the next token of an enormous amount of text.

Whether that amounts to thinking is still debated. In the simplified generator we studied, each next-token choice is calculated from learned numbers and the supplied context. A complete assistant may also use written instructions, retrieval and other programmed tools. Understanding the learned calculation helps us check its facts, distinguish fluent wording from reliable evidence, and ask more useful questions.