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.
Prerequisites
Table of Contents
- Learning Objectives
- Notation
- Core Intuition
- From Retrieval to Attention
- The QKV Formulation
- Why Scale by Root-dk
- Attention as Soft Dictionary Lookup
- Masking: Causal and Padding
- Computational Complexity
- Common Pitfalls
- Summary
- Exercises
Learning Objectives
- Derive scaled dot-product attention from first principles.
- Prove why the scaling is necessary for stable softmax.
- Interpret attention weights as a soft retrieval mechanism.
- Derive the quadratic complexity and identify the bottleneck.
- Implement causal masking mathematically.
Notation
- — query matrix
- — key matrix
- — value matrix
- — attention weight matrix
- — key/query dimension
- — 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)
Query token (row):
Attention from "cat" to:
From Retrieval to Attention
Hard retrieval: Given a query , find the key most similar and return its value :
Soft retrieval (attention): Replace the hard with a soft distribution:
This is differentiable and allows gradient-based learning.
The QKV Formulation
For all queries simultaneously:
Step by step:
- Compute similarity scores: . Entry .
- Scale: .
- Normalize: (row-wise). Each row sums to 1.
- Aggregate: . Each output row is a weighted average of value rows.
Why Scale by Root-dk
Theorem. If , then has:
Proof. Each term has mean 0 and variance . Sum of independent terms has variance .
Problem: For large (e.g., 128), dot products have standard deviation . The softmax input has values in , pushing softmax into saturation (near one-hot), causing:
- Near-zero gradients through softmax.
- Attention concentrating on a single key.
Solution: Divide by 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 tell us: "how much does output position read from input position ?"
Properties:
- Each row of 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):
After softmax, positions with get weight 0: position can only attend to positions .
Padding mask: For variable-length sequences padded to the same length, mask padding positions with to prevent attending to padding tokens.
Computational Complexity
| Operation | FLOPs | Memory |
|---|---|---|
| Softmax | ||
Total: compute, memory.
The quadratic scaling in is the fundamental bottleneck of standard attention. For tokens: the attention matrix has billion entries — infeasible to store in GPU memory.
Common Pitfalls
Pitfall 1. Forgetting the scaling factor. Without , attention weights collapse to near-one-hot for large , 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 and . In self-attention they're equal; in cross-attention (encoder-decoder), they differ.
Summary
- Attention computes data-dependent weighted averages: .
- Scaling by prevents softmax saturation.
- Interpretable as soft dictionary lookup.
- Causal masking enforces autoregressive structure.
- Quadratic in sequence length: compute, memory.
Exercises
Exercise 1. Compute the attention output for , , with .
Exercise 2. Prove that 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 .
Exercise 5. Derive the gradient through the attention operation.