Self-attention
Each token builds a query, key and value; it scores its query against every earlier token's key, softmaxes the scores and takes a weighted sum of values. Cost grows O(n²) with context length.
Analogy: A meeting: each person (token) asks a question, everyone shows a name tag saying what they know, and you listen mostly to people whose tag matches your question, but only to those who spoke before you.
How it works
- Scores are scaled by √d before the softmax so large dot products don't saturate it.
- A causal mask hides future positions, so training predicts every position in parallel without cheating.
- Multi-head attention runs several smaller attentions in parallel, each tracking a different relation.
- Generation keeps past keys and values in the KV cache, which grows linearly and dominates memory at long context.
- GQA groups query heads to share K/V heads; Llama 3 8B's 8 K/V heads cut the cache 4×.
Check yourself
Answer to mark it learned; your answers aren't scored.
You train a small language model from scratch with hand-written attention. Training loss drops suspiciously fast to near zero, but at inference the model produces garbage. Most likely bug?
Go deeper
Full explanation
Self-attention is how a token gathers information from the other tokens in its sequence. Each token vector x is projected three ways:
- Query
q = x·W_Q: what am I looking for? - Key
k = x·W_K: what do I contain? - Value
v = x·W_V: what do I pass on if selected?
For all tokens at once: Attention(Q,K,V) = softmax(QKᵀ/√d)·V. Each query is dotted with every key, scaled by √d (head dimension) so large dot products don't saturate the softmax, turned into weights that sum to 1, and used to average the values.
A causal mask sets scores for future positions to −∞ before the softmax, so token i sees only tokens ≤ i. That lets training predict every position in parallel without cheating.
Multi-head attention runs h smaller attentions in parallel (e.g., 32 heads × 128 dims = 4,096), each tracking a different relation, then concatenates and projects them.
Cost: the score matrix is n×n, so compute grows O(n²) with sequence length. During generation, past keys and values live in the KV cache, which grows linearly and dominates memory at long context. MQA shares one K/V head across all query heads; GQA shares one per group (Llama 3 8B: 8 K/V heads for 32 query heads), cutting the cache 4× with little quality loss.
Code Scaled dot-product attention with a causal mask in NumPy
import numpy as np
def softmax(x, axis=-1):
x = x - x.max(axis=axis, keepdims=True) # subtract max for numerical stability
e = np.exp(x)
return e / e.sum(axis=axis, keepdims=True)
def causal_attention(Q, K, V):
"""Q, K, V: (seq_len, d_head). Returns output (seq_len, d_head) and weights."""
n, d = Q.shape
scores = Q @ K.T / np.sqrt(d) # (n, n): every query vs every key -> O(n^2)
future = np.triu(np.ones((n, n), dtype=bool), k=1) # True above the diagonal
scores = np.where(future, -np.inf, scores) # mask BEFORE softmax so rows still sum to 1
weights = softmax(scores, axis=-1)
return weights @ V, weights
rng = np.random.default_rng(0)
n, d_model, d_head = 5, 16, 8
X = rng.normal(size=(n, d_model)) # 5 token vectors
W_q, W_k, W_v = (rng.normal(size=(d_model, d_head)) for _ in range(3))
out, w = causal_attention(X @ W_q, X @ W_k, X @ W_v)
print(out.shape) # (5, 8)
print(np.round(w, 2)) # lower-triangular: token 0 attends only to itself
# Multi-head = run h of these on separate projections, concat, multiply by W_o.
# In production use torch.nn.functional.scaled_dot_product_attention (fused kernels).Real example
You serve Llama 3 8B in bf16 with 8k-token conversations. KV cache per token = 2 (K and V) × 32 layers × 8 KV heads × 128 dims × 2 bytes = 128 KiB, so one 8k sequence holds 1 GiB. On an 80 GB GPU with ~16 GB of weights, that leaves room for at most ~60 concurrent sequences, fewer after runtime overhead. With full multi-head attention (32 KV heads) the cache would be 4 GiB per sequence and you'd fit ~15. GQA is a 4× concurrency win decided at model-design time, so check the KV-head count when you choose a model.
Trade-offs +3 · −3
+ You gain
- Direct path between any two tokens, regardless of distance.
- Pure matrix multiplies: highly parallel on GPUs during training and prefill.
- Content-based routing: what each token reads is decided per input, not fixed by position.
− You pay
- O(n²) compute and, naively, O(n²) memory for the score matrix.
- KV cache grows linearly with context × batch and caps concurrency.
- Each new token reads the whole KV cache, so long contexts slow down decoding.
Use it when
Know it cold to reason about long-context cost, KV cache sizing, GQA/MQA when picking a model, and kernels such as FlashAttention or paged attention in your serving stack.
Avoid it when
Don't hand-roll it for production: use fused kernels (PyTorch scaled_dot_product_attention, FlashAttention). Hand-written attention is for learning and research.
Numbers to know 5
- Score matrix per head per layer: n² entries; 32k tokens ≈ 1.07B entries.
- Doubling context ≈ 4× attention FLOPs but only 2× KV cache.
- KV cache per token = 2 × layers × KV heads × head_dim × bytes; Llama 3 8B in bf16 ≈ 128 KiB.
- GQA in Llama 3 8B: 32 query heads share 8 K/V heads, a 4× smaller cache than MHA.
- Typical head dimension: 64–128.
Common pitfalls 4
- Believing FlashAttention makes attention linear: it removes O(n²) memory and IO, but FLOPs stay quadratic.
- Masking after the softmax (zeroing weights) instead of −∞ before it: rows no longer sum to 1.
- Forgetting the causal mask in training code: loss looks great because the model reads the answer, and inference is garbage.
- Reading attention weights as an explanation of the decision; they are one signal among many layers.
Interview questions 2
Answer out loud first, then reveal.
Why is attention O(n²), and what do we do about it in production?Show answer
Every query is scored against every key, so one head in one layer builds an n×n matrix: 32k tokens is ~1B scores. FlashAttention fixes the memory side by computing in tiles and never materializing that matrix, but the FLOPs stay quadratic. Sliding-window or sparse attention and state-space hybrids cut the FLOPs at some quality cost. In serving, though, the bigger pain at long context is usually the KV cache, which grows linearly and limits batch size, so I look first at GQA models, paged attention and KV-cache quantization.
MHA vs MQA vs GQA: what's the trade-off?Show answer
It's about how many key/value heads you keep. MHA has one K/V head per query head: best quality, largest cache. MQA shares a single K/V head across all query heads: smallest cache and fastest decode, but measurable quality loss. GQA sits in between; Llama 3 8B uses 8 K/V heads for 32 query heads, a 4× smaller cache at near-MHA quality. The GQA paper also showed an existing MHA checkpoint can be converted by uptraining with ~5% of the original pre-training compute. For a serving-heavy product, I prefer a GQA model.