Transformers
Attention lets each token gather information from the others: the architecture behind modern AI.
For decades, networks read text the way you read this sentence: one word after another, carrying a running summary. In 2017 a new design dropped that habit. In a transformer each word gathers information directly from the other words it is allowed to see, in a single step, and all the words are processed at once. That one change is behind today's language models, and it spread to images, speech, code and proteins.
What you’ll learn
- Explain why reading a sequence one step at a time is a bottleneck, and how attention lets each token draw directly on the tokens it may see, all positions in parallel.
- Describe self-attention as a soft lookup with queries, keys and values, and compute softmax weights from a few scores.
- Name the parts of a transformer block: attention heads, a feed-forward network, residual connections, normalization and positional information.
- Explain how a language model splits text into tokens, is trained to predict the next token, and generates text with temperature and sampling.
- Explain why attention's cost grows with the square of the context length, and name the main ways around it.
Reading everything at once
Before 2017 the standard network for text was a recurrent neural network. It reads one token (roughly, one word) at a time and carries a hidden state, a running summary, from each step to the next. Two problems follow from that design:
- Distance. For word 1 to influence word 50, its information has to survive 49 updates of the summary, and in practice much of it fades.
- Waiting. Step 50 cannot start until step 49 is done, so the steps cannot be spread across the thousands of arithmetic units of a GPU.
In 2017 Ashish Vaswani and colleagues proposed a network with no recurrence at all, the transformer, in a paper titled "Attention is all you need". Its central operation, self-attention, lets each position read directly from every position it is allowed to see, in one step: all of them in an encoder, which reads a whole text at once, and only the earlier ones in a decoder, which writes text left to right. Either way, all positions of a sequence are computed at the same time.
Think first A recurrent network and a transformer each train on the same 1,000-token document. Why can the transformer use a GPU so much better?
The recurrent network must compute its 1,000 hidden states one after another, because each needs the previous one. The transformer computes all 1,000 positions at once: during training it sees the whole document and only has to hide the future from each position. A GPU is built for exactly that kind of work, many independent multiplications at the same time.
Attention is a soft lookup
Think of looking up a word in a dictionary. You hold a query (the word you want), compare it with every key (the headwords), and read off the value (the definition) of the one that matches. Self-attention does the same, but softly: instead of returning one entry, it returns a blend of all of them, weighted by how well each one matches.
Each token produces three lists of numbers (vectors), computed from its own embedding:
- a query: what this token is looking for;
- a key: what this token offers to others who are looking;
- a value: what it hands over if it is chosen.
The match between a query and a key is a score: multiply their entries pair by pair and add them up. A higher score means a better match. The scores are then turned into weights by the softmax:
A query scores three keys at , and . What weight, in percent, does the softmax give the first key? (Use and .)
Show the answer
66.5 %
. The other two keys get about and . A gap of one point in score multiplies the weight by : softmax favors the best match strongly, but it never ignores the others completely.
Many heads, one block
One softmax gives one blend per token. Language needs several at once: which word came just before, which noun a pronoun refers to, which words share a topic. Multi-head attention runs several attention heads side by side, each with its own ways of making queries, keys and values, so each head can look for something different. Their results are joined and mixed into one vector per token.
A transformer is a stack of identical blocks. Each block does two things to the vector of every token:
- Attention: the token gathers information from the other tokens. This is the only step where tokens exchange anything.
- A feed-forward network: a small two-layer network applied to each token on its own, which transforms what was gathered.
Each step adds its result to the token's vector instead of replacing it (a residual connection), and the vectors are rescaled to a standard size before each step (layer normalization). Both keep very deep stacks trainable. GPT-2's smallest model stacks 12 blocks; GPT-3 stacks 96.
Feed "dog bites man" and "man bites dog" to attention layers that have no information about positions. What happens?
- The outputs differ, because "bites" attends to different words
- Each word gets exactly the same output vector in both sentences, so the network cannot tell who bit whom
- The network cannot process the second sentence at all
- The outputs differ, because the softmax depends on the order of the keys
Show the answer
B. Each word gets exactly the same output vector in both sentences, so the network cannot tell who bit whom
Scores depend only on the contents of the query and key vectors, and the softmax and the weighted average do not care in which order the keys are listed. Each word sees the same set of words in both sentences, so it gets the same output. That is why every transformer adds a positional encoding: originally a pattern of sine waves added to each embedding, today often a rotation of queries and keys that depends on position.
Text in, next token out
Networks compute with numbers, so text is first cut into tokens by a tokenizer. Common words become one token and rare words several pieces, so any text can be written with a fixed vocabulary of, say, 50,000 tokens. The usual recipe, byte-pair encoding, starts from single characters and repeatedly glues together the most frequent neighboring pair.
A language model is trained on one simple task, next-token prediction: given the tokens so far, output a probability for every token of the vocabulary, and pay a penalty that grows the less probability the true next token got. Repeated over trillions of tokens of text, this one task forces the model to pick up spelling, grammar, facts and patterns of reasoning, because all of them help predict what comes next.
To train on every position of a text at once, a causal mask stops each token from attending to the tokens after it; otherwise it could simply look up the answer. Transformers come in three shapes:
| Shape | Who sees whom | Trained to | Good at |
|---|---|---|---|
| Encoder, e.g. BERT (2018) | every token sees the whole text, both ways | fill in hidden words (masked language modeling) | classifying text, finding similar documents |
| Decoder, e.g. the GPT series (2018 on) | each token sees only earlier tokens | predict the next token | generating text, chat, code |
| Encoder–decoder, e.g. the original transformer, T5 | a two-way encoder reads the input; a one-way decoder writes the output and attends to the encoder through cross-attention | map one sequence to another | translation, summarization |
Generating text
A decoder writes by repeating one step: compute the distribution of the next token, choose one, append it, and run again. How to choose is up to you. Greedy decoding always takes the most likely token. Sampling draws at random from the distribution, so the same prompt can continue in many ways.
The temperature divides the scores (the logits) before the softmax. Below it sharpens the distribution toward the favorite; above it flattens it so unlikely tokens get a real chance. Top-k keeps only the most likely tokens, and top-p (nucleus) sampling keeps the smallest set whose probabilities add up to ; both cut off the long tail of unlikely tokens.
One more trick makes generation fast. Earlier tokens never change, and under the causal mask neither do their keys and values, so a model stores them in a KV cache instead of recomputing them for every new token. Each new token then computes only its own query, key and value and attends to the cache. The price is memory: the cache grows with every token in the context window.
The price of looking everywhere
Each token scores every token it may see, so a text of tokens needs scores in every head of every layer, or about half as many under a causal mask. Either way, double the context and that work quadruples.
Computing the attention scores for a 1,000-token text takes 1 unit of work. How many units does a 4,000-token text take?
Show the answer
16 units
The number of scores is : . The rest of the network (the feed-forward layers and the projections that make queries, keys and values) grows only in proportion to , so for long texts attention takes over the bill, while the KV cache grows only 4-fold.
Researchers attack this cost from several sides: let each token attend only to a window of nearby tokens; compute exact attention in small tiles that never leave the GPU's fast on-chip memory (FlashAttention); let many heads share one set of keys and values to shrink the cache; or replace attention with recurrences that train in parallel, the state space models of the topic Recurrent Networks & Sequence Models. A mixture of experts attacks a different cost: it sends each token through only a few of many feed-forward networks.
The Representation level opens each piece. Self-Attention & Multi-Head Attention derives scaled dot-product attention, masks and the cost of a layer. The Transformer Block assembles the residual stream, normalization, feed-forward layers and positional information, and counts parameters and FLOPs. Transformer Language Models covers tokenization, the training objective, encoders versus decoders and decoding. Efficient Transformers takes on the quadratic cost and the memory of inference. Twelve Emergence lessons then go to the research frontier: attention as associative memory, attention sinks and massive activations, what transformers can compute, feed-forward layers as memories, mixtures of experts, the anatomy of a modern LLM, pretraining objectives compared, language modeling as compression, multi-token and diffusion language models, FlashAttention, serving systems and speculative decoding.
Key takeaways
- A transformer replaces step-by-step recurrence with attention: each token draws directly on the tokens it may see (all of them in an encoder, the earlier ones in a causal decoder), and all positions are computed in parallel.
- Self-attention is a soft lookup: a query is scored against every key, the softmax turns the scores into positive weights that sum to , and the output is the weighted average of the values.
- Multi-head attention runs several lookups side by side; a block adds a per-token feed-forward network, with residual connections and normalization, and positions must be added explicitly.
- Language models tokenize text, are trained to predict the next token, and generate by sampling, with temperature, top-k and top-p controlling randomness. Encoders such as BERT read both ways; decoders such as GPT only look back.
- Attention's work grows with the square of the context, and the KV cache with its length; efficient variants restrict, reorganize or replace the computation.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A query's attention scores for four keys are , , and . Which statement about its attention weights is true?
- They are the scores divided by their total: , , and
- All four are positive and they add up to , with most of the weight (about 81%) on the first key
- Only the first key gets any weight, because it has the highest score
- They add up to , one unit per key
Show the answer
B. All four are positive and they add up to , with most of the weight (about 81%) on the first key
The softmax exponentiates and normalizes: against , so the first key gets about , the second and the last two each. Every weight is positive and the total is exactly .
Inside a transformer block, which operation moves information from one token's vector to another's?
- The feed-forward network
- Layer normalization
- Self-attention
- The residual connection
Show the answer
C. Self-attention
Attention is the only step in which a token's new vector depends on other tokens. The feed-forward network, normalization and the residual addition all act on each token separately.
Which pairing of model and training is correct?
- BERT sees the whole text in both directions and is trained to fill in hidden words; GPT sees only earlier tokens and is trained to predict the next token
- BERT is trained to predict the next token; GPT is trained to fill in hidden words
- Both see the whole text in both directions; they differ only in size
- GPT uses no attention at all, only feed-forward layers
Show the answer
A. BERT sees the whole text in both directions and is trained to fill in hidden words; GPT sees only earlier tokens and is trained to predict the next token
An encoder such as BERT attends both ways and learns by masked language modeling. A decoder such as GPT uses a causal mask and learns by next-token prediction, which is exactly what text generation needs.
You lower the sampling temperature from to . What happens to the generated text?
- It becomes more random, because low temperature flattens the distribution
- Nothing changes, because temperature only affects training
- The model forgets the prompt
- It becomes more predictable, close to always picking the most likely token
Show the answer
D. It becomes more predictable, close to always picking the most likely token
Dividing the logits by multiplies every gap between them by , so the softmax piles almost all probability on the top token. As the temperature approaches , sampling becomes greedy decoding.
A model's context grows from 2,000 to 8,000 tokens. Roughly how much more work do the attention scores of one layer take?
- times
- times
- times
- The same, since the model has the same number of parameters
Show the answer
C. times
The number of query–key scores is , and . The parameters are unchanged, but attention's work depends on the length of the text, not only on the weights.
Go deeper
- Self-Attention & Multi-Head Attention · Queries, keys and values, scaled dot products and many heads in parallel.
- The Transformer Block · Residual stream, normalization, feed-forward layers and positional information.
- Transformer Language Models · Tokenization, next-token prediction, encoders versus decoders, and generating text.
- Efficient Transformers · The quadratic cost of attention, inference memory and the ways around them.
Further reading
- A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
- S. J. D. Prince, Understanding Deep Learning, ch. 12 "Transformers" (MIT Press, 2023), free at udlbook.github.io/udlbook.
- D. Jurafsky & J. H. Martin, Speech and Language Processing (3rd ed. draft), the chapters on transformers and large language models, free at web.stanford.edu/~jurafsky/slp3.