Self-attention is the operation at the heart of the transformer. Each token in a sequence looks at every token in that same sequence, itself included, decides how relevant each one is, and replaces its own vector with a weighted blend of what it found. After one layer, the vector for “it” in “the cat sat because it was tired” can carry information pulled from “cat”.
Ordinary attention was first used to let a translation model’s decoder look back at the source sentence: two different sequences. Self-attention points the same machinery inward. The 2017 transformer paper notes it was “sometimes called intra-attention” and had already been used in reading-comprehension models.
How it works
Every token’s vector is multiplied by three learned matrices to produce a query, a key and a value. The query says what the token is looking for, the key says what it offers, and the value is the content it passes on if chosen.
- Score each pair by taking the dot product of one token’s query with another token’s key.
- Divide by the square root of the key dimension, which stops large dot products from saturating the next step. This is the “scaled” in scaled dot-product attention.
- Apply a softmax across each row, so a token’s weights over all positions are positive and sum to 1.
- Output a weighted sum of the value vectors using those weights.
The chart is that weight matrix for one sentence: read a row to see where one token put its attention. Because all rows are computed together as a few matrix multiplications, the whole sequence is processed in parallel, which is what made transformers so fast to train.
Variations you’ll meet
- Multi-head attention runs several self-attention operations side by side with separate projections, so one head can track syntax while another tracks coreference.
- Causal (masked) self-attention blocks each token from seeing later positions. Decoder-only language models use it so that predicting the next word can’t peek at the answer.
- Cross-attention is the non-self version: queries come from one sequence, keys and values from another.
The catch
Every token scores every other token, so the work and the score matrix grow with the square of the sequence length. That is the main cost of a long context window, and it drives techniques like FlashAttention that reorganize the computation to use memory more efficiently. Self-attention also has no built-in sense of order, which is why transformers add positional encodings.