Explain attention mechanisms beyond transformers — types and trade-offs
Written by the mlprep team · Updated
You mentioned transformers use self-attention. Walk me through the different types of attention — self vs cross attention, multi-head, and the scaling problem. What does "attention is O(n²)" actually mean in practice?
Scaled dot-product attention#
Attention(Q, K, V) = softmax(QK^T / √d_k) · V
Q (queries), K (keys), V (values) are linear projections of the input.
QK^Tcomputes similarity scores between every query and every key: an n×n matrix.√d_kscaling prevents the dot products from growing large enough to push softmax into regions of very small gradients. Without it: larger d_k → larger dot products → softmax saturates → vanishing gradients.- Softmax normalizes scores to attention weights summing to 1.
- Multiplying by V: each output position is a weighted sum of value vectors.
Self-attention vs cross-attention#
Self-attention: Q, K, V all come from the same sequence. Each token can attend to every other token in the same sequence. Used in encoder layers (BERT) and decoder self-attention.
Cross-attention: Q comes from one sequence (decoder), K and V come from another sequence (encoder output). Allows the decoder to "look at" the encoder's representation when generating each output token. Core of encoder-decoder architectures (original transformer, T5).
Multi-head attention#
Instead of one attention function with d_model dimensions, use h heads with d_k = d_model/h dimensions each:
MultiHead(Q,K,V) = Concat(head_1, ..., head_h) · W_O
head_i = Attention(Q·W_Q_i, K·W_K_i, V·W_V_i)
Each head learns to attend to different aspects of the input — positional relationships, semantic relationships, syntactic structure. Total compute is similar to single-head (smaller per-head dimensions), but representational power is much higher.
The O(n²) problem#
Computing QK^T requires n² dot products. Storing the attention matrix requires O(n²) memory. For n=4096 tokens and batch size 8, this is a 4096²×8 = ~1B float16 values ≈ 2 GB just for attention weights.
Real limits:
- GPT-3: 2048 token context. Full matrix still fits.
- Claude, Gemini: 100k–1M tokens. Naive attention is infeasible.
Solutions to quadratic attention#
Sparse attention: attend to only a subset of positions — local windows, strided patterns, or learned sparse patterns (BigBird, Longformer). O(n·k) where k is the window size.
Flash Attention: not algorithmically different from standard attention, but reorders computation to avoid materializing the full n×n matrix in HBM (GPU high-bandwidth memory). Uses tiling and online softmax. Same result, ~10× less memory, ~2-4× faster. Now the default for most transformer implementations.
Linear attention: approximates softmax attention with kernel methods. Rewrites attention as Q(K^T V) instead of (QK^T)V — the latter is O(n²d) but with the associativity swap becomes O(nd²). Approximate but sublinear in sequence length. Used in Mamba and other state-space model variants.
Causal masking (decoder)#
For autoregressive generation, each position can only attend to previous positions. Achieved by masking the upper triangle of the attention matrix with -∞ before softmax. This ensures the model can't "see the future" during training or inference.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Attention = softmax(QK^T/√d_k)V. Three matrices because you want separate "what to look for" (Q), "what I offer" (K), and "what I contribute" (V) projections. Multi-head learns multiple relationship types. Self-attention: Q,K,V from same sequence. Cross-attention: Q from decoder, K,V from encoder. O(n²) memory from storing QK^T — Flash Attention avoids this via tiling without changing the math. Linear attention reorders Q(K^TV) for sublinear complexity.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How does Flash Attention achieve the same result as standard attention while using O(n) memory instead of O(n²)?
- What is rotary position encoding (RoPE) and why did it replace learned or sinusoidal position encodings?
- When would you use an encoder-only model (BERT) vs a decoder-only model (GPT) vs an encoder-decoder (T5)?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions