Self-Attention
Self-attention is the step in a Transformer where every token looks at the other tokens and gathers the information it needs. Each token asks a query ("what am I looking for?"), every token offers a key ("what do I contain?"), and the matches decide how much of each token's value ("what I pass on") is mixed in. In "The trophy did not fit in the suitcase because it was too big", attention is how the word "it" can pick up information about "trophy".
Queries, Keys and Values
| Part | Description |
|---|---|
| Query (Q) | It is used to describe what the current token is looking for |
| Key (K) | It is used to describe what each token offers, to be matched against queries |
| Value (V) | The information a token passes on when it is attended to |
| Attention weights | softmax(Q · K / √d): how much each token attends to each other token; each row adds up to 1 |
| Causal mask | It is used to stop a token from looking at later tokens, so the model can't peek at the answer |
| Multi-head attention | Several attention calculations side by side, each free to look for a different kind of link |
Q, K and V are made by multiplying each token's vector by three learned weight matrices: the q_proj, k_proj and v_proj layers from "Inside a Transformer".
Example: Attention by Hand
This program computes causal self-attention for four tokens with NumPy. The embeddings and weight matrices are random, standing in for learned ones, so the pattern itself means nothing; the steps are what matter.
import numpy as np
np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(0)
tokens = ["the", "cat", "sat", "down"]
X = rng.normal(size=(4, 8)) # 4 tokens, each an 8-number embedding
# Three learned weight matrices turn each embedding into a query, a key and a value
W_q, W_k, W_v = (rng.normal(size=(8, 4)) for _ in range(3))
Q, K, V = X @ W_q, X @ W_k, X @ W_v # each (4 tokens, 4 numbers)
scores = Q @ K.T / np.sqrt(K.shape[1]) # how well each query matches each key
mask = np.triu(np.ones((4, 4)), k=1) == 1 # a token may not look at later tokens
scores[mask] = -np.inf
def softmax(s):
e = np.exp(s - s.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
weights = softmax(scores) # each row adds up to 1
print("Attention weights (row = token looking, column = token looked at):")
print(" " + "".join(f"{t:>7}" for t in tokens))
for t, row in zip(tokens, weights):
print(f"{t:>7} " + "".join(f"{w:7.2f}" for w in row))
output = weights @ V # each token: a weighted mix of the values
print("\nOutput shape:", output.shape)
print("Output for 'down':", output[3])
print("Check: 'down' row of weights adds up to", weights[3].sum())Attention weights (row = token looking, column = token looked at):
the cat sat down
the 1.00 0.00 0.00 0.00
cat 0.97 0.03 0.00 0.00
sat 0.92 0.00 0.08 0.00
down 0.01 0.25 0.08 0.66
Output shape: (4, 4)
Output for 'down': [ 0.15 -0.59 0.13 1.63]
Check: 'down' row of weights adds up to 1.0Explanation:
- Each token gets a query, a key and a value, here 4 numbers each, by multiplying its 8-number embedding by
W_q,W_kandW_v. Q @ K.Tcompares every query with every key: a big number means a good match. Dividing by√4 = 2keeps the numbers from growing too large as vectors get longer.- The causal mask sets the scores for later tokens to minus infinity, so after softmax they become exactly 0. That is the upper-right triangle of zeros: "the" can only look at itself, and "down" can look at all four.
- Softmax turns each row into weights that add up to 1. "down" puts 0.66 on itself and 0.25 on "cat".
- The output for each token is a weighted average of the values, so information moves from the tokens it attends to. The output has the same shape as the values: 4 tokens.
Example: Attention in a Real Model
SmolLM2-135M has 30 layers with 9 heads each, 270 attention heads in all. This program reads their weights for the trophy sentence.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M", attn_implementation="eager")
model.eval() # "eager" attention can return its weights
def attention(sentence):
ids = tokenizer(sentence, return_tensors="pt").input_ids
with torch.no_grad():
out = model(ids, output_attentions=True)
tokens = [tokenizer.decode(i) for i in ids[0]]
return tokens, torch.stack(out.attentions)[:, 0] # (30 layers, 9 heads, tokens, tokens)
tokens, A = attention("The trophy did not fit in the suitcase because it was too big.")
print("Shape: layers, heads, tokens, tokens =", tuple(A.shape))
it = tokens.index(" it")
def show(title, weights):
top = weights.topk(3)
print(title, ", ".join(f"{tokens[j]!r} {w:.2f}" for w, j in zip(top.values, top.indices)))
show("Layer 14, head 9, 'it' looks at:", A[13, 8, it])
show("Layer 22, head 7, 'it' looks at:", A[21, 6, it])
show("Average of all 270 heads: ", A[:, :, it].mean(dim=(0, 1)))
# The model reads left to right, so the word after "it" cannot change where "it" looks
_, B = attention("The trophy did not fit in the suitcase because it was too small.")
print("\nChange 'big' to 'small': largest change in what 'it' looks at =", (A[:, :, it] - B[:, :, it]).abs().max().item())Shape: layers, heads, tokens, tokens = (30, 9, 15, 15)
Layer 14, head 9, 'it' looks at: ' trophy' 0.54, 'The' 0.12, ' did' 0.09
Layer 22, head 7, 'it' looks at: 'case' 0.30, 'The' 0.25, ' suit' 0.14
Average of all 270 heads: 'The' 0.45, ' the' 0.16, ' because' 0.13
Change 'big' to 'small': largest change in what 'it' looks at = 0.0Explanation:
attn_implementation="eager"uses the plain attention code, which can return the weights; the faster default does not. The weights have shape(30, 9, 15, 15): for every layer and head, how much each of the 15 tokens attends to each other token.- Layer 14, head 9 (index
[13, 8], since Python counts from 0) sends 54% of the attention of "it" to "trophy": this head links the pronoun to a noun earlier in the sentence. Layer 22, head 7 looks at "case" in "suitcase" instead. Different heads find different links, which is the point of having many. - Averaged over all 270 heads, 45% of the attention goes to the first token, "The". Many heads use the first token as a place to put attention when they have nothing useful to look at; researchers call this an attention sink.
- Changing "big" to "small" changes nothing (0.0) in what "it" attends to. The model reads left to right, so when it processes "it", the words after it don't exist yet. Deciding whether "it" means the trophy or the suitcase can only happen at later tokens, such as "big", which can look back at both.
Reading individual heads gives hints, not a full explanation: one head's pattern is only one of 270 that work together.
Multiple Heads and Positions
| Idea | How SmolLM2-135M does it |
|---|---|
| Multi-head attention | 9 heads of 64 numbers each (9 × 64 = 576), computed in parallel and joined back together by o_proj |
| Grouped-query attention | 9 query heads share 3 sets of keys and values, which is why k_proj and v_proj output 192 numbers (3 × 64); this saves memory |
| Position information | Attention by itself ignores word order, so rotary position embeddings (RoPE) rotate each query and key by an angle that depends on its position |
Common Mistakes
Thinking attention weights explain the answer. They show where information moved in one head, not why the model answered as it did.
Forgetting the scaling by √d. Without it, large dot products make softmax put almost all the weight on one token, and training becomes unstable.
Forgetting the causal mask when building a language model. Without it, the model sees the next token during training and learns nothing useful.
Expecting attention alone to know word order. Position information has to be added, as with RoPE.
Interview Corner
Explain queries, keys and values.
Each token's vector is projected into a query, a key and a value. The query is compared with every key to get attention weights, and the output is the weighted sum of the values. In formula form: softmax(QKᵀ / √d) V.
Why use multiple attention heads?
Each head can attend to a different kind of relationship, such as the previous word, a matching noun or punctuation, at the same time. The heads' outputs are joined and projected back to the model's width.
Practice
Exercise: remove the mask. Comment out scores[mask] = -np.inf in the first program. What happens to the upper triangle of the weights, and why would that be a problem when training a model to predict the next token?
Check your understanding:
- Why is each attention row guaranteed to add up to 1?
- What does the causal mask do, and why does a language model need it?
- Why did changing "big" to "small" not change where "it" looks?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Queries, keys, values | Q, K, V = X @ W_q, X @ W_k, X @ W_v |
| Scores | Q @ K.T / np.sqrt(d) |
| Causal mask | np.triu(np.ones((n, n)), k=1) == 1 |
| Weights and output | softmax(scores) @ V |
| Real attention weights | from_pretrained(name, attn_implementation="eager"), then model(ids, output_attentions=True) |
| In PyTorch | torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True) |
Was this tutorial helpful?