Concept · Chapter 7: Transformers
Self-Attention
Self-attention lets every token in a sequence look at every other token, decide how relevant each one is, and update itself with a weighted mix of what it finds.
The problem
In a recurrent network, information between distant words must travel step by step through every word in between — slow to compute and easy to lose.
The solution
Let each token compare itself to all tokens at once (via dot products of learned queries and keys), convert the scores into weights with softmax, and take a weighted sum of their values.
The consequence
Any two tokens interact in a single step, the whole sequence is processed in parallel, and the cost grows with the square of sequence length — which later drives work like KV caching and FlashAttention.
You should understand first
Start from the simplest version
Forget Q, K and V for a moment. Take one sentence:
the cat sat because it was tired
To understand "it", a reader looks back and connects it to "cat". Self-attention gives the model a way to do the same thing: each word asks "which other words matter to me?" and pulls in information from them.
We already have the tools:
- Every word is a vector (an embedding).
- The dot product scores how aligned two vectors are.
- Softmax turns a list of scores into weights that sum to 1.
- A weighted sum mixes vectors according to those weights.
That's attention. Build it one step at a time:
Try it · toy model
One short sentence, one question: which words should each word pay attention to? Build attention step by step — similarity, softmax, weighted sum, then queries and keys.
Why queries, keys and values?
Scoring raw embeddings against each other has a flaw: a word is always most similar to itself, and "what I'm looking for" is forced to be the same as "what I am". So each token makes three different vectors, each through its own learned matrix:
| Vector | Role | Analogy |
|---|---|---|
| Query | what this token is looking for | the search box |
| Key | what this token offers to others | the item's index card |
| Value | the information actually passed along | the item's contents |
The model learns during training, so it learns what to look for and what to advertise.
The equation
Causal masking
A GPT-style model predicts the next token, so while training, position 5 must not peek at positions 6, 7, 8. We set those scores to before the softmax, which makes their weights exactly 0. The attention matrix becomes lower-triangular.
The price: O(n²)
Every token scores every other token, so a sequence of tokens needs an table. Doubling the context length quadruples that work and memory. Much modern engineering — KV caches, FlashAttention, grouped-query attention — exists to live with this cost.
Why should I care?
As a researcher
It's the core operation of the Transformer. Most architecture papers since 2017 modify some part of it: positions, heads, masking, cost or memory.
As an engineer
Its quadratic cost in context length is why long contexts are expensive, why KV caches exist, and why inference is often memory-bound.
Modern systems that depend on it
- Transformer blocks
- BERT and GPT
- Every modern LLM
- KV cache
- FlashAttention
- Vision Transformers
Historical context
Before
RNNs and LSTMs passed information along the sequence one step at a time; attention existed, but as an add-on connecting a decoder to an encoder.
After
Multi-head attention, the Transformer, and eventually efficiency variants (multi-query and grouped-query attention, FlashAttention, sparse and linear attention).
Used today
Every layer of every Transformer-based model: GPT-style chat models, BERT-style encoders, embedding models, vision and speech Transformers.
What to remember
- Each token produces a query, a key and a value by multiplying its vector with three learned matrices.
- Score = query · key: how relevant that token is to this one.
- Scores are divided by √d to keep softmax from saturating, then softmaxed into weights.
- Output = weighted sum of the values.
- Causal masking hides future tokens in GPT-style models.
- Cost is O(n²) in sequence length n.
Key papers
Neural Machine Translation by Jointly Learning to Align and Translate
Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio · 2014 · ICLR 2015
Introduced attention in neural networks for language: instead of squeezing a sentence into one vector, the decoder looks back at every input word and decides which ones matter right now.
How to read it: Figure 3's alignment heat-maps are the best picture of 'attention' ever drawn — look at them first.
Attention Is All You Need
Ashish Vaswani, Noam Shazeer et al. · 2017 · NeurIPS 2017
Introduced the Transformer — the architecture behind BERT, GPT and nearly every modern large language model, and later adapted to vision, audio and more.
How to read it: Section 3 is the architecture — read it with Figure 1 open. Sections 3.2.1–3.2.2 contain the attention equation. You can skim the training details on a first pass.
Watch
3Blue1Brown
Attention in transformers, step-by-step | Deep Learning Chapter 6
Animates exactly what queries, keys and values do. Watch it alongside the Attention Explorer.
Andrej Karpathy
Let's build GPT: from scratch, in code, spelled out.
The best way to reach IMPLEMENT level on Transformers: write one yourself, line by line, in PyTorch.