Attention and the transformer
The transformer, introduced in 2017, is the architecture behind essentially every modern language model, and increasingly vision, audio and protein models too. Its key idea is attention.
Self-attention: every word looks at every other word
Consider: "The trophy didn't fit in the suitcase because it was too big." What does it refer to? You resolve it by relating it to trophy and big. Self-attention lets the model do the same: when processing each token, it looks at all the other tokens and decides how much each one matters.
Mechanically, each token's vector produces three new vectors:
- a query ("what am I looking for?"),
- a key ("what do I contain?"),
- a value ("what information do I pass on?").
Each token compares its query with every other token's key to get attention scores, turns those into weights with softmax, and takes a weighted mix of the values. The result is a new vector for that token that blends in context from the whole passage.
Multi-head attention runs many attention operations in parallel, each free to track a different kind of relationship: grammar, coreference, topic, position.
The transformer block
A transformer stacks dozens of identical blocks. Each block has:
- Multi-head self-attention: tokens exchange information.
- A feed-forward network: each token's vector is transformed on its own. Much of the model's stored knowledge is thought to live in these layers.
- Residual connections and normalization: keep signals stable through many layers.
Language models that generate text use causal (masked) attention: each token can only look at tokens before it, so the model learns to predict what comes next without peeking.
Why transformers won
| Recurrent networks | Transformers |
|---|---|
| Process tokens one at a time, so training can't be parallelized well | Process all tokens at once, so they train efficiently on GPUs |
| Memory of early tokens fades | Any token can attend directly to any other |
| Hard to scale | Scale smoothly with more data, parameters and compute |
The trade-off: attention compares every token with every other, so cost grows with the square of the text length. Much research goes into making long contexts cheaper.
From architecture to products
- Decoder-only transformers (GPT, Claude, Gemini, Llama) generate text and power chatbots.
- Encoder-only transformers (BERT) understand text and power search and classification.
- Vision transformers split images into patches and treat them like tokens.
Check your understanding
In self-attention, what does a token's 'query' represent?
Why did transformers replace recurrent networks for language?