Self-Attention, Explained
After reading this you will be able to read an attention weight matrix, reproduce a scaled dot-product attention score by hand, and tell which patterns come from the geometry of the tokens rather than from anything the model has learned.
What self-attention does
Self-attention is the operation that lets each token in a sequence pull information from every other token. Give it the sentence the cat sat and it produces, for each of the three tokens, a set of weights that say how much that token should look at each token including itself. Those weights always sum to 1 across a row.
Here is the hook. Take the token sat. Attention does not know grammar. It computes a similarity score between sat and every token, scales it, runs a softmax, and uses the resulting weights to average the value vectors. If the weight on cat comes out to 0.62 and the weight on the comes out to 0.11, that means the new representation of sat is mostly built from the value vector of cat. The arc diagram in the tool draws that as a thick line to cat and a thin line to the.
The tool builds the vectors deterministically from token identity and position, then projects them through random but seeded matrices. So the patterns you see are real arithmetic, not learned meaning. That distinction runs through this whole article.
When to reach for this idea, and when not
Self-attention earns its place when every element of a sequence might depend on every other element, at any distance, and you want that dependency computed in one step rather than passed along a chain. A recurrent network reading the cat that the dog chased sat has to carry information about cat across five intermediate steps to reach sat. Attention connects them directly with one weight.
It is a poor fit when the input has no meaningful pairwise relationships, or when the sequence is so long that the cost hurts. Attention compares every token with every other token, so cost grows with the square of the length. A sequence of 1000 tokens needs 1000 × 1000 = 1,000,000 scores per head. Double the length to 2000 and you need 4,000,000, four times as many. For short sequences that is cheap. For a whole book it is the central engineering problem.
Attention has no built-in sense of order. The scores depend only on the vectors, not on where the tokens sit. Order enters through the positional encoding added to each embedding. Remove it and the cat sat and sat cat the would produce the same set of weights up to a relabeling.
The formula and why each piece is there
Scaled dot-product attention takes three matrices, all derived from the input. Query Q, key K, and value V. Each row is one token.
Read it right to left. Q K^\top is the matrix of raw scores: entry (i, j) is the dot product of query i with key j, a measure of how well token i matches token j. Dividing by \sqrt{d}, where d is the dimension of the query and key vectors, keeps those dot products from growing as the dimension grows. The softmax turns each row of scores into weights that are positive and sum to 1. Multiplying by V replaces each token with the weighted average of all value vectors.
Why \sqrt{d} and not d? If each component of the query and key is roughly independent with variance 1, a dot product of d terms has variance about d, so its typical size is about \sqrt{d}. Dividing by \sqrt{d} pulls the scores back to a typical size near 1. Without it, at d = 64 the scores would sit around \pm 8, the softmax would saturate, and almost all weight would collapse onto a single token.
The softmax, worked by hand
The softmax is where scores become weights, so it pays to compute one. Suppose token sat produces three raw scores against the, cat, sat: 0.5, 2.0, 1.0. The softmax of a vector z is:
Turning three scores into three weights
- Exponentiate each score: e^{0.5} \approx 1.649, e^{2.0} \approx 7.389, e^{1.0} \approx 2.718.
- Sum them:
1.649 + 7.389 + 2.718 = 11.756. - Divide each by the sum:
1.649 / 11.756 = 0.1403,7.389 / 11.756 = 0.6285,2.718 / 11.756 = 0.2312. - Check:
0.1403 + 0.6285 + 0.2312 = 1.000.
So sat attends to cat with weight 0.6285, to sat with 0.2312, to the with 0.1403. The gap between the raw scores 2.0 and 1.0 is one unit, but the weights differ by a factor of 0.6285 / 0.2312 = 2.72, which is exactly e^{1.0}. That factor is the whole story of softmax: equal score differences give equal weight ratios.
How the scaling slider reshapes attention
The scaling slider in the tool multiplies the scores before the softmax, which is the same as dividing the effective \sqrt{d}. Call the multiplier \beta. Large \beta sharpens the weights toward one token. Small \beta softens them toward a flat average.
Take the same scores 0.5, 2.0, 1.0. At \beta = 3 the scores become 1.5, 6.0, 3.0, and the weights come out to about 0.010, 0.945, 0.045: almost all weight on cat. At \beta = 0.25 the scores become 0.125, 0.5, 0.25 and the weights flatten to about 0.303, 0.440, 0.344: close to the uniform 0.333 each. The slider does not change which token scores highest; it changes how decisively the winner takes the weight.
cat, but higher beta concentrates the weight while lower beta spreads it toward uniform.Reading the arc diagram and the heatmap
The heatmap is the full weight matrix. Rows are the token doing the attending, columns are the token being attended to. Row i sums to 1. A bright cell at (sat, cat) means sat puts most of its weight on cat. Read across a row to see where one token looks. Read down a column to see who looks at that token.
The arc diagram shows one row at a time. Click a token and the arcs leaving it have thickness proportional to that row of the heatmap. A single thick arc means the softmax concentrated, which happens with high scaling or a strong single match. Many thin arcs of similar width mean the row is close to uniform.
Switching heads changes the matrices Q, K, V. With 4 heads the embedding of dimension d is split into four blocks of d/4, and each block computes its own pattern. That is why one head can spread attention evenly while another concentrates on the token next door. The tool seeds each head separately, so the differences you see are geometric accidents of the random projections, not learned specialties.
Common mistakes when reading attention
A high attention weight is not an explanation. It tells you which value vectors were averaged, not why the model produced its output. Two heads can disagree, later layers can overwrite the result, and the value vector itself carries information the weight does not show. Treat attention as a routing map, not a reason.
Three more traps. First, do not read the heatmap by column when you mean by row: (sat, cat) and (cat, sat) are different cells and generally different numbers, because attention is not symmetric. Second, do not forget the diagonal. A token attending mostly to itself, weight 0.5 or higher on (sat, sat), is common and simply means the token keeps its own information. Third, do not read meaning into these particular arcs. Because the projections are seeded random, a thick arc from sat to the reflects vector geometry, not any relationship a trained model would find.
The causal mask
Turn on the causal mask and the tool sets every score above the diagonal to -\infty before the softmax. Since e^{-\infty} = 0, those weights become exactly 0. Token i can then attend only to tokens 1 through i.
Work it for the cat sat. Row the can see only the, so its weight is 1.000 on itself. Row cat can see the and cat: if the unmasked scores were 0.5 and 2.0, the two weights are 1.649 / (1.649 + 7.389) = 0.1825 and 0.8175. Row sat can see all three, giving back the earlier 0.1403, 0.6285, 0.2312. The masked matrix is lower triangular, and every row still sums to 1. This is exactly what lets a decoder generate text left to right: at generation time token i does not yet know token i + 1, so it must not attend to it during training either.
| attends to → | the | cat | sat |
|---|---|---|---|
| the | 1.000 | 0 | 0 |
| cat | 0.1825 | 0.8175 | 0 |
| sat | 0.1403 | 0.6285 | 0.2312 |
Related tools on this site
Self-attention is one layer inside a larger network. To see the pieces around it, start with the Neural Network Playground for how a small network learns a boundary, then step through the arithmetic of learning in Backpropagation Step-by-Step. The vectors attention consumes are embeddings, which you can train yourself in the Word Embedding Trainer. For the sequence model attention replaced, the Character RNN Text Generator reads text one step at a time. And the softmax sharpening you saw here connects to activation shapes in the Activation Function Explorer.
Frequently asked questions
Why do the attention patterns look random in this tool?
Because the query, key, and value matrices are seeded random rather than learned. The patterns reflect the geometry of the pseudo-embeddings and positional encodings, which is real arithmetic, but they carry no linguistic meaning. A trained Transformer learns these matrices from data over many steps, and only then do interpretable patterns emerge.
What does dividing by the square root of d actually prevent?
It keeps the softmax out of its saturated region. A dot product of d unit-variance terms has typical size \sqrt{d}, so at d = 64 scores would run near \pm 8 and the softmax would put almost all weight on one token. Dividing by \sqrt{64} = 8 brings the typical score back to about 1.
Do the rows or the columns of the heatmap sum to 1?
The rows. Each row is one token's softmax over all tokens, so it sums to 1. Columns can sum to anything, since a popular token can receive weight from many rows.
What is the difference between one head and four heads?
One head runs a single attention pattern over the full vector. Four heads split the vector into four smaller blocks and run four independent patterns, which a real model then concatenates. More heads let different subspaces route information differently in the same layer.
Can I use these attention weights to explain a model's prediction?
Not reliably. Attention weights show which value vectors were averaged, not why a prediction came out. Later layers can override the result and the value content itself is not visible in the weight. Read attention as routing, not reasoning.