Summary
Attention forms one permitted weighted value mixture for each query. Queries and keys determine weights. Values supply the mixed payload; key and value rows must remain paired.
Normalize each query’s allowed scores separately, then multiply the resulting matrix by . Without dropout or later projections, every nonempty row is a convex value combination. This primitive appears in sequence, vision, graph, and memory models; an architecture’s dominant cost depends on its actual dimensions.
The mechanism step by step
For a single query and set of key-value pairs:
- Score each key against the query: .
- Normalize with softmax: . The sum to 1. They form an attention distribution.
- Aggregate: output .
Take one-dimensional query , keys , and values . Exponentiated scores are , so weights are . The output is . Changing a value changes the mixture’s payload without changing these query-key scores.
Learning objective
A larger value can outweigh a smaller attention weight
Derivation
What becomes of the second contribution if its value is zero but its weight stays unchanged?
If corresponding query-key coordinates are independent, zero-mean, and unit-variance, their summed dot product has variance . Dividing by gives unit variance under those assumptions. Learned correlations or different coordinate scales can change that analysis; scaling is not a universal nonsaturation guarantee.
Self-attention vs. cross-attention
- Self-attention: queries, keys, and values derive from the same sequence; a mask may restrict visible positions.
- Cross-attention: queries derive from one source and paired keys/values from another; their sequence lengths can differ.
Multi-head attention
Apply learned projections for several heads, mix values separately, concatenate the outputs, and apply an output projection. Head dimensions and counts are architecture choices; semantic specialization must be demonstrated rather than assumed.
In modern LLMs, heads are reduced via grouped-query attention where multiple Q heads share K/V heads.
Causal (autoregressive) masking
New task: Exclude future or padded positions from each mixture.
Picture and change: Set forbidden scores to before normalization; keep absolute position and cache-offset conventions explicit.
Check: Excluding the third key in the example renormalizes weights to and changes output to . Simply zeroing its old weight without renormalization gives , a different operation.
Use when: Only a permitted subset may contribute. An entirely masked row has no categorical distribution; reject it or define a separate zero-output policy explicitly.
Connection to retrieval
New task: Return one retrieved item instead of a value mixture.
Picture and change: Replace aggregation with the maximum-score key’s associated item.
Check: The example selects the first key and value , not the attention output .
Use when: A hard candidate is required. Positive-temperature softmax preserves score order, but a weighted sum is not nearest-neighbor retrieval. Cosine and raw dot-product rankings agree only under appropriate normalization, not in general.
Cost
- Score and mixture arithmetic costs , excluding projections.
- Explicit scores and weights need intermediate storage, in addition to inputs and output.
FlashAttention tiles exact dense attention without retaining the full score matrix. Its storage still includes dimension-dependent inputs, outputs, row statistics, and tile workspace.
Common pitfalls
- Unpaired rows. Permuting keys without the same value permutation changes the operation.
- Wrong causal offset. Cached decoding compares absolute query and key positions, not an arbitrary local triangle.
- Explanatory overreach. Mixture weights do not establish a causal explanation for the final model prediction.
- All-masked rows. Subtracting a row maximum of negative infinity produces invalid arithmetic without a special policy.
Reconstruct
What survives a joint permutation of keys and values?
Permuting paired keys and values merely permutes weights and their corresponding payloads, leaving the final sum unchanged. The mask and position-dependent score terms must receive the same permutation. Permuting only keys breaks that pairing guarantee.
Related
- Transformer architecture. Full assembly.
- FlashAttention. Efficient implementation.
- Grouped-query attention. Modern KV-cache optimization.