Glossary · Attention
Self-attention
Also: attentionscaled dot-product attentioncausal attention
Read it at the depth you need: one sentence · a paragraph · the math
1In one sentence
The layer where each token builds a weighted average of earlier tokens: a query is scored against every key, and the softmax of the scores weights the values.
2In a paragraph
Attention is how information moves between positions. Each token makes a query ("what am I looking for?"), a key ("what do I contain?") and a value ("what do I pass on?"). The query is compared with the key of every earlier token; the better the match, the more of that token's value is mixed in. In a language model the attention is causal: a token sees only itself and what came before, never the future.
3The math, shapes and parameters
For one head with head size h, the token at position t computes
q = WQxt, ki = WKxi, vi = WVxi
outt = Σi≤t softmaxi( q·ki / √h ) vi
The √h keeps the scores from growing with the head size, so the softmax does not saturate. Models run many heads side by side (multi-head attention) and add a position signal, usually RoPE, to q and k.
Cost. The projections are ordinary matmuls (2 FLOPs per weight). The scores are extra: for a new token, 2 × T × h multiply-adds per head for q·k and as many for the weighted sum of values, so attention's share of the work grows with the context length T. The keys and values of past tokens are kept in the KV cache so they are not recomputed.
Term by term on Notation Decoder, the sister site: Scaled dot-product attention, decoded · Softmax · Q, K and V
Introduced in Vaswani et al., “Attention Is All You Need” (2017).
Related
Multi-head attention (MHA) · Grouped-query attention (GQA) · KV cache · RoPE (rotary position embedding) · every term