Self-attention is the operation that lets every token in a sequence look at every other token and decide, on the fly, which ones matter for its own representation. Instead of pushing words through a fixed left-to-right recurrence, a transformer computes, for each token, a weighted blend of information drawn from the whole sequence, and it learns those weights from data. This lesson unpacks the single equation behind that behavior, scaled dot-product attention, then shows how running several of these operations in parallel, multi-head attention, lets one layer capture many kinds of relationships at once.
The mechanism: scaled dot-product attention
Each input token is first projected into three vectors by learned weight matrices: a queryq (what this token is looking for), a keyk (what this token offers), and a valuev (the information it passes on). Stack them into matrices Q, , and the entire operation is:
Ask the tutor
Ask about this lesson, or about anything in AI. Answers cite the lessons they draw on.
Finished this lesson?
Mark it complete to earn XP, keep your streak, and schedule a review.
K
V
Attention(Q,K,V)=softmax(dkQK⊤)V
Read it right to left. The product QK⊤ forms a score matrix whose entry (i,j) is the dot product of query i with key j, a raw measure of compatibility. Softmax, applied across each row, turns those scores into non-negative weights that sum to one, so each token ends up with a probability distribution over the sequence. Multiplying that weight matrix by V produces, for every token, a weighted average of the value vectors. Because softmax and matrix multiplication are both differentiable, the whole lookup is trainable end to end by gradient descent.
Why divide by dk?
If the components of q and k are independent with zero mean and unit variance, their dot product q⋅k=∑i=1dkqiki has variance dk, so its typical magnitude grows like dk. Feed large scores into softmax and it saturates: one weight approaches 1, the rest approach 0, and the gradient through softmax nearly vanishes. Dividing by dk rescales the scores back to unit variance, keeping softmax in a responsive, well-conditioned regime so learning stays stable.
1ProjectMultiply each token embedding by learned matrices W_Q, W_K, W_V to produce a query, key, and value vector for that token.
2ScoreDot every query with every key (the matrix product QKᵀ). Entry (i, j) measures how compatible token i's query is with token j's key.
3ScaleDivide all scores by sqrt(d_k) so their variance stays near 1 and softmax does not saturate.
4NormalizeApply softmax along each row, turning scores into non-negative weights that sum to 1.
5AggregateMultiply the weight matrix by V so each token's output is a weighted average of value vectors.
Attention is a soft dictionary lookup
A hard lookup matches a query to one key and returns its single value. Softmax
replaces that argmax with a smooth, differentiable average over all values, so
the model can be trained with gradients while, in the limit of very sharp
weights, still behaving like a lookup.
Intuition
For a curious beginner
Picture each token asking a question, while every other token holds up a labeled answer card. The token compares its question against each label, trusts the close matches most, and takes a blended answer weighted by those matches. Nothing is hard-selected, each token softly reads a little from everyone, and more from the relevant ones.
Engineering
How it is actually used
Project embeddings to Q, K, V with three weight matrices. Score with QK⊤, divide by dk, softmax each row, then multiply by V. Run h of these in parallel on sliced projections, concatenate the outputs, and mix them with WO. In code it is a handful of matmuls plus one softmax.
Mathematical
The underlying mechanism
Attention(Q,K,V)=softmax(dk. The term normalizes the dot product's variance from back to , keeping softmax off its saturated tails where the Jacobian collapses. Softmax places each row on the probability simplex, so the output is a convex combination of value vectors.
For a curious beginner
Picture each token asking a question, while every other token holds up a labeled answer card. The token compares its question against each label, trusts the close matches most, and takes a blended answer weighted by those matches. Nothing is hard-selected, each token softly reads a little from everyone, and more from the relevant ones.
How it is actually used
Project embeddings to Q, K, V with three weight matrices. Score with QK⊤, divide by dk, softmax each row, then multiply by V. Run h of these in parallel on sliced projections, concatenate the outputs, and mix them with WO. In code it is a handful of matmuls plus one softmax.
The underlying mechanism
Attention(Q,K,V)=softmax(dk. The term normalizes the dot product's variance from back to , keeping softmax off its saturated tails where the Jacobian collapses. Softmax places each row on the probability simplex, so the output is a convex combination of value vectors.
Worked example: two tokens by hand
Take two tokens with dk=2. Suppose the projections give the vectors below, and we compute the output for token 1, whose query is q1=[1,1], attending over both tokens.
vector
token 1
token 2
key k
[1,1]
[1,−1]
value v
[1,0]
[0,1]
Scores.q1⋅k1=(1)(1)+(1)(1)=2, and q1⋅k2=(1)(1)+(1)(−1)=.
Scale. Divide by dk=2≈1.414, giving scaled scores ≈[1.414,0].
Softmax.e1.414≈4.11 and e0=1, so the sum is ≈5.11 and the weights are ≈[0.80,0.20].
Token 1 pulls about 80% of its new representation from token 1's value and 20% from token 2's, a genuine, differentiable blend rather than a hard pick.
Multi-head attention
A single attention operation forces every relationship, syntax, coreference, positional cues, through one set of Q/K/V projections. Multi-head attention instead runs h attention operations in parallel, each with its own learned projections into a lower-dimensional subspace (typically dk=dmodel/h). Each head can specialize: one may track subject–verb agreement, another may attend to the previous token, another to long-range topic words. The heads' outputs are concatenated and passed through a final linear projection WO:
Because each head works in a subspace with dk<dmodel, the total cost is comparable to one full-width attention, yet the layer gains the ability to attend to several patterns at once.
Common mistakes
Forgetting the scale. Dropping 1/dk lets scores grow with dimension, saturating softmax and stalling gradients early in training.
Softmax over the wrong axis. Normalize across keys (each query's row), not across queries, otherwise the weights no longer answer "where should this token look?"
Confusing more heads with bigger heads. Adding heads splits dmodel into more, smaller subspaces; it does not enlarge each head. Total parameters stay roughly fixed.
Treating attention weights as explanations. High weight shows where information flowed, not why the model produced an output, read attention maps as diagnostics, not ground-truth reasoning.
Further reading
Attention Is All You Need, Vaswani et al. (2017), which introduced scaled dot-product and multi-head attention.