Self-Attention Deep Dive: Q, K, V Roles and Transformer Design Trade-offs
Machine LearningModel answerLast updated
Explain how self-attention builds queries, keys and values, what the value vectors do, and why Transformers handle long-range context better than recurrent models.
Imagine you are asked to walk a teammate through how a Transformer works, concentrating on the self-attention layer.
Cover the following in your answer:
- Q, K and V construction. Starting from a matrix of input token embeddings, show how the query, key and value matrices are produced. State the shapes involved, and say what kind of information each of the three is meant to carry.
- The role of V. What do the value vectors represent, and how are they used once the attention weights are known?
- From scores to outputs. Describe at a high level how similarity scores turn into attention weights and then into the layer's output. Mention any scaling or masking you would apply and why.
- Comparison with recurrent models. Contrast Transformers with RNNs and LSTMs. Explain how Transformers deal with sequential dependency and with long-range context, and name the costs they introduce.
- Multi-head attention and positional encoding. Briefly outline both, and explain when each matters at inference time.
Aim for a structured answer that a colleague could follow, with formulas where they help and a few concrete numbers or trade-offs.
Hints
Hint 1
Write the single-head formula first: softmax(QKᵀ / √d_k + mask) V. Then attach shapes to every term and walk through it left to right.
Hint 2
Separate 'where to look' from 'what to retrieve'. Q and K decide the weights; V is the payload that is actually mixed into the output. Ask yourself why one projection for both jobs would be limiting.
Hint 3
For the RNN comparison, think in terms of path length between two tokens, parallelism during training, and memory at inference. For the inference part, think about the KV cache, grouped-query attention, and what happens past the trained context length.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
A Transformer is a stack of identical blocks. Each block has two sublayers, both wrapped in a residual connection and layer normalization (modern models usually normalize before each sublayer for stable training):
- Multi-head self-attention, where tokens exchange information.
- A position-wise feed-forward network, a two-layer MLP (typically about 4x expansion) applied to every token independently.
The data path is: tokens, then embeddings plus positional information, then N blocks, then an output head. Variants include encoder-only (bidirectional), decoder-only (causal) and encoder-decoder models with cross-attention.
Producing Q, K and V
Let X be the input with shape (n, d_model), one row per token. Three learned projections give:
- Q = X W_Q, with W_Q of shape (d_model, d_k)
- K = X W_K, with W_K of shape (d_model, d_k)
- V = X W_V, with W_V of shape (d_model, d_v)
In self-attention all three come from the same token representations, just through different learned linear maps. In cross-attention, Q comes from one sequence (the decoder) and K, V from another (the encoder output).
What each carries:
- Query: what this token is looking for. A verb might query for its subject.
- Key: how this token advertises itself so it can be matched. Keys are used only to compute scores.
- Value: the content this token contributes if it is selected.
Keys and values are separate on purpose. The features that make a token easy to find need not be the features worth passing on. A token might be matched by its syntactic role while contributing semantic content.
From scores to outputs
Attention(Q, K, V) = softmax(QKᵀ / √d_k + M) V
- Similarity. S = QKᵀ has shape (n, n). Entry S_ij = qᵢ · kⱼ says how well token j matches what token i wants.
- Scaling. If q and k components have roughly unit variance, their dot product has variance d_k. Dividing by √d_k keeps logits in a range where softmax is not saturated, which would otherwise starve gradients.
- Masking and softmax. Add a mask M with −∞ at forbidden positions (future tokens in causal decoding, padding). A row-wise softmax turns each row into a probability distribution over source positions.
- Aggregation. Output oᵢ = Σⱼ A_ij vⱼ.
What V represents
After the weights are computed, Q and K have finished their job: they decided where to look. V decides what is retrieved. Each output row is a convex combination of value vectors. Peaked weights approximately copy one token's value; diffuse weights blend many. The soft dictionary analogy fits: queries probe keys, and the stored payloads (values) come back in proportion to the match.
The head outputs are concatenated, projected by W_O, and added to the residual stream. So V is effectively how information from other positions gets written into each token's representation.
Transformers versus RNNs and LSTMs
| Aspect | RNN / LSTM | Transformer |
|---|---|---|
| Time dimension | Sequential: hₜ needs hₜ₋₁ | All positions in parallel during training |
| Path between tokens i and j | O(|i − j|) | O(1) |
| Long-range information | Squeezed through a fixed-size state; gradients vanish or explode (gating helps, does not remove) | Direct access to any earlier token |
| Compute per layer | O(n · d²) | O(n² · d) attention plus O(n · d²) FFN |
| Inference memory | O(1) state | KV cache grows O(n) |
| Order handling | Built in | None; needs positional information |
Sequential dependency. A Transformer processes the whole sequence in a few large matrix multiplies, which maps well to GPUs. An RNN needs n serial steps.
Long-range context. Any two tokens are one attention hop apart, so there is no fixed-size bottleneck and no long chain for gradients to decay through.
Costs.
- Attention is quadratic in sequence length. Mitigations: FlashAttention (exact, IO-aware kernels), sliding-window or sparse attention, linear-attention and state-space alternatives.
- Autoregressive generation is still one token at a time.
Multi-head attention
Rather than one attention with width d_model, use h heads with d_k = d_model / h:
- headᵢ = Attention(X W_Qⁱ, X W_Kⁱ, X W_Vⁱ)
- MHA(X) = Concat(head₁, …, head_h) W_O
A single softmax tends to average competing signals. Multiple heads can attend to different positions in different subspaces (local context, coreference, syntax) at about the same total compute as one wide head.
At inference the head layout drives memory. Decoding caches K and V for every past token, layer and head:
cache bytes ≈ 2 · layers · kv_heads · d_k · n · bytes_per_value
For a 32-layer model with 32 heads of size 128 in fp16, that is about 0.5 MB per token, so roughly 2 GB for a single 4k-token sequence. The cache, not the weights, often limits batch size and context length. Multi-query and grouped-query attention share K/V across heads, cutting the cache several-fold with small quality loss.
Positional encoding
Self-attention is permutation-equivariant: without position information, "dog bites man" and "man bites dog" yield the same set of token representations. Options:
- Sinusoidal (original): fixed sin/cos features added to embeddings.
- Learned absolute: one trained vector per position; cannot go past the trained maximum length.
- Relative / rotary (RoPE): rotates q and k by position-dependent angles so qᵢ · kⱼ depends on the offset.
At inference this matters mainly for context length: a model used beyond the lengths seen in training can degrade, which is why position-interpolation and scaling tricks for rotary embeddings exist. With a KV cache, each new token needs its correct position index, and cached keys must have been encoded with their own positions.
Common mistakes
- Saying V is "just another copy of the input" without explaining the separation of matching and content.
- Forgetting the √d_k scaling or being unable to justify it.
- Claiming Transformers are cheaper than RNNs; they are faster to train in parallel but costlier per layer in sequence length.
- Ignoring the causal mask when describing decoders.
- Describing positional encoding as optional, or forgetting that the KV cache dominates inference memory.