How AI works
What is a transformer in AI, and what does attention do?
The design inside ChatGPT comes from a 2017 paper called Attention Is All You Need. Here's what attention actually computes, worked by hand on a five-word sentence, and why it pushed the older designs aside.
A transformer is a type of neural network, introduced by Google researchers in 2017, that looks at all the words of a passage at the same time instead of one after another. Its key step, attention, lets each word score how relevant the other words are to it, then update its own meaning with a blend weighted toward the most relevant ones. That's how "its" in "The dog wagged its tail" picks up that it means the dog. The GPT models behind ChatGPT are transformers.
What a transformer is, in plain English
Read this sentence: “The dog wagged its tail.” You knew right away that “its” means the dog's. You didn't get that from the word “its” alone. You connected it to another word in the sentence. Software reading text faces that problem with nearly every word, because what a word means depends on the words around it. “Bank” means one thing near “river” and another near “account”.
A transformer is a design for a neural network built to handle exactly that. A neural network is a large math function made of layers of simple units, with millions or billions of adjustable numbers inside called weights, tuned by training on examples (here's how one works). What sets a transformer apart is a step called attention: every word looks at the other words in the passage, works out which ones matter to it, and pulls in information from those.
The design comes from a 2017 paper by eight researchers working at Google, “Attention Is All You Need”, presented at the NIPS 2017 conference. It proposed a network based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Recurrence and convolutions were the two main older ways of passing information along a sentence. The paper's main test was translating English into German and French.
Here's the trip text takes through a transformer:
- Split the text into tokens. A token is a word or a piece of a word.
- Turn each token into a vector, a list of numbers that stands for it. These starting vectors are called embeddings, and the model learns them in training. In the original paper's base model each one was 512 numbers long.
- Add a signal for position, so the model can tell which word came first.
- Pass the vectors through a stack of identical layers. In each layer, the words first share information through attention, and then each word's vector goes through a small neural network on its own. The original paper stacked six layers.
- Use what comes out. In a chatbot, the final vector of the last token is turned into probabilities for the next token. In other uses, the final vectors serve as context-aware descriptions of every word, ready for a job like sorting reviews into positive and negative.
The original transformer had two halves, because translation needs both: an encoder that reads the source sentence and a decoder that writes the translation. By the top of either stack, the vector for “its” has been mixed with information from the words around it, so it carries far more than “some possessive word”.
How attention works: queries, keys and values
Attention sounds mysterious, but it's a short recipe of multiplying and adding. It's easiest to follow if you think of a search.
When you search a library catalog, you type what you want: your query. The catalog compares it with a label on every book, the book's key. The best matches come back, and you read what's inside them, their values. Attention runs that lookup for every word in the passage. The paper defines attention as mapping a query and a set of key-value pairs to an output, where the output is a weighted sum of the values. Unlike a catalog, it doesn't hand back only the top match. It hands back a blend of everything, weighted by how well each key matched.
So each word's vector is turned into three new vectors, by multiplying it with three grids of learned numbers:
- A query: what this word is looking for. For “its”, roughly “which earlier thing owns something?”
- A key: what this word offers, as a label other words match against. For “dog”, roughly “I'm a thing that can own a tail.”
- A value: the information this word passes along to any word that attends to it.
Nobody writes those descriptions. The model learns the three grids during training, and the numbers in them rarely line up with neat human labels. The descriptions are just a way to picture each vector's job.
Then, for each word, attention runs four steps:
- Score every word it can see. Compare this word's query with each word's key using a dot product: multiply the two lists position by position and add up the results. Vectors pointing the same way give a big score, and unrelated ones give a score near zero.
- Scale the scores down. Divide each score by the square root of the key's length. Long vectors produce large dot products, which push the next step into putting nearly all the weight on one word and leave training with almost no signal to learn from, so the authors scale the dot products to counteract it. They call the whole recipe scaled dot-product attention.
- Turn scores into percentages with softmax: raise the number e (about 2.718) to the power of each score, then divide each result by their total so everything adds up to 100%. These percentages are the attention weights. It's the same softmax a language model uses at its last step to turn scores into next-word probabilities, which our guide to large language models works through.
- Blend the values. Multiply each word's value by its weight and add them up. That weighted average is the attention output, and it gets added to the word's own vector, so the word keeps its meaning and gains some of its neighbors'. The paper writes this as LayerNorm(x + Sublayer(x)): the input x plus what the layer computed, then rescaled to a steady range.
In the paper's notation, the whole recipe is one line: Attention(Q, K, V) = softmax(QKT / √dk) V. Q, K and V hold the queries, keys and values of every word, stacked into grids. QKT computes every query-key dot product in one go, and dk is the length of each key. Doing all the words at once as grid (matrix) multiplication suits graphics chips (GPUs), which are built to run thousands of multiplications at the same time.
Attention worked by hand on one sentence
Here's one attention step run by hand on “The dog wagged its tail”, working out what “its” picks up from the other words. The numbers are invented and tiny on purpose: each vector has 2 numbers instead of 64 or more, chosen so the answer is easy to read. A trained model learns its own numbers. The arithmetic, though, is exactly what a real attention head does: score with dot products, scale, softmax, blend.
We'll use a chatbot-style model, where a word can look only at itself and the words before it. The paper's decoder enforces this with a mask that blocks later positions, so the prediction at each position depends only on the known outputs that came before it. So “its” can see “The”, “dog”, “wagged” and itself, but not “tail”.
Say the query for “its” is [2, 1]. Each key has 2 numbers, so the scores get divided by √2, about 1.41. (In the paper, each head's keys had 64 numbers, so it divided by 8.)
| Word | Key | Score: query · key | Score ÷ √2 | escaled score | Attention weight |
|---|---|---|---|---|---|
| The | [−1, 2] | 2×(−1) + 1×2 = 0 | 0 | 1.00 | 4.2% |
| dog | [2, 0] | 2×2 + 1×0 = 4 | 2.83 | 16.92 | 70.3% |
| wagged | [0, 1] | 2×0 + 1×1 = 1 | 0.71 | 2.03 | 8.4% |
| its | [1, 0] | 2×1 + 1×0 = 2 | 1.41 | 4.11 | 17.1% |
| tail | blocked by the mask, because it comes later | 0% | |||
The e column adds up to 24.06, and each weight is that row's number divided by 24.06. “dog” wins with 70.3%, because its key points the same way as the query. Look at what softmax did along the way: “dog” scored 4 and “its” scored 2, yet “dog” ends up with about four times the weight. Raising e to a power turns modest gaps in score into big gaps in weight. And “The” still gets 4.2%, because softmax never hands out exactly zero. Only the mask can do that.
Now the blend. To make the result readable, give the value vectors simple meanings: the first number means “animal” and the second means “action”. So “dog” has the value [1, 0], “wagged” has [0, 1], and “The” and “its” have [0, 0].
Output for “its” = 0.042 × [0, 0] + 0.703 × [1, 0] + 0.084 × [0, 1] + 0.171 × [0, 0] = [0.70, 0.08]
That gets added to the vector for “its”. After one attention step, “its” carries a strong dose of “animal” borrowed from “dog”, plus a trace of “action”. A real model does this across hundreds of numbers and many layers, and later layers build on earlier ones. Once “its” holds information about the dog, later words such as “tail” can pick that up by attending to “its”.
Trained models really do learn this kind of pattern. In the paper's appendix, the authors show two attention heads in layer 5 of 6 that are apparently involved in anaphora resolution, the linguists' name for working out what a word like “its” refers to, and they note that the attention from “its” is very sharp. Google's announcement of the paper shows a pair of sentences where “it” means an animal in one and a street in the other. In one of its steps, the model clearly identified the two nouns “it” could refer to, and the share of attention each noun got followed the meaning.
Heads, layers and word order: the rest of a transformer
Several attention heads at once
One attention step produces one blend, but words relate to each other in several ways at once. “its” needs its owner, “wagged” needs whoever did the wagging, and a later word might care about tense or tone. So a transformer runs several attention steps side by side, each with its own query, key and value grids. Each one is called a head. The paper's base model used h=8 parallel attention layers, or heads, each working with vectors of 64 numbers, and the eight results are joined back into one 512-number vector. According to the paper, this lets the model pick up different kinds of information from different positions for about the same computing cost as one full-size head.
A small neural network after every attention step
After attention, each word's vector goes through a small feed-forward network on its own, which the paper describes as two linear transformations with a ReLU activation in between. In plain terms: multiply by one grid of weights, replace any negative numbers with zero, then multiply by a second grid. Attention moves information between words. This part reworks what each word now holds.
It also holds most of an encoder layer's weights. In the base model, each encoder layer's attention grids hold about 1.05 million weights (four grids of 512 × 512: queries, keys, values, and one that combines the heads), while its feed-forward network holds about 2.1 million (512 × 2,048, then 2,048 × 512). The part the paper is named after is the smaller share of each encoder layer.
Why word order has to be added in
Attention on its own has a surprising blind spot: it ignores word order. Its scores come from comparing vectors, and nothing in that arithmetic knows where a word sits. Without position information, an attention layer in which every word can see every other word gives each word the same result for “dog bites man” as for “man bites dog”. Two sentences with opposite meanings would look the same.
The authors point out that since our model contains no recurrence and no convolution, order has to come from somewhere else. Their fix was to add a position signal to each word's starting vector, built from sine and cosine waves of different frequencies, so every position gets its own pattern. Later models often learn their position vectors instead. OpenAI's first GPT paper says it used learned position embeddings in place of the sine waves.
BERT, GPT and the two halves
Later models mostly kept one half of the original design. Hugging Face's course puts the split simply: encoder-only models are good for tasks that require understanding of the input, decoder-only models suit generating text, and encoder-decoder models suit jobs like translation and summarization. BERT, from 2018, is an encoder. Its name stands for Bidirectional Encoder Representations from Transformers, and it reads every word in light of the words on both sides. OpenAI's first GPT went the other way: a 12-layer decoder-only transformer with 12 heads per layer, trained to predict the next token. ChatGPT's models come from that GPT line, and OpenAI's technical report describes GPT-4 as a Transformer-based model pre-trained to predict the next token in a document.
Why transformers replaced recurrent neural networks
Before 2017, the standard tool for language was the recurrent neural network (RNN), including improved versions called LSTMs. The transformer paper itself calls them firmly established as state of the art approaches in sequence modeling. An RNN reads one token at a time, in order, and carries a hidden state: one vector that acts as its running summary of everything so far. Each new hidden state is computed from the previous one plus the current token. That design has two problems, and the transformer fixes both.
It's slow to train. Step 50 can't start until step 49 is done, because it needs step 49's summary. The paper says this inherently sequential nature precludes parallelization within training examples. GPUs are fast because they run thousands of calculations at once, and a recurrent network leaves most of that capacity idle. A transformer layer handles every position of a passage in the same pass.
Distant words have to survive a long relay. For word 2 to affect word 50, its information has to be squeezed into the summary and carried through 48 updates, and it tends to fade along the way. Google's announcement uses the sentence “I arrived at the bank after crossing the river”: an RNN could only work out that “bank” means a riverbank after reading each word between “bank” and “river” step by step. In a transformer's encoder, where words can look both ways, “bank” attends straight to “river” in one step, however far apart they are. The paper notes that learning long-range dependencies is a key challenge, and that shorter paths between words make it easier.
Attention itself is older than the transformer. In 2014, Bahdanau, Cho and Bengio added it to RNN translators. They suspected that squeezing a whole sentence into one fixed-length vector was a bottleneck, and their fix let the model (soft-)search for parts of a source sentence while translating. What the transformer changed was keeping the attention and dropping the recurrence entirely.
The paper's Table 1 sets out the trade-off. Here it is in plain words, where n is the number of tokens and d is the length of each word's vector:
| Per layer | Recurrent layer | Self-attention layer |
|---|---|---|
| Steps that must happen one after another | n (one per token) | 1 |
| Most steps between any two words | n | 1 |
| Work grows like | n × d² | n² × d |
The last row is the catch, so here are real numbers. With the base model's d = 512, a 100-token sentence costs a recurrent layer roughly 100 × 512² ≈ 26 million multiply-adds, against roughly 100² × 512 ≈ 5 million for self-attention. At 1,000 tokens the order flips: about 262 million for the recurrent layer and 512 million for attention. The paper says self-attention is faster when the sequence length n is smaller than the representation dimensionality d, which is usually the case for single sentences in machine translation. Even when attention does more arithmetic, it does it in parallel rather than in a queue.
The payoff came fast. The paper's big model trained for 3.5 days on eight GPUs and beat the best published English-to-German translation results, and Google's write-up says the design needed less computation, speeding up training by up to an order of magnitude.
Where beginners go wrong about transformers and attention
A few ideas about transformers sound right and aren't.
- “Attention means the model is concentrating, like a person.” It's a weighted average. Each word computes match scores, turns them into percentages and blends in other words' values. Nothing in it is aware of anything. It's the same arithmetic, repeated across heads and layers.
- “The attention weights show why the model gave its answer.” Tempting, since they make nice pictures, but contested. A 2019 study across several language tasks found that attention weights were frequently uncorrelated with gradient-based measures of feature importance (other ways of measuring which words mattered), and that very different attention distributions could produce the same prediction. A reply later that year argued the answer depends on one's definition of explanation. The safe reading: an attention map is a clue about what a model is doing, not proof.
- “A transformer reads everything at once, so a chatbot writes its whole answer at once.” It processes your prompt in parallel, but a GPT-style model still writes one token at a time, and each new token takes another pass through every layer. The parallelism mostly speeds up training and reading.
- “Longer context is free.” In an encoder, where every token scores every other token, the work grows with the square of the length. (A chatbot-style decoder scores only earlier tokens, which roughly halves the count, but it still grows with the square.) A 1,000-token passage needs 1 million scores per head in each layer, and 10,000 tokens need 100 million. Across the base model's 8 heads and 6 encoder layers, those 1,000 tokens already mean 48 million scores. The FlashAttention paper opens by noting that transformers are slow and memory-hungry on long sequences for this reason, and making attention cheaper is a busy research area.
- “Transformers are only for text.” Anything you can chop into a sequence works. A 2020 paper titled “An Image is Worth 16x16 Words” showed that a pure transformer applied directly to sequences of image patches can do very well at image classification. The patches play the part of words.
Common questions
Why is the paper called Attention Is All You Need?
Because its model dropped the recurrent and convolutional layers that earlier translation systems relied on and connected words using attention alone, plus small feed-forward networks. Attention wasn't new in 2017. Building a whole translation model on attention, with no recurrence at all, was.
Is a transformer the same as a large language model?
No. A transformer is a network design. A large language model is a model trained on a huge amount of text to predict the next token, and the best-known ones, such as OpenAI's GPT models, are built as transformers. The same design is also used for translation and for images.
What are query, key and value in attention?
They're three vectors the model computes from each word. The query is what the word is looking for, the key is what it offers to be matched against, and the value is the information it passes on. A word's attention weights come from comparing its query with the keys of the words it can see.
How many attention heads does a transformer have?
There's no fixed number. The original paper's base model used 8 heads per layer, each working with 64-number vectors, and OpenAI's first GPT used 12. It's a design choice, and bigger models tend to use more.
Can transformers work with images?
Yes. Vision transformers cut an image into small square patches and treat each patch like a word, so attention lets each patch draw on the patches that matter to it.
Learn it properly
This article works through one attention step by hand. How AI Really Works builds the full picture in order, with short lessons and hands-on exercises, including Attention, Simply and The Transformer, In Depth, then how a next-token predictor becomes an assistant and why scaling it up works.
Sources
- Attention Is All You Need (abstract) · Vaswani et al., arXiv, 2017
- Attention Is All You Need (full text, v7) · Vaswani et al., arXiv, 2017
- Attention is All you Need, Advances in Neural Information Processing Systems 30 (NIPS 2017) · NeurIPS Proceedings
- Transformer: A Novel Neural Network Architecture for Language Understanding · Google Research blog, Jakob Uszkoreit, 2017
- Neural Machine Translation by Jointly Learning to Align and Translate · Bahdanau, Cho & Bengio, arXiv, 2014
- LLM Course, Chapter 1: How do Transformers work? · Hugging Face
- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding · Devlin et al., arXiv, 2018
- Improving Language Understanding by Generative Pre-Training · Radford et al., OpenAI
- GPT-4 Technical Report · OpenAI, arXiv, 2023
- An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale · Dosovitskiy et al., arXiv, 2020
- Attention is not Explanation · Jain & Wallace, arXiv, 2019
- Attention is not not Explanation · Wiegreffe & Pinter, arXiv, 2019
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness · Dao et al., arXiv, 2022
Read next
How do large language models like ChatGPT work?
An LLM predicts the next chunk of text, one token at a time, from patterns learned in billions of examples. Here's the mechanism, with real numbers.
What is gradient descent, explained simply?
Gradient descent finds a low point by measuring the slope and stepping downhill, again and again. See it worked in numbers, with steps too big and too small.
How is an AI model actually trained, step by step?
An AI model is trained by making guesses, scoring the errors with a loss function and nudging its numbers downhill with gradient descent, step by step.