6.3 — Self-attention vs cross-attention
Goal: Specify where Q, K, V come from in practice: three separate linear projections of a single input (self-attention), or queries from one sequence and keys/values from another (cross-attention). Understand why three projections, and why the decoupling matters.
1. Why this session exists
6.2 wrote the attention operation as a function of three matrices — but did not say where they come from. In a real Transformer, , , and are all produced from the input embeddings by learned linear projections. This session specifies the wiring.
Two patterns appear in practice:
- Self-attention. , , are all projections of the same input sequence. A token can attend to other tokens in its own sequence. Used everywhere in decoder-only LLMs (GPT, LLaMA, Claude, Mistral).
- Cross-attention. comes from one sequence; come from another. A token in one sequence attends to tokens in a different one. Used in encoder–decoder Transformers for translation (the original AIAYN setup) and in multimodal models where a text sequence attends to an image-token sequence.
The single most-asked question once people see attention is "why three separate projections?" The answer is in §3.[1, 3]
2. Self-attention
For an input sequence of tokens with embedded representations (one embedding row per token), self-attention introduces three learnable matrices:
and computes:
All three matrices act on the same but with different weights. The output has one row per token — each row is what that token's query "found" by attending to all the keys.
Most modern Transformers use (a single dimension we will just call — the "head dimension" — once we introduce multi-head in 6.4). In the single-head case , but multi-head splits across heads.
2.1 The slogan
A clean way to read self-attention:
"Each token computes a query, every token broadcasts a key and a value, and the token gathers a weighted mixture of values according to how well its query matches each key."
The mixing is not uniform across pairs of tokens (as it would be in some hand-wired graph) and not fixed by position (as in convolution). It is content-addressed: token attends to token if and only if is large.
2.2 Why three matrices and not one
The most common confusion: if produces both and via linear maps, why not just use for both — set and skip the projections?
Four reasons.
(a) Three distinct roles. Each token plays three different roles at the same position:
- As a query: "what am I looking for?"
- As a key: "what do I represent?"
- As a value: "what do I contribute if attended to?"
These are different questions and they need different answers. A learned linear projection lets the network express each role in its own subspace. Setting forces "what I look for" and "what I represent" to be the same vector — pushing a token to attend mostly to itself, which destroys the operation's usefulness.
(b) Independent normalisation. Queries and keys are dot-producted; their magnitudes matter. Values are averaged; their directions and magnitudes matter for content delivery. Decoupling lets the network normalise queries/keys for the dot-product geometry while letting values have whatever scale matches the downstream computation.
(c) Asymmetry. The score is generally not equal to (with three different projections). This asymmetry is necessary for language: "the cat sat" should not give the same attention pattern as "sat the cat". If , the score is symmetric, and the attention matrix is symmetric — a serious expressive limit.
(d) Capacity. Three independent projection matrices give the layer parameters. With a single shared matrix it would be . The extra parameters are cheap relative to the FFN block (6.8), and they buy substantial expressive power.
3. Cross-attention
Cross-attention appears when there are two sequences and we want one to read from the other.
The classic setting is the encoder–decoder Transformer for machine translation (Vaswani et al., 2017)[2]:
- The encoder takes a source sequence (e.g. an English sentence) and produces a contextualised representation via self-attention layers.
- The decoder generates a target sequence (e.g. a French translation), token by token. At each step, the decoder needs to "look at" the source to know what to translate. That look is cross-attention.
In a cross-attention layer:
Queries come from the target sequence; keys and values come from the source. The output has shape — one row per target token, each row a mixture of source representations.
3.1 Cross-attention in modern LLMs
Pure decoder-only LLMs (GPT, LLaMA, Mistral, Claude) use only self-attention. There is no separate encoder; the entire input — prompt and generated tokens — lives in one sequence and uses self-attention throughout.
Cross-attention is still important in three modern settings:
- Encoder–decoder Transformers (T5, original BART, mT5, Whisper). The encoder reads input, the decoder cross-attends to it while self-attending to the output. Whisper is the most familiar example — it cross-attends from text decoder to audio encoder.
- Multimodal models. Vision-language models (Flamingo, IDEFICS, some early LLaVA variants) bridge an image encoder to a text decoder via cross-attention layers. The text decoder's queries attend to the image encoder's keys/values.
- Retrieval-augmented generation (RAG) variants. Some architectures add a cross-attention layer that lets the model read from a separate "memory" or retrieved-document encoder.
For the rest of this course's main path — decoder-only LLM pretraining — every attention layer is self-attention. We focus on the self-attention case from 6.4 onwards; cross-attention shares the same mathematics with a different source for .
4. The full picture of one self-attention sub-layer
Putting §2 together, the self-attention sub-layer of a Transformer is:
With , , , attention matrix , output .
In multi-head attention (6.4), the same operation is run times in parallel on different projections of , then concatenated. In 6.5 we add the causal mask. In 6.7 we modify and for positional information. The block is then completed in 6.8 with an FFN.
The four-line specification above is the entire content of "one attention head." All subsequent complexity is glue.
5. Parameter count
For a single attention head with hidden size and head dim :
Plus the output projection (introduced for multi-head in 6.4), which adds another parameters for the whole sub-layer.
For heads with — the standard configuration — the total over is
A clean number to memorise: a self-attention sub-layer has parameters (ignoring biases, which are sometimes omitted in modern Transformers anyway). For , that's M parameters per self-attention block. The FFN block (6.8) will be twice as expensive — .
6. What we keep going forward
Two things to lock in for the rest of the chapter:
- Self-attention is one specific wiring of the general attention formula. all come from the same input via three learned linear projections. The parameters of a self-attention layer are exactly (plus once we go multi-head).
- Cross-attention exists and is structurally identical, except come from a different sequence. It powers encoder-decoder models and multimodal Transformers. Decoder-only LLMs do not use it.
From 6.4 onward, "attention" means self-attention unless explicitly stated otherwise.
(a) Given and projections , write the entries in terms of and the weight entries. Verify the shapes.
(b) Show that if , the attention matrix is symmetric up to the softmax (i.e. the pre-softmax score matrix is symmetric). Argue why this is a problem for language modelling using a specific 3-word example.
(c) A self-attention layer with and a single head has how many parameters in alone? Same question for .
(d) Identify the queries, keys, and values in a Whisper-style speech-to-text cross-attention layer. What is the source sequence, what is the target sequence, and which tokens attend to which?
(e) Decoder-only Transformers (GPT, LLaMA) need to know about the prompt and the generated text. Argue why "self-attention with a causal mask over the full prompt+generation sequence" plays the same role as the encoder–decoder split in machine-translation Transformers. (No formal proof needed — just the structural argument.)
References
- [1]
Raschka, S. (2024). Build a Large Language Model (From Scratch), Chapters 3–4. Manning. — Self-attention implementation (6.3, 6.4), causal masking (6.5), pre-norm block (6.10–6.11).
↩ - [2]
Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). "Attention is all you need". NeurIPS. arXiv:1706.03762 — The Transformer paper. Scaled dot-product attention (6.2), multi-head attention (6.4), encoder–decoder cross-attention (6.3), sinusoidal positional encoding (Appendix 6.A), the FFN sub-layer (6.8), post-LN block diagram (6.10), full architecture read (6.11).
↩ - [3]
Radford, A., Narasimhan, K., Salimans, T., & Sutskever, I. (2018). "Improving language understanding by generative pre-training" (GPT-1). OpenAI technical report. — Decoder-only Transformer with causal self-attention (6.3, 6.5); first use of learned PE (Appendix 6.B).
↩