AI / ML Theory
Chapter 6 · 22 min

6.2 — Scaled dot-product attention

Goal: Specialise the soft-lookup formula to use the scaled dot product as similarity, derive the batched form Attn(Q, K, V) = softmax(QKᵀ/√d_k) V, and understand why the √d_k scaling is the difference between training and not training.

1. Why this session exists

6.1 left us with the general attention formula

attn(q, K, V)=∑i=1mαi vi,αi=exp⁡(s(q,ki))∑jexp⁡(s(q,kj)),\text{attn}(q,\, K,\, V) = \sum_{i = 1}^{m} \alpha_i\, v_i, \qquad \alpha_i = \frac{\exp(s(q, k_i))}{\sum_j \exp(s(q, k_j))},

with the similarity function s(q,k)s(q, k) left unspecified. This session picks the function that every Transformer uses — the scaled dot product — and writes the operation in batched matrix form. Picking the similarity is not arbitrary: the choice has a direct consequence on whether the network trains at all, and the dk\sqrt{d_k} scaling factor is the single most important hyperparameter-free piece of the design.[1, 2, 4, 5]


2. The dot product as a similarity

For two vectors q,k∈Rdkq, k \in \mathbb{R}^{d_k}, the natural geometric similarity is the inner product

⟨q,k⟩=q⊤k=∑j=1dkqj kj.\langle q, k \rangle = q^\top k = \sum_{j = 1}^{d_k} q_j\, k_j.

It is large and positive when qq and kk point in similar directions, near zero when they are orthogonal, and negative when they oppose. As a similarity score for attention, it has three structural virtues:

  1. Computable in a single GEMM. With all queries packed into Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k} and all keys into K∈Rm×dkK \in \mathbb{R}^{m \times d_k}, every pairwise score is one matrix product:
S=QK⊤∈Rn×m,Sij=⟨qi,kj⟩.S = Q K^\top \in \mathbb{R}^{n \times m}, \qquad S_{ij} = \langle q_i, k_j \rangle.

This is the workhorse operation GPUs are tuned for.

  1. Bilinear in the parameters. Because the score is linear in qq and in kk, the gradient through it has a simple form. We will see in 6.3 that qq and kk are produced from input embeddings by separate learnable linear maps; the dot product makes the whole thing differentiable in clean closed form.

  2. Statistically well-behaved at standard initialisation. If qq and kk have i.i.d. zero-mean unit-variance coordinates, the dot product has a controlled distribution — variance dkd_k, mean 00. This is the property that the dk\sqrt{d_k} scaling exploits.

Other choices exist — additive attention (Bahdanau et al., 2014)[3] uses s(q,k)=w⊤tanh⁡(Wqq+Wkk)s(q, k) = w^\top \tanh(W_q q + W_k k); bilinear attention uses s(q,k)=q⊤Wks(q, k) = q^\top W k — and the original "neural attention" paper (Bahdanau et al., 2014) used additive. Attention Is All You Need picked the dot product and added the dk\sqrt{d_k} scaling for the reason in §4 below; this is the choice the entire LLM family has inherited.


3. The batched form

For a query matrix Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k} (one query per row), a key matrix K∈Rm×dkK \in \mathbb{R}^{m \times d_k}, and a value matrix V∈Rm×dvV \in \mathbb{R}^{m \times d_v}, the scaled dot-product attention is:

 Attn(Q, K, V)=softmax ⁣(QK⊤dk)V. \boxed{\ \text{Attn}(Q,\, K,\, V) = \text{softmax}\!\left( \frac{Q K^\top}{\sqrt{d_k}} \right) V. \ }

The softmax is applied row-wise: each of the nn rows of QK⊤/dkQ K^\top / \sqrt{d_k} is independently normalised over its mm entries.

3.1 Shapes, slowly

Let us trace the shapes:

| Quantity | Shape | What it is | | --- | --- | --- | | QQ | n×dkn \times d_k | Queries (one per row) | | KK | m×dkm \times d_k | Keys (one per row) | | VV | m×dvm \times d_v | Values (one per row) | | QK⊤Q K^\top | n×mn \times m | Pairwise similarity matrix; row ii is "query ii vs all keys" | | QK⊤/dkQ K^\top / \sqrt{d_k} | n×mn \times m | Scaled scores | | softmax(⋅)\text{softmax}(\cdot) | n×mn \times m | Attention weights; each row sums to 1 | | softmax(⋅) V\text{softmax}(\cdot)\, V | n×dvn \times d_v | Output (one row per query) |

A typical self-attention layer in a decoder-only LLM has n=m=Tn = m = T (queries, keys, values all come from the same sequence of length TT) and dk=dv=d/hd_k = d_v = d / h where dd is the hidden size and hh is the number of heads (6.4). For a small Transformer with T=1024,d=768,h=12T = 1024, d = 768, h = 12, that's dk=dv=64d_k = d_v = 64, so Q∈R1024×64Q \in \mathbb{R}^{1024 \times 64}, the score matrix is 1024×10241024 \times 1024, and the output is 1024×641024 \times 64.

3.2 Row-wise softmax: each query is independent

The softmax in attention is applied across keys for each query: row ii of QK⊤Q K^\top becomes a probability distribution over the mm keys that query ii might attend to.

Concretely, with S=QK⊤/dkS = Q K^\top / \sqrt{d_k}, the attention weight matrix A∈Rn×mA \in \mathbb{R}^{n \times m} has entries

Aij=exp⁡(Sij)∑j′=1mexp⁡(Sij′),∑j=1mAij=1 for each i.A_{ij} = \frac{\exp(S_{ij})}{\sum_{j' = 1}^{m} \exp(S_{ij'})}, \qquad \sum_{j = 1}^{m} A_{ij} = 1\ \text{for each } i.

Different queries can attend to different distributions over keys; the rows do not interact. This is what makes attention "per-token" in its mixing.

3.3 The compute and memory bill

Compute:

  • QK⊤Q K^\top: Θ(n m dk)\Theta(n\, m\, d_k) FLOPs.
  • Softmax: Θ(n m)\Theta(n\, m).
  • AVA V: Θ(n m dv)\Theta(n\, m\, d_v).

Total: Θ(nm(dk+dv))\Theta(n m (d_k + d_v)). For self-attention with n=m=Tn = m = T and dk=dv=d/hd_k = d_v = d/h, the per-head cost is Θ(T2d/h)\Theta(T^2 d / h), and the total over hh heads is Θ(T2d)\Theta(T^2 d).

Memory: the score matrix S∈Rn×mS \in \mathbb{R}^{n \times m} has Θ(nm)\Theta(nm) entries. For self-attention this is Θ(T2)\Theta(T^2), the quadratic memory cost that motivates long-context variants in 6.13.


4. Why dk\sqrt{d_k}? The variance argument

The scaling factor 1/dk1 / \sqrt{d_k} is the single design choice that makes scaled dot-product attention trainable. Here is the argument from Attention Is All You Need §3.2.1.

Suppose query and key vectors q,k∈Rdkq, k \in \mathbb{R}^{d_k} are each composed of dkd_k i.i.d. random coordinates with mean 0 and variance 1 — a reasonable model for vectors right after initialisation, where the matrices WQ,WKW_Q, W_K have small variance and inputs are standardised. Then:

E[q⊤k]=∑j=1dkE[qj]E[kj]=0,\mathbb{E}[q^\top k] = \sum_{j = 1}^{d_k} \mathbb{E}[q_j] \mathbb{E}[k_j] = 0, Var[q⊤k]=∑j=1dkVar[qjkj]=∑j=1dkVar[qj] Var[kj]=dk.\mathrm{Var}[q^\top k] = \sum_{j = 1}^{d_k} \mathrm{Var}[q_j k_j] = \sum_{j = 1}^{d_k} \mathrm{Var}[q_j]\, \mathrm{Var}[k_j] = d_k.

(In the variance step we used independence of qq and kk and the variance-of-product formula for zero-mean factors.) So the standard deviation of q⊤kq^\top k scales as dk\sqrt{d_k}.

For dk=64d_k = 64, the scores have std ≈8\approx 8. The softmax of such scores is already badly saturated — one entry is multiple standard deviations larger than the others, the corresponding α→1\alpha \to 1, the rest →0\to 0. Two consequences:

(a) Vanishing gradients. Saturated softmax has ∂α/∂s→0\partial \alpha / \partial s \to 0 everywhere except the "winner." Backprop through the softmax sends essentially zero gradient to the keys that lost. The other keys cannot move toward better matches.

(b) Hard match before training begins. With softmax saturated at initialisation, every query in every layer locks onto a single key from step zero. The network looks like it is making decisions, but the decisions are essentially random and the gradients to fix them are vanishingly small.

The fix: divide the scores by dk\sqrt{d_k} before the softmax. This rescales q⊤kq^\top k to have unit variance, putting the softmax in its non-saturated regime regardless of dkd_k. With variance 1, exponential differences between scores are bounded by a constant, the softmax output is informative for every query, and gradients flow to every key.


5. A small worked example

Take three keys and three values in dk=dv=2d_k = d_v = 2:

K=(100111),V=(10001055).K = \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix}, \qquad V = \begin{pmatrix} 10 & 0 \\ 0 & 10 \\ 5 & 5 \end{pmatrix}.

And one query q=(1,0)q = (1, 0), so Q=(1,0)Q = (1, 0) as a 1×21 \times 2 row.

Step 1 — scores. QK⊤=(1⋅1+0⋅0, 1⋅0+0⋅1, 1⋅1+0⋅1)=(1,0,1)Q K^\top = (1 \cdot 1 + 0 \cdot 0,\ 1 \cdot 0 + 0 \cdot 1,\ 1 \cdot 1 + 0 \cdot 1) = (1, 0, 1).

Step 2 — scale. Divide by dk=2≈1.414\sqrt{d_k} = \sqrt{2} \approx 1.414: (0.707,0,0.707)(0.707, 0, 0.707).

Step 3 — softmax. Exponentials: (exp⁡(0.707),exp⁡(0),exp⁡(0.707))≈(2.028,1.000,2.028)(\exp(0.707), \exp(0), \exp(0.707)) \approx (2.028, 1.000, 2.028). Sum: 5.0565.056. Normalised: (0.401,0.198,0.401)(0.401, 0.198, 0.401).

Step 4 — weighted values. Output =0.401⋅(10,0)+0.198⋅(0,10)+0.401⋅(5,5)=(4.01+0+2.005, 0+1.98+2.005)=(6.015,3.985)= 0.401 \cdot (10, 0) + 0.198 \cdot (0, 10) + 0.401 \cdot (5, 5) = (4.01 + 0 + 2.005,\ 0 + 1.98 + 2.005) = (6.015, 3.985).

The query (1,0)(1, 0) aligns best with keys 1 and 3 (both have score 1) and roughly evenly splits attention between them, lightly attending to key 2. The output mixes the values of the chosen keys.

5.1 Without the 2\sqrt{2} scaling

If we omitted the scale (scores (1,0,1)(1, 0, 1) directly into softmax), the exponentials would be (e,1,e)≈(2.718,1.000,2.718)(e, 1, e) \approx (2.718, 1.000, 2.718), sum 6.4366.436, weights (0.422,0.155,0.422)(0.422, 0.155, 0.422) — slightly more concentrated, but for dk=2d_k = 2 the effect is small. At dk=64d_k = 64, with typical post-init magnitudes, the score gap would be many standard deviations and the softmax would be near-degenerate. The scaling matters more the larger dkd_k gets.


6. Reading the formula in one phrase

The whole operation in plain language:

"Each query produces a probability distribution over keys (by softmax of scaled dot-product similarities). The output is the values, averaged under that distribution."

Every architectural choice in the rest of Chapter 6 is a refinement of this single sentence. Self-attention (6.3) specifies where Q,K,VQ, K, V come from. Multi-head (6.4) specifies how many copies of this operation run in parallel. Causal mask (6.5) specifies which keys each query may attend to. Positional info (6.6, 6.7) specifies how order is injected. FFN (6.8) is the per-position non-linearity that pairs with attention to build a complete block.

Self-test

(a) Verify the shape rules of §3.1: given Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k}, K∈Rm×dkK \in \mathbb{R}^{m \times d_k}, V∈Rm×dvV \in \mathbb{R}^{m \times d_v}, confirm by index notation that Attn(Q,K,V)∈Rn×dv\text{Attn}(Q, K, V) \in \mathbb{R}^{n \times d_v}.

(b) Show that for fixed Q,K,VQ, K, V, the operation Q↦Attn(Q,K,V)Q \mapsto \text{Attn}(Q, K, V) is not linear in QQ (the softmax breaks linearity). Identify exactly which step introduces non-linearity.

(c) Re-derive the variance argument of §4 if qq and kk have variance σ2\sigma^2 (not 11) per coordinate. What is Var[q⊤k]\mathrm{Var}[q^\top k]? What scaling factor should be used in place of dk\sqrt{d_k} to recover unit variance?

(d) For the example of §5, change the query to q=(0,1)q = (0, 1) and recompute the attention weights and output. Which value gets the largest weight? Does the answer match your geometric intuition about the keys?

(e) Compute the total FLOPs and the score-matrix memory for a self-attention layer with T=4096,d=4096,h=32,dk=dv=128T = 4096, d = 4096, h = 32, d_k = d_v = 128. Compare with a single attention head (h=1,dk=4096h = 1, d_k = 4096) of the same total dd. Which one is cheaper in compute? Which uses less score-matrix memory?

[6, 7, 8]

References

  1. [1]

    Prince, S. J. D. (2023). Understanding Deep Learning, §12 (Sequence-to-Sequence Models) and §13 (Transformers). MIT Press. — Attention as soft lookup (6.1), scaled dot-product attention (6.2), multi-head attention (6.4).

    ↩
  2. [2]

    Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). "Attention is all you need". NeurIPS. arXiv:1706.03762 — The Transformer paper. Scaled dot-product attention (6.2), multi-head attention (6.4), encoder–decoder cross-attention (6.3), sinusoidal positional encoding (Appendix 6.A), the FFN sub-layer (6.8), post-LN block diagram (6.10), full architecture read (6.11).

    ↩
  3. [3]

    Bahdanau, D., Cho, K., & Bengio, Y. (2014). "Neural machine translation by jointly learning to align and translate". arXiv:1409.0473 — First "neural attention" paper; additive attention as a precursor to scaled dot-product (6.1, 6.2).

    ↩
  4. [4]

    Luong, M.-T., Pham, H., & Manning, C. D. (2015). "Effective approaches to attention-based neural machine translation". EMNLP. arXiv:1508.04025 — Dot-product attention variants (6.2).

    ↩
  5. [5]

    3Blue1Brown. "But what is a GPT? Visual intro to Transformers" and "Attention in transformers, step-by-step". 3blue1brown.com — Visual introduction to attention (6.1, 6.2).

    ↩
  6. [6]

    Dettmers, T., Lewis, M., Belkada, Y., & Zettlemoyer, L. (2022). "LLM.int8(): 8-bit matrix multiplication for transformers at scale". arXiv:2208.07339 — Outlier-aware quantisation; structural activation outliers (7.4 §6.2; full treatment Cap 10.6).

    ↩
  7. [7]

    Wang, P., Li, L., Shao, Z., et al. (2024). "Math-Shepherd: Verify and reinforce LLMs step-by-step without human annotations". arXiv:2312.08935 — Outcome-conditioned synthetic PRM labels (9.12 §6.2).

    ↩
  8. [8]

    Snell, C., Lee, J., Xu, K., & Kumar, A. (2024). "Scaling LLM test-time compute optimally can be more effective than scaling model parameters". arXiv:2408.03314 — Inference-time scaling laws (9.15 §6.2).

    ↩