LLMS & TRANSFORMERS · INTERVIEW QUESTION
Explain the self-attention mechanism in detail. What are Q, K, V and why do we use scaled dot-product attention?
🟡 intermediate · Transformer Architecture
Hint: Think about the analogy of information retrieval and why we divide by √d_k.
Answer
Self-attention allows each token to attend to every other token in the sequence, computing contextual representations.
The Mechanism
- Q (Queries): "What am I looking for?"
- K (Keys): "What do I contain?"
- V (Values): "What information do I provide?"
All three are linear projections of input embeddings: , , .
Why Scale by ?
For large , under independent zero-mean, unit-variance query/key components, dot-product variance grows as and standard deviation as , pushing softmax into regions with vanishing gradients. Scaling keeps variance at ~1.
Multi-Head Attention
Runs parallel attention functions with different projections, allowing the model to attend to different aspects simultaneously. Outputs are concatenated and projected.
Complexity
This quadratic cost in is the key bottleneck for long sequences, motivating approaches like FlashAttention and sparse attention.
Related questions
- Explain positional encoding in Transformers. Compare sinusoidal, learned, RoPE, and ALiBi.
- Explain FlashAttention. How does it achieve sub-quadratic memory while maintaining exact attention?
- What are Large Language Models (LLMs) and how do they work?
- How does multi-head attention differ from single-head attention? Why use multiple heads?
- Explain the difference between LoRA, full fine-tuning, and prompt tuning. When would you use each?