TRANSFORMERS - PART 2: SELF-ATTENTION, KV CACHE, MULTI-HEAD
Self-attention: the intuition
Embeddings give each word meaning. Positional embeddings give order. But how does the sentence talk to itself? -> Self-attention.
- Every token looks at every other token and assigns an importance score.
- Not sequential. All tokens talk at once. (Global information flow)
- Low score for irrelevant words, high score for useful ones (nouns, pronouns, adjectives). (Filtering noise)
- Weights change with the sentence. (Dynamic weighting)
Example
"The bank was closed because it was a holiday." The token "it" gives high attention to "bank" and almost none to "closed" or "holiday".
Transformer block = self-attention -> feed forward, repeated in N blocks. Feed forward is the simple neural network already learned.
Positional embeddings (sinusoidal) are not learned. Sine and cosine are fixed functions, so nothing to train.
Query, Key, Value
Input embedding = token embedding + positional embedding. Before attention, each token gets three vectors made from it.
| Vector | Meaning | Role |
|---|---|---|
| Query (Q) | What am I looking for? | The question it asks others |
| Key (K) | What do I contain? | What others match against |
| Value (V) | What information do I offer? | What is handed over if matched |
- W_Q, W_K, W_V start random and are adjusted during training.
- Every token has its own Q, K, V. N tokens -> N sets.
- Names come from databases (query, key, value). The paper came from Google.
Database lookup is a hard lookup: exact match only. Attention is a soft lookup: partial or fuzzy matches, each with a score.
Layer normalization before the projections keeps values from getting too big or too small. It only stabilises the maths.
The attention formula, step by step
- Q K^T - similarity of every query with every key
- Q and K are both 3x4. Cannot multiply: inner sizes 4 and 3 do not match.
- Transpose K (swap rows and columns) -> 4x3.
- 3x4 times 4x3 = 3x3. Always n x n, a square matrix.
- Dot product - measures how aligned two vectors are. Same direction = high, opposite = low.
- High score = this key may answer my query.
- Divide by sqrt(d_k) - d_k is the key dimension. Scaling keeps numbers and gradients stable in backprop. Otherwise values blow up or die off. Found by experiment. Relative order of scores stays the same.
- Softmax - turns raw scores into a probability distribution between 0 and 1 that sums to 1.
Example
Input 2, 1, 0.1 -> 0.66, 0.24, 0.10. Sum = 1. Now it reads as 66%, 24%, 10%.
- Multiply by V (weighted sum) - each token collects the values of others in proportion to its attention weights. Result: a context-rich representation.
Attention weights can be drawn as a heat map (n x n). Bright = high attention, dark = low.
Example
"The animal didn't cross the street because it was too tired." The query of "it" matches the key of "animal", so "it" absorbs animal's meaning.
Self-attention in NumPy
import numpy as np
def softmax(x):
e = np.exp(x - x.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
X = np.random.randn(3, 8) # 3 tokens, 8 dims
Wq = np.random.randn(8, 4)
Wk = np.random.randn(8, 4)
Wv = np.random.randn(8, 4)
Q, K, V = X @ Wq, X @ Wk, X @ Wv # each 3x4
def self_attention(Q, K, V):
dk = K.shape[-1]
scores = Q @ K.T / np.sqrt(dk) # 3x3
w = softmax(scores)
return w @ V, w- @ is matrix multiplication, .T is transpose.
- Input 3x8, weights 8x4, Q/K/V 3x4, attention matrix 3x3.
- d_k = 4, so sqrt = 2.
Generation flow and KV cache
Generation is autoregressive: one token out, appended to input, run again. Each step runs attention over the whole sequence.
Is everything recomputed at every step? For "the cat sat", when generating the next token, the keys and values of "the", "cat", "sat" are identical to the previous step.
Only the new token needs a new query (its own new question). Previous keys and values are stored and reused -> KV cache.
- New token: compute its Q, K, V. Q attends to all cached keys.
- Weighted sum uses cached values.
- Tokens only look at the past, never the future.
- Saves repeated computation: speed and latency optimization. It also avoids recomputation, not information compression.
Why the first token is slow -> the cache is empty, so K and V for the whole prompt must be built. Later tokens reuse it.
| Metric | Meaning |
|---|---|
| Time to first token | How fast the prompt is processed and the cache filled |
| Tokens per second | Average speed of each later token |
Time to first token and tokens per second are different metrics. Mixing them up is a red flag in interviews.
Why long context is hard
- KV cache grows linearly with context length.
- Longer prompt -> slower first token.
- 1M context needs huge memory. 10M would exceed current servers and GPUs.
- Progress comes from faster GPU maths and memory optimizations. (Infra problem)
Multi-head attention
One head explores only one kind of relationship. Several heads look at different things at once, giving richer context.
- Each head has its own Q, K, V.
- What each head learns is not controlled. It emerges in training.
- Experiments showed more heads beat a single head.
- Head count is empirical: more heads = smaller dimension per head, so each explores a narrower space. Different companies pick different counts.
8 heads x 96 = 768 after concatenating the outputs, back to the model dimension. A model has N stacked transformer blocks, each with multi-head self-attention.
Glossary
- Self-attention
- Each token scores every other token and gathers information from the relevant ones.
- Query
- Vector saying what a token is looking for.
- Key
- Vector saying what a token contains, matched against queries.
- Value
- Vector holding the information a token offers when matched.
- Dot product
- Operation that measures how aligned two vectors are.
- Softmax
- Function turning scores into probabilities between 0 and 1 that sum to 1.
- KV cache
- Stored keys and values of earlier tokens reused during generation.
- Time to first token
- Delay before the first output token, dominated by building the cache.
- Multi-head attention
- Several attention heads run in parallel, each on a smaller dimension.
- Transpose
- Matrix with rows and columns swapped.