Self-attention
A mechanism where each element in a sequence computes a weighted combination of all elements in that sequence, letting the model decide which parts to focus on.
Roadmap step 2 of 4: Attention and the MLP. Try it: Transformer Explainer: the transformer block ↗, LLM Visualization: a small GPT in 3D, step by step ↗
What it is
Self-attention is the core operation of the Transformer. Each token in an input is compared with every other token, producing weights that say how relevant each one is. The output for each token is a weighted mix of information from the whole sequence. It replaced recurrence as the main way models relate distant parts of an input.
Why it matters
Self-attention lets models capture long-range relationships and be trained in parallel on modern hardware, which is a major reason large language models scale well. Its cost grows quickly with sequence length, which drives much work on long context, efficient variants and linear attention. Understanding it helps in reasoning about context limits, memory use and inference speed.
How it works
Each token's representation is projected into three vectors: a query, a key and a value. The query of one token is compared with the keys of all tokens, usually by dot product, and a softmax turns the scores into weights. Those weights combine the value vectors into the output. Multiple heads run this in parallel with different projections, and causal masking stops a token from seeing later ones in language models. Because attention ignores order by itself, positional encoding is added.