AI / ML Theory
Chapter 6 · 16 min

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 Q,K,VQ, K, V — but did not say where they come from. In a real Transformer, QQ, KK, and VV are all produced from the input embeddings by learned linear projections. This session specifies the wiring.

Two patterns appear in practice:

  • Self-attention. QQ, KK, VV 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. QQ comes from one sequence; K,VK, V 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 TT tokens with embedded representations X∈RT×dX \in \mathbb{R}^{T \times d} (one embedding row per token), self-attention introduces three learnable matrices:

WQ∈Rd×dk,WK∈Rd×dk,WV∈Rd×dv,W_Q \in \mathbb{R}^{d \times d_k}, \qquad W_K \in \mathbb{R}^{d \times d_k}, \qquad W_V \in \mathbb{R}^{d \times d_v},

and computes:

 Q=XWQ,K=XWK,V=XWV,Y=Attn(Q,K,V). \boxed{\ Q = X W_Q, \qquad K = X W_K, \qquad V = X W_V, \qquad Y = \text{Attn}(Q, K, V). \ }

All three matrices act on the same XX but with different weights. The output Y∈RT×dvY \in \mathbb{R}^{T \times d_v} has one row per token — each row is what that token's query "found" by attending to all the keys.

Most modern Transformers use dk=dvd_k = d_v (a single dimension we will just call dhd_h — the "head dimension" — once we introduce multi-head in 6.4). In the single-head case dk=dv=dd_k = d_v = d, but multi-head splits dd 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 ii attends to token jj if and only if qi⊤kjq_i^\top k_j is large.

2.2 Why three matrices and not one

The most common confusion: if XX produces both QQ and KK via linear maps, why not just use XX for both — set Q=K=V=XQ = K = V = X 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 Q=KQ = K 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 qi⊤kjq_i^\top k_j is generally not equal to qj⊤kiq_j^\top k_i (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 Q=KQ = K, the score is symmetric, and the attention matrix is symmetric — a serious expressive limit.

(d) Capacity. Three independent projection matrices give the layer 3d⋅dk3 d \cdot d_k parameters. With a single shared matrix it would be d⋅dkd \cdot d_k. 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 Xsrc∈RTsrc×dX^\text{src} \in \mathbb{R}^{T_\text{src} \times d} (e.g. an English sentence) and produces a contextualised representation HsrcH^\text{src} via self-attention layers.
  • The decoder generates a target sequence Xtgt∈RTtgt×dX^\text{tgt} \in \mathbb{R}^{T_\text{tgt} \times d} (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:

 Q=XtgtWQ,K=HsrcWK,V=HsrcWV. \boxed{\ Q = X^\text{tgt} W_Q, \qquad K = H^\text{src} W_K, \qquad V = H^\text{src} W_V. \ }

Queries come from the target sequence; keys and values come from the source. The output has shape Ttgt×dvT_\text{tgt} \times d_v — 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 K,VK, V.


4. The full picture of one self-attention sub-layer

Putting §2 together, the self-attention sub-layer of a Transformer is:

Q=XWQ,K=XWK,V=XWV,A=softmax ⁣(QK⊤dk),Y=AV.\boxed{ \begin{aligned} Q &= X W_Q, \\ K &= X W_K, \\ V &= X W_V, \\ A &= \text{softmax}\!\left( \frac{Q K^\top}{\sqrt{d_k}} \right), \\ Y &= A V. \end{aligned} }

With X∈RT×dX \in \mathbb{R}^{T \times d}, WQ,WK∈Rd×dkW_Q, W_K \in \mathbb{R}^{d \times d_k}, WV∈Rd×dvW_V \in \mathbb{R}^{d \times d_v}, attention matrix A∈RT×TA \in \mathbb{R}^{T \times T}, output Y∈RT×dvY \in \mathbb{R}^{T \times d_v}.

In multi-head attention (6.4), the same operation is run hh times in parallel on hh different projections of XX, then concatenated. In 6.5 we add the causal mask. In 6.7 we modify QQ and KK 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 dd and head dim dk=dv=dhd_k = d_v = d_h:

#θattn-head=3⋅d⋅dh(for WQ,WK,WV).\#\theta_\text{attn-head} = 3 \cdot d \cdot d_h \quad \text{(for } W_Q, W_K, W_V\text{)}.

Plus the output projection WOW_O (introduced for multi-head in 6.4), which adds another h⋅dh⋅d=d2h \cdot d_h \cdot d = d^2 parameters for the whole sub-layer.

For hh heads with dh=d/hd_h = d/h — the standard configuration — the total over WQ,WK,WV,WOW_Q, W_K, W_V, W_O is

 #θself-attn=4d2. \boxed{\ \#\theta_\text{self-attn} = 4 d^2. \ }

A clean number to memorise: a self-attention sub-layer has 4d24 d^2 parameters (ignoring biases, which are sometimes omitted in modern Transformers anyway). For d=4096d = 4096, that's ∼67\sim 67M parameters per self-attention block. The FFN block (6.8) will be twice as expensive — 8d28 d^2.


6. What we keep going forward

Two things to lock in for the rest of the chapter:

  1. Self-attention is one specific wiring of the general attention formula. Q,K,VQ, K, V all come from the same input XX via three learned linear projections. The parameters of a self-attention layer are exactly WQ,WK,WVW_Q, W_K, W_V (plus WOW_O once we go multi-head).
  2. Cross-attention exists and is structurally identical, except K,VK, V 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.

Self-test

(a) Given X∈RT×dX \in \mathbb{R}^{T \times d} and projections WQ,WK,WV∈Rd×dhW_Q, W_K, W_V \in \mathbb{R}^{d \times d_h}, write the entries Qi,j,Ki,j,Vi,jQ_{i,j}, K_{i,j}, V_{i,j} in terms of XX and the weight entries. Verify the shapes.

(b) Show that if WQ=WKW_Q = W_K, the attention matrix A=softmax(QK⊤/dk)A = \text{softmax}(Q K^\top / \sqrt{d_k}) 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 d=1024d = 1024 and a single head has how many parameters in WQ,WK,WVW_Q, W_K, W_V alone? Same question for d=4096d = 4096.

(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. [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. [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. [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).

    ↩