TL;DR
The short answer
A transformer is a neural network that processes all the tokens of a text at once and lets each token look at every other token to work out what it means in context. That look-around step is called attention. In "the animal didn't cross the street because it was tired," attention is how "it" connects to "animal."
A transformer stacks dozens of layers, each with an attention step (tokens exchange information) and a feed-forward step (each token is processed on its own). Invented at Google in 2017, it's the architecture behind ChatGPT, Claude, Gemini, Llama and most modern AI for images, audio and video too.
The problem: meaning depends on context
After lesson 4, every token has an embedding, a list of numbers for its meaning. But one embedding per token isn't enough, because words change meaning with their neighbors. "Bank" in "river bank" and "bank account." "Apple" in "apple pie" and "Apple stock." And the classic:
The animal didn't cross the street because it was too tired.
The animal didn't cross the street because it was too wide.
One word changes at the end, and "it" switches from the animal to the street. To understand "it," a model must connect it to the right word, possibly far away, using knowledge about the world (animals get tired, streets are wide).
Before 2017, language models read text the way you'd read a telegram, one word at a time, passing a summary of everything so far to the next step. These recurrent networks had two big bugs: the summary faded over long texts, and the word-by-word design couldn't use the thousands of parallel cores in a GPU.
Attention: every word asks a question
Attention lets each token gather information from the other tokens directly, in one step, no matter how far apart they are. It works through three roles that every token plays at once. They have intimidating names, but they're like a matchmaking party:
- Each token holds up a query: "Here's what I'm looking for." For "it," something like "I'm a pronoun; I need the noun I refer to."
- Each token wears a key: "Here's what I am." For "animal": "I'm a noun, a living thing, the subject of this sentence."
- Each token carries a value: "Here's the information I'll share if you pick me."
Every token compares its query with every other token's key and gets a match score. The scores are turned into percentages that add up to 100% (with the same softmax trick that turns scores into probabilities in lesson 7). Then each token takes a blend of everyone's values, weighted by those percentages. If "it" matches "animal" at 70%, its new embedding is mostly made of what "animal" had to share.
The queries, keys and values aren't programmed. Each token computes them from its embedding by multiplying it with three weight matrices, and those weights are learned in training like every other knob. Nobody teaches the model grammar. It discovers that matching pronouns to nouns, verbs to subjects and adjectives to the things they describe lowers the loss, and the attention weights drift into those patterns.
import numpy as np
def softmax(x):
e = np.exp(x - x.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def attention(Q, K, V):
scores = Q @ K.T / np.sqrt(K.shape[-1]) # how well each query matches each key
weights = softmax(scores) # every row sums to 1
return weights @ V, weights # each token gets a blend of values
rng = np.random.default_rng(0)
x = rng.normal(size=(4, 8)) # 4 tokens, 8 numbers each (real models: thousands)
Wq, Wk, Wv = (rng.normal(size=(8, 8)) * 0.3 for _ in range(3)) # learned in a real model
out, w = attention(x @ Wq, x @ Wk, x @ Wv)
print(np.round(w, 2)) # row i: how much token i looks at each tokenMany heads, many layers
A sentence has many relationships at once. "It" relates to "animal" (what it refers to), "tired" relates to "it" (what's tired), "didn't" relates to "cross" (what's negated). One attention pattern can't capture all of that, so each layer runs several attention operations side by side, called attention heads, each with its own queries, keys and values. Researchers who look inside trained models find heads that specialize: some track the previous word, some link pronouns, some follow quotes or brackets in code.
After attention comes the second half of each layer, the feed-forward network: a small two-layer network (lesson 2) applied to each token separately. If attention is the meeting where tokens share information, the feed-forward step is each token going back to its desk to think about what it heard. Research suggests much of a model's factual knowledge is stored in these feed-forward weights.
Then the whole thing repeats. A transformer is a stack of these layers, each refining every token's embedding a little more.
| Model | Year | Layers | Attention heads per layer |
|---|---|---|---|
| Original Transformer (base) | 2017 | 6 + 6 (encoder and decoder) | 8 |
| GPT-2 (largest) | 2019 | 48 | 25 |
| GPT-3 | 2020 | 96 | 96 |
How a transformer knows word order
Attention has a strange blind spot: it treats the text as a bag of tokens. Every token looks at every other one, and nothing in the matching says who came first. "Dog bites man" and "man bites dog" would look the same.
The fix is to mix position information into each token's embedding before the first layer, so that "dog at position 1" differs from "dog at position 3." The original paper used a pattern of waves of different frequencies; most modern models use a cleverer variant called rotary position embeddings. Either way, the model learns to use position like any other information.
One more rule matters for chatbots. A model that generates text is trained to predict the next token, so it must not peek at the future. In GPT-style models, each token can only attend to the tokens before it. This is called causal (or masked) attention, and it's why these models write strictly left to right.
Why transformers won
The 2017 paper, "Attention Is All You Need," was about machine translation. Its best model trained in three and a half days on eight GPUs and set new records. But the real breakthrough was that transformers fit the hardware: all tokens are processed at the same time, so training splits neatly across thousands of chips. That made it possible to scale models up enormously, and as lesson 6 explains, scale turned out to be most of the game.
The architecture also turned out to be general. A transformer doesn't care what its tokens are. Cut an image into small patches and treat each patch as a token, and you get a vision transformer (2020). Do the same with chunks of audio, video frames or molecules. DeepMind's AlphaFold 2, which predicted protein structures well enough to win a share of the 2024 Nobel Prize in Chemistry, is built around attention.
Exercise · about 5 minutes
Be an attention head
Take this sentence: "Sarah handed Maria the keys because she was leaving early."
- Who is "she"? Write down your answer and the words that made you decide.
- Now change the ending: "...because she had asked for them." Who is "she" now? Which word flipped it?
- Ask a chatbot the same two questions. Then ask it to explain which words it relied on.
- Draw the sentence with arrows from "she" to the words it should attend to most, thick for strong and thin for weak.
You just did what one attention head does, with the same clues: the other words, and knowledge about how the world works.
Quiz
1.What problem does attention solve?
2.In attention, what do queries and keys do?
3.Why does a transformer have many attention heads per layer?
4.Why does a transformer need position information added to its embeddings?
5.Which property did most to make transformers win over recurrent networks?
0 of 5 answered
Key takeaways
Meaning depends on context. Attention lets every token look at every other token to pick up that context.
Each token has a query (what it looks for), a key (what it is) and a value (what it shares). All three are learned.
Each layer has many attention heads plus a feed-forward step, and a transformer stacks dozens of layers.
Position information is added because attention alone ignores word order. Chat models attend only to earlier tokens.
Transformers won because they parallelize well. The cost: attention grows with the square of the text length.
Go deeper
- Jay Alammar: The Illustrated TransformerThe classic visual walkthrough of the architecture, used in university courses around the world.
- 3Blue1Brown: Attention in transformers, step by stepA gorgeous animated explanation of queries, keys and values.
- Transformer ExplainerAn interactive visualization of a real GPT-2 model running in your browser, from Georgia Tech.
- How Transformer LLMs Work (DeepLearning.AI)A free short course by Jay Alammar and Maarten Grootendorst that goes one level deeper.
- Vaswani et al. (2017), Attention Is All You NeedThe original transformer paper.