Skip to content
mlmentorship

The attention mechanism

Compute a weighted sum of values, weights derived from query-key similarity. The single operation that powers transformers, retrieval, and most of modern ML.

Published · 7 min read ·Core ·Foundation
Reading depth

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:

  1. Score each key against the query: .
  2. Normalize with softmax: . The sum to 1. They form an attention distribution.
  3. 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

Attention weight is not the final contributionA smaller attention weight can carry a larger value. Compare the products, not the weights alone.Width: weight. Height: value.weight 0.8value 1area 0.8weight 0.2value 10area 20.8 + 2 = 2.8Each tile contributes 0.2
Derivation
The query and keys determine three attention weights One query is compared with three keys. After scaled similarity and softmax, the key rows receive normalized weights 0.60, 0.30, and 0.10. The weights sum to one. Values do not participate in this scoring stage. 1 · KEYS SET THE MIXING WEIGHTS q query k₁ k₂ k₃ scaled similarity α₁ = 0.60 α₂ = 0.30 α₃ = 0.10 SOFTMAX WEIGHTS: 0.60 + 0.30 + 0.10 = 1
The same weights mix the three values into the output For a one-dimensional teaching example, values 1, 4, and 7 are multiplied by weights 0.60, 0.30, and 0.10. Their contributions 0.60, 1.20, and 0.70 sum to the attention output 2.50. Keys do not become part of the output. 2 · VALUES SUPPLY THE PAYLOAD 0.60 × v₁ (1) = 0.60 0.30 × v₂ (4) = 1.20 0.10 × v₃ (7) = 0.70 output 2.50 WEIGHTED SUM: 0.60 + 1.20 + 0.70
Read it this way: query-key scores determine weights summing to one. Those same weights mix the paired values into 2.5. Keys select the mixture; values supply its contents.
Check: Why does the value with weight 0.30 contribute more than the value with weight 0.60?
Read it this way: A smaller attention weight can carry a larger value. Compare the products, not the weights alone.
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.