Learn: Scaled Dot-Product Attention

What you're learning

The single operation the entire Transformer is built on. By the end you’ll be able to write scaled dot-product attention from memory, explain why it’s scaled by , and compute its FLOPs and cost. Everything in this curriculum is a variation on what you learn here.

First lesson of the Attention Mechanisms curriculum. Vocabulary follows the attention-glossary.


1. Learning map

graph TD
    A["Problem: mix information<br/>across a sequence,<br/>content-dependently"] --> B["Idea: soft key–value lookup"]
    B --> C["Q, K, V projections"]
    C --> D["scores = QKᵀ"]
    D --> E["scale by 1/√d_k"]
    E --> F["softmax → weights"]
    F --> G["weighted sum of V"]
    G --> H["output"]
    D --> I["cost: O(s²·d)<br/>the quadratic wall"]
    style B fill:#44a,color:#fff
    style I fill:#a44,color:#fff

2. Intuition: attention is a soft dictionary lookup

Forget matrices for a moment. A Python dict is a hard lookup: you have a query key, you find the one entry whose key matches exactly, and you return its value. Attention is the soft, differentiable version of that:

  • Every token emits a query (“what am I looking for?”),
  • every token also exposes a key (“what do I offer?”) and a value (“what I’ll actually hand over”),
  • a query compares itself against all keys, producing a similarity score for each,
  • those scores become weights (they sum to 1), and the output is the weighted average of all values.

So instead of retrieving one value, each token retrieves a blend of everyone’s values, weighted by how well its query matches each key. It’s content-based, learned, and — crucially — differentiable, so the network learns what to look for.

The one-sentence version

Attention lets every position pull in information from every other position, with the amount pulled decided by learned query–key similarity. It is the mechanism for content-dependent, long-range information routing.

A little history. The idea entered deep learning as additive attention for machine translation (Bahdanau et al., 2014), where an MLP scored a decoder query against encoder states.1 The Transformer replaced that MLP with a plain dot product (cheaper, parallelizable) and made attention the entire model rather than an add-on to an RNN.2


3. The math

Pack the sequence’s queries, keys, and values into matrices. For tokens, with query/key dimension and value dimension :

obtained by linear projections of the input : , , .

Scores. Every query dotted with every key:

measures how much token ‘s query matches token ‘s key.

Scale, then softmax row-wise to get weights that sum to 1 across keys:

Output = weighted sum of values:

Why divide by ?

Suppose the entries of and are independent with mean 0 and variance 1. Their dot product is a sum of independent zero-mean, unit-variance terms, so it has variance and standard deviation .2 As grows (say 128), raw scores swing by . Feed scores that large into softmax and it saturates: almost all mass lands on one key, and the gradient through the near-flat softmax tails . Dividing by renormalizes the scores back to unit variance, keeping softmax in its responsive, high-gradient regime. It’s a variance-control trick, nothing more — but training breaks without it.

Causal masking (for autoregressive LMs)

In a decoder LM, token must not see the future. Before softmax, set for all (a lower-triangular mask); softmax then assigns those positions zero weight. This mask is what makes the same attention op “causal” — and, later, what lets you cache past keys/values (KV cache).


4. Illustration: a 3-token pass

flowchart LR
    X["X (s×d)"] -->|W^Q| Q["Q (s×d_k)"]
    X -->|W^K| K["K (s×d_k)"]
    X -->|W^V| V["V (s×d_v)"]
    Q --> S["S = QKᵀ (s×s)"]
    K --> S
    S -->|"÷√d_k, softmax"| A["A (s×s)"]
    A --> O["O = A·V (s×d_v)"]
    V --> O

Concretely, with : is ; row of is a probability distribution over the 3 tokens; output row is — token ‘s personalized blend of all values. If is large, token is “attending to” token 2.


5. FLOPs & complexity

Count multiply-adds as 2 FLOPs. For batch , sequence , model dim (take for a single-head view):

StepShapeFLOPs
Scores
Softmax (small)

So the attention core is FLOPs, and — the headline — it is quadratic in sequence length . Double the context, quadruple the attention compute (and the score matrix’s memory). The projections add , which dominates at short but is overtaken by the term as context grows. This single fact is the reason Tiers 2–4 of this curriculum exist.


6. Practice


The primary source is Vaswani et al., “Attention Is All You Need” (2017)2 — read §3.2 (scaled dot-product & multi-head attention). For the pre-Transformer origin, skim Bahdanau et al. (2014)1.

Ask your teacher

Stuck on the variance argument, the masking, or the FLOPs count? Ask — I’m your teacher for this course and can go deeper on any piece, or make you a harder practice problem.

What’s next


References

Reference: attention-glossary | Topic: attention-mechanisms | Filed: 2026-09-10

Footnotes

  1. Bahdanau, Cho, Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate” — arXiv:1409.0473 (2014). The additive (MLP-scored) attention that preceded dot-product attention. ↩ ↩2

  2. Vaswani et al., “Attention Is All You Need” — arXiv:1706.03762 (2017). Introduces scaled dot-product attention (§3.2.1), the scaling and its variance rationale, multi-head attention, and the Transformer. ↩ ↩2 ↩3