How does self-attention work, and what are its advantages?
For each token, the model computes weights saying how strongly every other token matters to it, then builds a new, context-aware vector as the weighted average. It handles long dependencies, runs in parallel and weights context dynamically.
* Self-attention for "cat": the new vector mixes every token's vector in proportion to its weight *
Example: in "The cat sat on the mat.", each token has an embedding vector. For "cat", the model computes attention weights, for instance The 0.1, cat 0.4, sat 0.3, on 0.05, the 0.05, mat 0.1. The new vector for "cat" is the weighted average of all the token vectors under those weights. "Cat" now carries information about what it did (sat).
In "Die Sängerin legte die Partitur auf den Flügel, bevor sie ihn öffnete" ("The singer put the score on the grand piano before she opened it"), attention links ihn ("it") strongly to Flügel ("grand piano") and weakly to Partitur ("score").
Its advantages:
- it captures long-range dependencies in the text;
- it allows parallel processing, unlike step-by-step recurrent networks;
- it weights context dynamically, differently for every sentence.
Attention is mathematical weighting, not conscious paying attention.
Go deeper:
3Blue1Brown: Attention in transformers, step-by-step — queries, keys, values and the weighted sums that update each token's vector.
Jay Alammar: The Illustrated Transformer — self-attention drawn step by step, including "it" attending to the right noun.
Vaswani et al. (2017): Attention Is All You Need, arXiv — the original self-attention paper.