Scaled Dot-Product Attention

The foundational attention mechanism: derivation of query-key-value formulation, the scaling factor, softmax temperature, attention as soft dictionary lookup, and computational complexity analysis.

Intermediate

Table of Contents

  1. Learning Objectives
  2. Notation
  3. Core Intuition
  4. From Retrieval to Attention
  5. The QKV Formulation
  6. Why Scale by Root-dk
  7. Attention as Soft Dictionary Lookup
  8. Masking: Causal and Padding
  9. Computational Complexity
  10. Common Pitfalls
  11. Summary
  12. Exercises

Learning Objectives

  1. Derive scaled dot-product attention from first principles.
  2. Prove why the 1/dk1/\sqrt{d_k} scaling is necessary for stable softmax.
  3. Interpret attention weights as a soft retrieval mechanism.
  4. Derive the quadratic complexity O(T2d)O(T^2d) and identify the bottleneck.
  5. Implement causal masking mathematically.

Notation

  • QRTq×dk\mathbf{Q} \in \mathbb{R}^{T_q \times d_k} — query matrix
  • KRTk×dk\mathbf{K} \in \mathbb{R}^{T_k \times d_k} — key matrix
  • VRTk×dv\mathbf{V} \in \mathbb{R}^{T_k \times d_v} — value matrix
  • ARTq×Tk\mathbf{A} \in \mathbb{R}^{T_q \times T_k} — attention weight matrix
  • dkd_k — key/query dimension
  • TT — sequence length

Core Intuition

Attention answers: "For each position in the output, which input positions are most relevant?" It computes a weighted average of values, where the weights are determined by the similarity between queries and keys. Unlike fixed-weight layers (convolution, MLP), attention weights are data-dependent — they change based on the input content.

Interactive: Self-Attention Weights

Attention Matrix (softmax scores)

The
cat
sat
on
the
mat
The
0.29
0.13
0.12
0.11
0.24
0.12
cat
0.14
0.28
0.18
0.11
0.12
0.17
sat
0.11
0.21
0.28
0.15
0.11
0.14
on
0.11
0.12
0.18
0.29
0.11
0.20
the
0.26
0.13
0.12
0.10
0.28
0.12
mat
0.11
0.15
0.14
0.21
0.11
0.28

Query token (row):

Attention from "cat" to:

The
0.137
cat
0.276
sat
0.185
on
0.112
the
0.124
mat
0.167
Explore: Low temperature → attention concentrates on highest-scoring key (sharper). High temperature → weights become uniform. This is exactly how the 1/√d scaling works in practice.

From Retrieval to Attention

Hard retrieval: Given a query q\mathbf{q}, find the key kj\mathbf{k}_j most similar and return its value vj\mathbf{v}_j:

output=vj,j=argmaxjqTkj.(1)\text{output} = \mathbf{v}_{j^*}, \quad j^* = \arg\max_j \mathbf{q}^T\mathbf{k}_j. \tag{1}

Soft retrieval (attention): Replace the hard argmax\arg\max with a soft distribution:

output=jαjvj,αj=exp(qTkj)lexp(qTkl).(2)\text{output} = \sum_j \alpha_j \mathbf{v}_j, \quad \alpha_j = \frac{\exp(\mathbf{q}^T\mathbf{k}_j)}{\sum_l\exp(\mathbf{q}^T\mathbf{k}_l)}. \tag{2}

This is differentiable and allows gradient-based learning.


The QKV Formulation

For all queries simultaneously:

Attention(Q,K,V)=softmax(QKTdk)V.(3)\boxed{\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\left(\frac{\mathbf{Q}\mathbf{K}^T}{\sqrt{d_k}}\right)\mathbf{V}.} \tag{3}

Step by step:

  1. Compute similarity scores: S=QKTRTq×Tk\mathbf{S} = \mathbf{Q}\mathbf{K}^T \in \mathbb{R}^{T_q \times T_k}. Entry Sij=qiTkjS_{ij} = \mathbf{q}_i^T\mathbf{k}_j.
  2. Scale: SS/dk\mathbf{S} \leftarrow \mathbf{S}/\sqrt{d_k}.
  3. Normalize: A=softmax(S)\mathbf{A} = \text{softmax}(\mathbf{S}) (row-wise). Each row sums to 1.
  4. Aggregate: output=AV\text{output} = \mathbf{A}\mathbf{V}. Each output row is a weighted average of value rows.

Why Scale by Root-dk

Theorem. If qi,kjiidN(0,1)q_i, k_j \overset{\text{iid}}{\sim} \mathcal{N}(0, 1), then qTk=i=1dkqiki\mathbf{q}^T\mathbf{k} = \sum_{i=1}^{d_k}q_ik_i has:

E[qTk]=0,Var(qTk)=dk.(4)\mathbb{E}[\mathbf{q}^T\mathbf{k}] = 0, \quad \text{Var}(\mathbf{q}^T\mathbf{k}) = d_k. \tag{4}

Proof. Each term qikiq_ik_i has mean 0 and variance Var(qi)Var(ki)=1\text{Var}(q_i)\text{Var}(k_i) = 1. Sum of dkd_k independent terms has variance dkd_k. \blacksquare

Problem: For large dkd_k (e.g., 128), dot products have standard deviation 12811\sqrt{128} \approx 11. The softmax input has values in [30,+30][-30, +30], pushing softmax into saturation (near one-hot), causing:

  • Near-zero gradients through softmax.
  • Attention concentrating on a single key.

Solution: Divide by dk\sqrt{d_k} to normalize variance to 1, keeping softmax in its sensitive regime.


Attention as Soft Dictionary Lookup

Interpretation: Think of attention as querying a dictionary:

  • Keys = addresses/labels of stored information.
  • Values = stored content.
  • Query = what you're looking for.
  • Output = content blended by relevance.

The attention weights αij\alpha_{ij} tell us: "how much does output position ii read from input position jj?"

Properties:

  • Each row of A\mathbf{A} is a probability distribution (sums to 1, non-negative).
  • Attention is permutation equivariant w.r.t. key-value pairs (order doesn't matter without positional encoding).
  • Attention is not equivariant to query permutation in the causal case.

Masking: Causal and Padding

Causal mask (for autoregressive models):

Mij={0iji<j,A=softmax(QKTdk+M).(5)M_{ij} = \begin{cases}0 & i \geq j \\ -\infty & i < j\end{cases}, \quad \mathbf{A} = \text{softmax}\left(\frac{\mathbf{QK}^T}{\sqrt{d_k}} + \mathbf{M}\right). \tag{5}

After softmax, positions with -\infty get weight 0: position ii can only attend to positions i\leq i.

Padding mask: For variable-length sequences padded to the same length, mask padding positions with -\infty to prevent attending to padding tokens.


Computational Complexity

OperationFLOPsMemory
QKT\mathbf{QK}^TO(T2dk)O(T^2 d_k)O(T2)O(T^2)
SoftmaxO(T2)O(T^2)O(T2)O(T^2)
AV\mathbf{AV}O(T2dv)O(T^2 d_v)O(Tdv)O(Td_v)

Total: O(T2d)O(T^2 d) compute, O(T2)O(T^2) memory.

The quadratic scaling in TT is the fundamental bottleneck of standard attention. For T=128KT = 128K tokens: the attention matrix has 128K216128K^2 \approx 16 billion entries — infeasible to store in GPU memory.


Common Pitfalls

Pitfall 1. Forgetting the scaling factor. Without 1/dk1/\sqrt{d_k}, attention weights collapse to near-one-hot for large dkd_k, and gradients vanish.

Pitfall 2. Applying causal mask after softmax instead of before. The mask must be added to logits (before softmax) to properly zero out future positions.

Pitfall 3. Confusing TqT_q and TkT_k. In self-attention they're equal; in cross-attention (encoder-decoder), they differ.


Summary

  • Attention computes data-dependent weighted averages: softmax(QKT/dk)V\text{softmax}(\mathbf{QK}^T/\sqrt{d_k})\mathbf{V}.
  • Scaling by 1/dk1/\sqrt{d_k} prevents softmax saturation.
  • Interpretable as soft dictionary lookup.
  • Causal masking enforces autoregressive structure.
  • Quadratic in sequence length: O(T2d)O(T^2d) compute, O(T2)O(T^2) memory.

Exercises

Exercise 1. Compute the attention output for Q=[1,0]\mathbf{Q} = [1, 0], K=[[1,0],[0,1]]\mathbf{K} = [[1,0],[0,1]], V=[[1,2],[3,4]]\mathbf{V} = [[1,2],[3,4]] with dk=2d_k = 2.

Exercise 2. Prove that Var(qTk)=dk\text{Var}(\mathbf{q}^T\mathbf{k}) = d_k under the stated assumptions.

Exercise 3. Show that attention is equivariant to permutation of key-value pairs.

Exercise 4. Compute the exact memory (in bytes, FP16) needed to store the attention matrix for T=8192,H=32T=8192, H=32.

Exercise 5. Derive the gradient L/Q\partial\mathcal{L}/\partial\mathbf{Q} through the attention operation.