Transformers and Self-Attention
Recurrence forced language models to read one word at a time and to squeeze every dependency through a chain of hidden states. Self-attention removes the recurrence: at every layer each position compares itself to every other and reads a weighted mixture of them, in a single parallel step.
╌╌╌╌
The recurrent network reads a sentence one word at a time, carrying a hidden state forward. That design has two costs that gating only mitigates. The first is information loss: a dependency between two distant words must be copied through every hidden state in between, degrading at each step; even the LSTM's cell only slows the decay. The second is serial computation: the hidden state at position needs the hidden state at , so the sequence cannot be processed in parallel — training time grows with sentence length.1
Self-attention discards the recurrence. Instead of passing information down a chain, it lets every position look directly at every other position and pull in a weighted mixture of them, in one step. A dependency between word 1 and word 50 is a single comparison rather than a chain of 50 copies. And because the output at each position is computed independently of the others, the whole sequence is processed at once, so the computation parallelizes across a GPU. The transformer is a stack of layers built almost entirely from this one operation.
The two costs are really one geometric fact: in a recurrent network the number of steps a signal travels between two positions is their distance in the sequence, so a dependency between token and token passes through hidden states, and the training gradient that would tie them passes through multiplications. In self-attention that path length is for every pair — token and token are one dot product apart, no matter the gap. Shorter paths mean less information decay on the forward pass and less gradient decay on the backward pass, and they are why attention learns long-range structure that recurrence struggles with.
Attention as a soft lookup
Attention already appeared, in miniature, at the end of the recurrent chapter: the decoder of an encoder-decoder model got to look back at all the encoder's hidden states, weighting each by relevance. Self-attention applies that same idea inside a single sequence — a word attends to the other words of its own sentence rather than to a separate source text.2
Start with the simplest version. Each input is a vector , and we want an output that summarizes how relates to the words around it. Relatedness is measured by a dot product: is large when the two vectors point the same way. Compute one such score for every earlier position, normalize the scores with a softmax into weights that sum to one, and read off the weighted average of the inputs:
This is a soft dictionary lookup: the query is compared against a set of entries, the comparison scores become a probability distribution, and the answer is the distribution-weighted blend of the entries. Nothing is recurrent, and every is a separate sum, so all of them can be computed simultaneously.3
Queries, keys, and values
Using the same vector for all three jobs — the thing doing the comparing, the thing being compared against, and the thing being summed — is wasteful, because those are three genuinely different roles. Transformers give each role its own learned projection of the input.4
The score is now a dot product between the current word's query and each earlier word's key, and the output is the weighted sum of the corresponding values rather than of the raw inputs:
The three matrices are the only learned parameters of the attention layer; they are shared across all positions and trained end-to-end with the rest of the network. Query and key vectors have dimension , values have dimension , and the model as a whole works in dimension ; a single-head layer takes , though the multi-head version below will pull them apart.4
Why the scaling
A dot product of two -dimensional vectors sums products. If the components are roughly independent with unit variance, the dot product has variance proportional to , so as the dimension grows the scores spread out into large positive and negative values. Feed large values into a softmax and it saturates: almost all the probability collapses onto the single largest score, and the gradient with respect to the others goes to zero, which stalls learning.5
The fix is to divide the score by before the softmax, rescaling the variance back to a constant regardless of dimension. This is scaled dot-product attention:
Intuitively: a softmax turns a gap between two scores into a gap between two probabilities, but the size of the probability gap depends on the scale of the scores. Left unscaled, that scale grows with dimension, so at large even an ordinary gap saturates the softmax. Dividing by holds the scale fixed, so the same-sized gap always produces the same-sized probability gap.
To see why the constant matters, make the argument quantitative. Suppose two keys produce raw dot products with the query that differ by one standard deviation of the score distribution. Because that distribution has standard deviation , a one-sigma gap is a raw difference of : the winning logit is , the loser is . Run those through the softmax and the winner's probability climbs sharply with dimension — at it wins with probability , at with , at it is to four decimals. The distribution has collapsed onto one word, and the gradient that would nudge the others has vanished. Divide by first and the same one-sigma gap becomes a difference of exactly at every dimension, so the winner's probability holds steady at regardless of . That is the whole point of the scaling: it fixes the softmax's operating point so the layer learns the same way whether is or .
A numeric trace of one attention step
For example, take three tokens and work in , computing the output for the third position, which (being causal) attends to positions , , and . Suppose the projections have already produced these query, key, and value vectors:
Step 1 — score. Dot the query against each key: , , .
Step 2 — scale. Divide by : .
Step 3 — softmax. Exponentiate and normalize. The weights come out , , , summing to . Position attends most to itself (its key matched the query best) and splits the rest evenly between positions and .
Step 4 — weighted sum of values.
The output is a blend of the three value vectors, tilted toward . Two details. First, the scaling changed the answer: with the raw scores the softmax would give weights , a sharper peak on position ; the divisor softened the distribution, as intended. Second, nothing here touched positions or beyond; had this been an encoder (bidirectional) layer, the query would also have scored against future keys, but the causal mask forbids it.
The whole layer as one matrix product
Because every output is independent, the layer has an efficient batched form. Pack the input vectors as rows of a matrix and project them all at once:
The product is an matrix holding every query-key score at once; scale it, softmax each row, and multiply by . The entire self-attention computation for a sequence of tokens collapses to a single expression:
This is the equation the entire architecture is built around. Note its cost: forming requires dot products, so attention is quadratic in the sequence length. That quadratic cost is why transformer inputs are usually capped at a page or a paragraph, and why more efficient attention variants are an active research area.6
Causal (masked) self-attention
For a language model the constraint is absolute: predicting the next word may use only the words before it. If position were allowed to attend to position , the model would see the answer it is supposed to predict. So a language-model attention layer must be causal — each query attends only to keys at its own position or earlier, exactly the condition written into the sums above.7
In the matrix form the full scores every query against every key, including future ones. Those forbidden entries sit in the upper triangle of the matrix. To forbid them, set the upper triangle to before the softmax; , so every future key receives exactly zero weight and contributes nothing to the output.
The same layer, without the mask, is bidirectional: every position attends to the whole sequence in both directions. Bidirectional self-attention is what an encoder uses, where the full input is available at once; causal self-attention is what a decoder and any left-to-right language model use. It is the identical operation with one triangular mask flipped on or off.7
With the attention operation in hand — a query scored against keys, softmaxed into weights, mixing values, optionally masked to be causal — we can assemble the full network. That is the job of the next part, which stacks attention into multiple heads, wraps it in the transformer block, restores word order, and arrives at the architectures modern NLP is built on. This continues in The Transformer Architecture.
Footnotes
- Jurafsky & Martin, Speech and Language Processing (3rd ed.), §9.7 — Self-Attention Networks: recurrent connections cause information loss over long spans and force serial computation; transformers eliminate recurrence to allow direct access to arbitrarily distant context and full parallelism. ↩
- Jurafsky & Martin, §9.7 — Self-Attention Networks (Fig. 9.15): a self-attention layer maps a sequence to a sequence of the same length, each output attending to the inputs up to and including its own position, with per-position computations independent and hence parallelizable. ↩
- Jurafsky & Martin, §9.7, Eqs. 9.27–9.30 — the core attention computation: a dot-product score between elements, a softmax normalization into weights , and a weighted sum of the inputs. ↩
- Jurafsky & Martin, §9.7, Eqs. 9.31–9.33 — the query, key, and value roles and their projection matrices ; the score as query-key dot product and the output as a weighted sum over value vectors, with dimensions and . ↩ ↩2
- Jurafsky & Martin, §9.7, Eq. 9.34 — scaled dot-product attention: dividing the score by keeps the dot product from growing with dimension and saturating the softmax, which would otherwise cause vanishing gradients. ↩
- Jurafsky & Martin, §9.7, Eqs. 9.35–9.36 — the packed matrix form ; the score matrix makes attention quadratic in sequence length. ↩
- Jurafsky & Martin, §9.7 (Fig. 9.17) — causal (masked) self-attention: for language modeling the upper-triangular scores over future tokens are set to so the softmax zeros them, restricting each query to keys at or before its position. ↩ ↩2
╌╌ END ╌╌