Self-attention lets every token in a sequence look at every other token and decide what to pay attention to. A word's representation becomes a weighted blend of all the words around it — this is the engine inside every Transformer.
Where you meet it
- Every large language model — GPT, Claude, BERT, Llama — is a stack of self-attention layers.
- Resolving what a word refers to: in "the cat sat on the mat because it was tired", it attends back to cat.
- Machine translation, summarization, code completion — anywhere context across a sequence matters.
- Vision (ViT) and audio too: split the input into patches or frames, then attend.
What it does
It replaces each token's vector with a context-aware version. Instead of reading a word in isolation, the model asks "which other tokens are relevant to me right now?" and mixes their information in. "Self" means the sequence attends to itself — queries, keys, and values all come from the same input.
A word has no fixed meaning here — it becomes whatever the words it attends to make it. And every token attending to every other costs O(n²).
How it works
Each token is projected into three vectors: a query (what I'm looking for), a key (what I offer), and a value (the content I carry). To score how relevant token j is to token i, you take the dot product of i's query with j's key. High dot product → high relevance. Softmax turns the row of scores into weights that are positive and sum to 1, and the output is the weighted sum of all the values.
Attention(Q, K, V) = softmax(QKᵀ / √dₖ) · V
QKᵀ— every query dotted with every key: an n×n matrix of raw relevance scores.softmax(...)— each row becomes attention weights (positive, summing to 1).· V— blend the values by those weights; that mix is the new token vector.
The √dₖ divisor matters: as the key dimension dₖ grows, raw dot products grow with it, pushing softmax into a region where one weight is ~1 and the rest ~0. There the gradient nearly vanishes and learning stalls. Dividing by √dₖ keeps the scores at a sane scale — hence scaled dot-product attention.
Watch out
- Cost is O(n²) in sequence length — the QKᵀ matrix is n×n. Double the context, quadruple the compute and memory. This is why context windows have a limit.
- Order-blind by itself. Attention is permutation-invariant: shuffle the tokens and it gives the same answer. You must add positional encoding so the model knows word order.
- Decoders need a causal mask. When generating text left-to-right, each token may only attend to earlier ones — mask future positions to −∞ before softmax, or the model cheats by peeking ahead.
- Don't drop the √dₖ. Without scaling, large dₖ saturates softmax and gradients shrink — training becomes slow or unstable.
Go deeper
Self-Attention lässt jedes Token einer Sequenz auf jedes andere Token schauen und entscheiden, worauf es achtet. Die Repräsentation eines Worts wird zu einer gewichteten Mischung aller umliegenden Wörter — das ist der Motor in jedem Transformer.
Wo es vorkommt
- Jedes große Sprachmodell — GPT, Claude, BERT, Llama — ist ein Stapel von Self-Attention-Schichten.
- Auflösen von Bezügen: In "die Katze saß auf der Matte, weil sie müde war" bezieht sich sie zurück auf Katze.
- Übersetzung, Zusammenfassung, Code-Vervollständigung — überall, wo Kontext über eine Sequenz zählt.
- Auch Bild (ViT) und Audio: Eingabe in Patches oder Frames zerlegen, dann attendieren.
Was es tut
Es ersetzt den Vektor jedes Tokens durch eine kontextbewusste Version. Statt ein Wort isoliert zu lesen, fragt das Modell "welche anderen Token sind gerade für mich relevant?" und mischt deren Information ein. "Self" heißt: Die Sequenz attendiert auf sich selbst — Query, Key und Value stammen alle aus derselben Eingabe.
Ein Wort hat hier keine feste Bedeutung — es wird das, wozu die Wörter es machen, auf die es achtet. Und jeder schaut auf jeden: O(n²).
Wie es funktioniert
Jedes Token wird in drei Vektoren projiziert: eine Query (wonach ich suche), einen Key (was ich biete) und einen Value (den Inhalt, den ich trage). Um zu bewerten, wie relevant Token j für Token i ist, bildet man das Skalarprodukt aus is Query und js Key. Großes Skalarprodukt → hohe Relevanz. Softmax macht aus der Score-Zeile Gewichte, die positiv sind und sich zu 1 summieren, und der Output ist die gewichtete Summe aller Values.
Attention(Q, K, V) = softmax(QKᵀ / √dₖ) · V
QKᵀ— jede Query mit jedem Key multipliziert: eine n×n-Matrix roher Relevanz-Scores.softmax(...)— jede Zeile wird zu Attention-Gewichten (positiv, Summe 1).· V— die Values nach diesen Gewichten mischen; diese Mischung ist der neue Token-Vektor.
Der Divisor √dₖ ist wichtig: Wächst die Key-Dimension dₖ, wachsen die rohen Skalarprodukte mit — und drängen Softmax in einen Bereich, wo ein Gewicht ~1 und der Rest ~0 ist. Dort verschwindet der Gradient fast, und das Lernen stockt. Das Teilen durch √dₖ hält die Scores in vernünftiger Größe — daher scaled Dot-Product Attention.
Worauf achten
- Aufwand ist O(n²) in der Sequenzlänge — die QKᵀ-Matrix ist n×n. Doppelter Kontext, vierfacher Rechen- und Speicherbedarf. Darum haben Kontextfenster eine Grenze.
- Von sich aus reihenfolge-blind. Attention ist permutationsinvariant: Tokens vertauschen liefert dasselbe Ergebnis. Man muss Positional Encoding hinzufügen, damit das Modell die Wortreihenfolge kennt.
- Decoder brauchen eine Causal Mask. Beim Generieren von links nach rechts darf jedes Token nur auf frühere achten — zukünftige Positionen vor dem Softmax auf −∞ maskieren, sonst spickt das Modell nach vorn.
- Das √dₖ nicht weglassen. Ohne Skalierung sättigt großes dₖ den Softmax und die Gradienten schrumpfen — das Training wird langsam oder instabil.