Scaled Dot-Product Self-Attention
Scaled dot-product self-attention maps each token to queries, keys and values, computes softmax of , and returns a convex combination of values — a content-based, permutation-equivariant routing layer with cost.
1. Concept overview
Self-attention is a layer that lets each position in a sequence gather information from every other position, with weights determined by the content of the tokens rather than by fixed distances. Given an input matrix ( tokens, model width ), three learned linear maps produce
with and . The layer output is
where softmax is applied row-wise over keys. Row of the softmax matrix gives the mixture weights with which token reads the value vectors; output row is .
The name "self"-attention distinguishes it from encoder–decoder cross-attention: queries, keys and values all come from the same sequence. The factor is not cosmetic — it keeps scores in a range where softmax retains useful gradients.
2. Why this concept exists
Recurrent networks carry information through a hidden state that must pass through sequential steps, so distant dependencies are diluted and training cannot be parallelised across positions. Convolutions are parallel but have a fixed receptive field, requiring many layers to connect distant tokens.
Attention solves both: every pair of positions interacts in one layer via a single matrix product, and all positions are computed in parallel. Earlier attention (Bahdanau et al. 2015, Luong et al. 2015) was an additive alignment between encoder and decoder; Vaswani et al. (2017) replaced recurrence entirely with dot-product self-attention, showing that a content-based routing matrix is expressive and hardware-friendly.
The price is quadratic cost in sequence length: per layer. The transformer bet is that this price is acceptable up to a few thousand tokens, and that parallelisability and short gradient paths more than compensate. Modern long-context work (sparse attention, linear attention, state-space models) is largely an attempt to remove that term without losing the routing ability.
3. Historical background
Attention was introduced for machine translation by Bahdanau, Cho and Bengio (2015) as a soft alignment over encoder hidden states, computed by a small additive network. Luong, Pham and Manning (2015) compared dot-product and additive scoring and found dot products competitive and cheaper. Vaswani et al. (2017) introduced the scaled dot-product attention equation, multi-head attention, and the full transformer stack, making self-attention the central primitive. Child et al. (2019) proposed sparse factorisations for long sequences; Beltagy et al. (2020) and Zaheer et al. (2020) introduced Longformer and BigBird patterns. Dao et al. (2022) showed that exact attention can be made IO-efficient (FlashAttention) by tiling rather than changing the mathematics. Su et al. (2021) introduced RoPE, which injects position information directly into and . The 2020s LLM wave is a direct continuation of this line.
4. Fundamental problem
For each query position , compute a distribution over keys that reflects how relevant each key is to that query, and use it to aggregate values — doing this for all simultaneously, differentiably, and with shapes that stay manageable.
Three design questions must be answered:
- Score: how to measure query–key compatibility? A dot product is cheap and, after learned projections, expressive.
- Normalisation: convert arbitrary real scores into nonnegative weights summing to 1 — softmax with temperature .
- Scale: dot-product variance grows with dimension, so unnormalised scores can push softmax into saturation; divide by .
A fourth issue is crucial in generative models: without masking, position could read position , leaking the future. A causal mask sets those logits to .
5. First-principles explanation
Fact 1 (dot product as similarity). For vectors with i.i.d. zero-mean unit-variance components, and . Thus the score magnitude grows as with dimensionality even when tokens are unrelated; the content signal is buried in scale. Dividing by restores unit variance and makes the softmax temperature independent of .
Fact 2 (softmax as soft argmax). Row-wise softmax maps logits to a simplex. It is differentiable, shift-invariant (), and becomes sharply peaked as logit gaps grow. Sharpness controls the gradient signal: if one logit dominates by , and learning stalls.
Fact 3 (weighted average). is a convex combination of value rows, so lies in their convex hull. This bounded, differentiable retrieval operation is the whole layer.
Together: project inputs, score with a variance-normalised dot product, normalise with softmax, aggregate values.
6. Prerequisite concepts
You need: (a) matrix multiplication shapes and transposes; (b) the softmax function and its Jacobian; (c) cross-entropy / log-sum-exp for stable implementation; (d) backpropagation through a DAG, since the backward pass of attention has several VJPs; (e) basic probability (expectation and variance of a dot product); (f) sequence modelling context (token embeddings, recurrence, convolution) to appreciate what attention replaces. See the linked concepts for each.
7. Complete mathematical formulation
Single head. With :
Explicitly, and .
Causal mask (decoder). Replace for ; then is lower-triangular and each row sums to 1 over .
Multi-head. For heads with :
Backward formulas. Given upstream , with for simplicity:
8. Notation dictionary
| Symbol | Meaning | Shape / type | |---|---|---| | | sequence length (tokens) | integer | | | model / embedding width | integer | | | per-head key/query and value dimension | integers | | | number of attention heads | integer | | | input token representations | | | | queries, keys, values | , , | | | learned projection matrices | etc. | | | scaled logits (scores) | | | | row-stochastic attention matrix | | | | causal mask ( if ) | | | | output | | | | upstream gradients / adjoints | same shape as forward tensor | | | elementwise (Hadamard) product | operator |
9. Step-by-step derivation
Step 1 — projections. etc. are affine maps; their backward is a matrix multiply by , and the weight gradients are , etc.
Step 2 — scores. . Differentiating: accumulates into and (check shapes: ).
Step 3 — softmax Jacobian. For one row , has Jacobian . Therefore, for upstream row :
Vectorised over rows: . Note — softmax is invariant to adding a constant to a row, so the gradient has zero row-sum.
Step 4 — value aggregation. gives and (shapes ).
Step 5 — temperature check. If have independent unit-variance entries, , so has variance 1 after dividing by . For the unscaled logit standard deviation would be 8, driving toward overflow / one-hot attention.
Step 6 — causal mask. Adding for future positions makes exactly there; contributes no gradient, so information cannot flow backward from the future either.
10. Proofs and proof intuition
Lemma 1 (softmax shift invariance). for any scalar . Proof. Each component becomes , and cancels. This is why implementations subtract before exponentiating.
Lemma 2 (softmax VJP). With , where . Proof. with . Then . Multiplying by and summing over : .
Lemma 3 (permutation equivariance). Without positional information and masks, for any permutation matrix , . Proof. and similarly for , so scores become . Row-wise softmax commutes with row/column permutation: . Then . Consequence: positional encodings are required to distinguish token order.
Lemma 4 (convex-combination bound). Each output row lies in the convex hull of the value rows. Proof. and , and is exactly such a weighted sum.
11. Geometric interpretation
Each query locates a soft pointer into the sequence: the attention row is a distribution over positions, and is the expected value under that distribution. Geometrically, is a barycentric coordinate combination of value vectors — attention can only interpolate, never extrapolate, beyond their convex hull.
In the matrix , the diagonal corresponds to self-focus, off-diagonal entries to context. Causal attention restricts to a lower triangle; "induction heads" show a characteristic off-diagonal stripe that copies previously seen patterns. Multi-head attention runs such routings in parallel subspaces, letting different heads specialise (e.g. syntactic dependencies, positional copying, delimiter tracking). The scaled dot product is a learned, content-based similarity kernel; softmax turns squared-distance-like scores into a probability simplex.
12. Visual explanation
Use the interactive Attention Heatmap Playground: it displays as an heatmap with tokens on both axes. Hover a cell to see the logit , its softmax weight, and the contribution to the output. Toggle: (i) causal mask — the upper triangle blanks out; (ii) temperature — remove and watch the heatmap collapse to one-hot; (iii) multi-head — switch between heads to see specialised patterns. For the 3-token example below, the unmasked heatmap rows are about , , ; with a causal mask the first row becomes . Overlay the convex hull of the three value vectors to show that all outputs lie inside it.
13. Numerical worked example
Take , , , and (already projected) vectors Unscaled scores give rows , , . After dividing by , the logits are or . Since and :
| Row | Logits | Softmax weights | Output | |---|---|---|---| | | | | | | | | | | | | | | |
Because , token 3 contributes nothing despite weight — attention weights alone do not determine influence; the value magnitude matters too.
Backward check. Suppose . Then and , so whose entries sum to as predicted. Then . A finite-difference check on matches to ~.
Causal mask. Row 1 loses positions 2 and 3: logits , so and — token 1 can only read itself.
14. Real-world analogy
Picture a researcher writing a report with access to a library of note cards (values), each indexed by a topic tag (key). For each sentence they are writing (query), they score every card's relevance, convert those scores into a budget that sums to 100%, and copy a weighted blend of the cards into their draft. The process is content-based (matching topics, not fixed distances), parallel (all sentences can be drafted at once), and soft (many cards contribute). A causal mask is the rule that you may only consult notes written before the current sentence — essential for a fair, no-leakage writing process.
15. Algorithm pseudocode
algorithm ScaledDotProductAttention(X, WQ, WK, WV, causal):
Q <- X @ WQ ; K <- X @ WK ; V <- X @ WV # n x dk, n x dk, n x dv
S <- (Q @ K^T) / sqrt(dk) # n x n logits
if causal: S[i,j] <- -inf for j > i
m[i] <- max_j S[i,j] # subtract row max for stability
E[i,j] <- exp(S[i,j] - m[i]) ; l[i] <- sum_j E[i,j]
A[i,j] <- E[i,j] / l[i] # row-stochastic
Y <- A @ V # n x dv
cache S, A, Q, K, V for backward
return Y, A
# Backward: dV <- A^T @ dY ; dA <- dY @ V^T
# dS <- A * (dA - rowsum(dA * A))
# dQ <- dS @ K / sqrt(dk) ; dK <- dS^T @ Q / sqrt(dk)
16. Implementation from scratch
import numpy as np
def softmax_rows(x):
z = x - x.max(axis=-1, keepdims=True) # shift for numerical stability
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def attention_forward(X, WQ, WK, WV, causal=False):
Q, K, V = X @ WQ, X @ WK, X @ WV
dk = Q.shape[1]
S = Q @ K.T / np.sqrt(dk)
if causal:
S = np.where(np.triu(np.ones_like(S, dtype=bool), 1), -np.inf, S)
A = softmax_rows(S)
return A @ V, (X, Q, K, V, S, A)
def attention_backward(dY, cache, WQ, WK, WV):
X, Q, K, V, S, A = cache
dV = A.T @ dY
dA = dY @ V.T
dS = A * (dA - (dA * A).sum(axis=-1, keepdims=True))
dQ = dS @ K / np.sqrt(Q.shape[1])
dK = dS.T @ Q / np.sqrt(Q.shape[1])
dX = dQ @ WQ.T + dK @ WK.T + dV @ WV.T
dWQ, dWK, dWV = X.T @ dQ, X.T @ dK, X.T @ dV
return dX, (dWQ, dWK, dWV)
X = np.array([[1., 0.], [0., 1.], [1., 1.]]) # toy embeddings
WQ = np.eye(2); WK = np.eye(2); WV = np.eye(2)
Y, cache = attention_forward(X, WQ, WK, WV, causal=False)
print(np.round(Y, 4)) # [[0.4011, 0.1977], [0.1977, 0.4011], [0.3333, 0.3333]]
dY = np.array([[1., 0.], [0., 1.], [0., 0.]])
dX, dW = attention_backward(dY, cache, WQ, WK, WV)
# Gradient check against a central difference of a scalar objective:
def loss(Xp):
Yp, _ = attention_forward(Xp, WQ, WK, WV)
return (Yp * dY).sum()
h = 1e-5
for i in range(X.shape[0]):
for j in range(X.shape[1]):
Xp = X.copy(); Xp[i, j] += h
Xm = X.copy(); Xm[i, j] -= h
fd = (loss(Xp) - loss(Xm)) / (2 * h)
assert abs(fd - dX[i, j]) < 1e-6, (i, j, fd, dX[i, j])
print("gradient check passed")
The cache includes X so the weight gradients X.T @ dQ etc. are available; the finite-difference loop checks every entry of dX to .
17. Professional library implementation
import torch
import torch.nn.functional as F
B, H, N, D = 1, 2, 4, 8 # batch, heads, sequence, d_k = d_v = d_model/H
x = torch.randn(B, N, H * D, requires_grad=True)
q, k, v = x.chunk(3, dim=-1) # in real code: learned W_Q, W_K, W_V projections
q, k, v = [t.view(B, N, H, D).transpose(1, 2) for t in (q, k, v)]
# Fused, memory-efficient exact attention (FlashAttention on CUDA):
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(y.shape) # torch.Size([1, 2, 4, 8])
y.sum().backward()
print(x.grad.shape) # gradients flow through projections too
# Multi-head module used in transformer blocks:
mha = torch.nn.MultiheadAttention(embed_dim=H * D, num_heads=H, batch_first=True)
out, weights = mha(x, x, x, need_weights=True) # weights: softmax matrix (B, N, N)
For inference, use a KV cache so keys/values of past tokens are not recomputed; for long contexts prefer F.scaled_dot_product_attention over a hand-written matrix.
18. Code walkthrough
Scratch version. softmax_rows subtracts the row maximum before exponentiating; mathematically this is a no-op by shift invariance but prevents overflow. attention_forward caches because the backward needs them: softmax derivative needs , and needs . attention_backward implements the four VJPs in reverse order: . Each line corresponds exactly to a formula in section 7.
PyTorch version. F.scaled_dot_product_attention computes the same function but tiles the computation so the matrix is never materialised in HBM (FlashAttention); it also handles the causal mask and dropout. The reshape-transpose pattern (B,N,H,D).transpose(1,2) is required because the fused kernel expects (B,H,N,D); mixing these up is the most common shape bug. need_weights=True materialises for inspection — do not use it in production training because it costs memory.
19. Tensor and memory analysis
The dominant tensor is the score/attention matrix of shape . In fp16 (2 bytes), for , , : per layer if both and are kept (about 2.1 GB). Activations cost only MB. Projections cost parameters (~50 M for , ~100 MB in fp32 with Adam states ~400 MB).
FlashAttention avoids storing and : it keeps running row maxima/sums and the output in SRAM, reducing attention activation memory from to , at the price of extra FLOPs for online softmax rescaling. This is why context length, not parameter count, is the usual memory bottleneck for long-context inference.
20. Time complexity
Per head, costs FLOPs and costs ; with and heads, attention costs . The three projections cost . For , : attention FLOPs, projections FLOPs. Attention dominates once . Backward costs about forward. Linear alternatives reduce the term to but change the function.
21. Space complexity
Naive implementation stores and () plus activations and weights. With FlashAttention the quadratic tensors are never stored: memory is — linear in . During training, checkpointing entire transformer blocks reduces layer activation memory further at ~33% extra compute. For autoregressive decoding, the KV cache stores for all past tokens: per layer, which for 7B models and k can exceed weight memory.
22. Experimental demonstration
Run four experiments. (1) Reproduce the 3-token example in NumPy and compare with F.scaled_dot_product_attention — expect agreement to . (2) Gradient check: perturb one entry of by and compare with the analytic ; relative error should be in float64. (3) Temperature ablation: run with and without for and plot the entropy of attention rows and the gradient norm on a toy task; unscaled attention should collapse toward one-hot with tiny gradients. (4) Scaling: measure peak memory and time for with and without the fused kernel; expect ~ growth in memory and time per doubling of for the naive implementation.
23. Benchmark results
Illustrative measurements (single A100, fp16, , , ): naive PyTorch attention at uses ~2 GB of attention activations and takes tens of milliseconds per layer; FlashAttention reduces attention activation memory to and is reported by Dao et al. (2022) to give 1.5–2.3x end-to-end speedups on GPT-2 training versus a standard implementation. At the difference is small; at it is decisive. Do not treat these numbers as universal — they depend on GPU generation, kernel versions and shape. Always report , , , precision, and whether the matrix was materialised.
24. Limitations
- Quadratic time and memory in sequence length for exact attention.
- No built-in notion of distance or order; positional information must be injected explicitly (absolute, relative, RoPE or ALiBi).
- Permutation equivariant without positions, which is a feature for sets but a limitation for sequences.
- Softmax can saturate, producing near-one-hot attention and vanishing gradients.
- Attention weights are not faithful explanations of model decisions; multiple parameterisations yield identical outputs.
- Many heads learn redundant patterns; pruning often leaves quality intact.
- Exact attention is wasteful for tasks needing only local context.
25. Failure scenarios
- Label leakage: forgetting the causal mask in a decoder lets position read future tokens; validation perplexity looks excellent but generation is nonsense.
- Overflow in fp16: exponentiating unmasked logits can overflow; subtract the row max before
exp. - All-masked row: masking every key in a row makes the softmax denominator zero and produces NaNs that propagate through the whole network.
- Missing scale factor: with unscaled logits have standard deviation ~11, so softmax is effectively one-hot and training stalls.
- Shape/transposition bug: confusing
(B,N,H,D)with(B,H,N,D)silently mixes heads instead of raising an error; unit-test with distinct values per head. - KV-cache mismatch: using a cache built with a different positional offset or head layout yields plausible-looking but wrong continuations.
- OOM at long context: materialising scores for k exceeds GPU memory; use a fused or sparse kernel.
26. Common misconceptions
- "Attention weights explain the model." They are one view of an overparameterised computation; the same output can arise from different attention patterns.
- "Self-attention is permutation invariant." It is permutation equivariant; permuting inputs permutes outputs identically. Positional encodings break the symmetry.
- "Softmax attention chooses one token." It produces a distribution; hard selection is only a limiting case.
- "More heads are always better." Beyond a task-dependent point, heads are redundant or can be unstable.
- "Scaling is only for numerical stability." It is primarily variance normalisation so the softmax temperature does not grow with ; the stability benefit is secondary.
- "Attention replaces recurrence, so order no longer matters." Order must be reintroduced through positions; causal masking is separate from position encoding.
27. Alternative approaches
- Additive (Bahdanau) attention: scores via a learned tanh network, but more expensive per pair.
- Cross-attention: queries from one sequence, keys/values from another (encoder–decoder, retrieval).
- Linear / kernel attention: approximate with feature maps to get .
- Sparse patterns (Longformer, BigBird, Child et al.): local + global/dilated connections, or .
- State-space models / Mamba: recurrent-like mixing with and content-based gating.
- FlashAttention: the same exact function, but IO-aware tiling; an implementation alternative, not a mathematical one.
- RoPE / ALiBi: alternative ways to inject relative position information into scores.
29. Research applications
- Language models: virtually every modern LLM is a stack of causal self-attention + MLP blocks.
- Vision: ViTs treat image patches as tokens; attention maps reveal local/global feature specialisation.
- Protein structure: AlphaFold's Evoformer uses attention over residue and pair representations.
- Retrieval-augmented generation: cross-attention conditions generation on retrieved documents.
- Interpretability: analysing heads for induction, copy and syntactic behaviour; circuit-level tracing.
- Long-context research: sparse/linear attention, memory hierarchies, positional extrapolation (RoPE, ALiBi).
30. Important research papers
- Bahdanau D., Cho K., Bengio Y. (2015), Neural Machine Translation by Jointly Learning to Align and Translate, ICLR.
- Luong M.-T., Pham H., Manning C. D. (2015), Effective Approaches to Attention-based Neural Machine Translation, EMNLP.
- Vaswani A. et al. (2017), Attention Is All You Need, NeurIPS — scaled dot-product attention and the transformer.
- Child R. et al. (2019), Generating Long Sequences with Sparse Transformers, arXiv:1904.10509.
- Dao T., Fu D., Ermon S., Brunskill E., Jabbari S. (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, NeurIPS.
- Su J. et al. (2021), RoFormer: Enhanced Transformer with Rotary Position Embedding, arXiv:2104.09864.
- Press O., Nof A., Bar Asher S., Levy O. (2022), Train Short, Test Long: Attention with Linear Biases, ICLR.
31. Further reading
- Vaswani et al. (2017), arXiv:1706.03762 — the original paper, section 3.2.
- Dao et al. (2022), arXiv:2205.14135 — IO-aware exact attention.
- Illustrate Transformers:jalammar.github.io/illustrated-transformer/ — visual walkthrough.
- PyTorch SDPA docs: docs.pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html.
- Hugging Face "Attention Interfaces" documentation for masked and fused variants.
32. Practical exercises
- Implement
attention_forwardandattention_backwardin NumPy from the formulas; gradient-check every input against finite differences at float64. - Reproduce the 3-token numerical example by hand and in code, including the causal-masked row.
- Implement multi-head attention as a reshape/transpose wrapper around your single-head function; verify shapes for .
- Plot attention entropy versus with and without the scale; explain the trend using variance arguments.
- Train a tiny transformer on a copy task and inspect whether any head develops an induction pattern.
- Benchmark naive vs fused attention at and report peak memory and time.
33. Debugging challenges
- NaNs in attention output: check for all-masked rows or unshifted exponentiation of large logits.
- Attention rows do not sum to 1: you applied softmax over the wrong axis, or forgot to mask before softmax.
- Model can "see the future": the causal mask was built with the wrong triangle or applied to instead of .
- Gradients of are zero: the attention matrix becomes exactly one-hot (missing scale or very large logits).
- Shapes are correct but outputs are garbage: you transposed
(B,N,H,D)incorrectly and mixed heads; test with head-identifying values. - Peak memory jumps at : you materialised and ; switch to the fused kernel.
- Fused and manual attention disagree: check whether dropout, masking conventions or scaling differ.
34. Advanced exercises
- Prove the softmax VJP and permutation-equivariance lemmas from section 10 on paper.
- Implement an online-softmax (FlashAttention-style) forward pass in NumPy using tiling, and verify bit-level closeness to the naive result.
- Derive the gradient with respect to for multi-head attention and implement it.
- Compare RoPE, ALiBi and learned absolute positions on a length-extrapolation task; plot perplexity versus context length.
- Implement linear attention with the feature map and compare its complexity and accuracy to softmax attention.
- Measure which heads are redundant by ablation and quantify the accuracy drop when removing the least important 25%.
35. Interview questions
- Derive the factor from the variance of a dot product.
- Write the shapes of and the backward tensors .
- Why is the softmax applied row-wise, and what would column-wise softmax mean?
- Prove that self-attention is permutation equivariant, and explain why positions must be encoded.
- Derive .
- What is the time and memory complexity of one attention layer, and how does FlashAttention change memory?
- Why would you use a causal mask, and how is it implemented numerically?
- Are attention weights a valid explanation of a prediction? Why or why not?
36. Research questions
- Can exact attention be made subquadratic without sacrificing quality, or is a fundamental expressivity trade-off?
- How do attention heads specialise, and can specialisation be predicted from initialization?
- What is the role of softmax saturation in the "attention collapse" observed in some deep models?
- How should positional information be represented to extrapolate beyond training context length?
- Can attention maps give causally valid explanations, or only correlational ones?
- How does KV-cache quantisation affect long-context generation quality and what error bounds can be proved?
37. Mastery assessment
To pass: (1) write the attention equation and derive the scale factor from variance; (2) hand-compute the 3-token example including softmax weights and one backward step; (3) implement forward and backward from scratch and gradient-check to ; (4) prove permutation equivariance and the softmax VJP; (5) state time/memory complexity and explain what FlashAttention changes; (6) diagnose leakage, saturation, all-masked rows and shape bugs. Complete the linked assessment; reading the page is not mastery.
38. Implementation submission
Push a repository with attention.py (NumPy forward/backward), tests/test_gradcheck.py (finite differences at float64), experiments.ipynb (3-token reproduction, temperature ablation, -scaling with naive vs fused attention, entropy plots), and a README.md containing the derivations of the softmax VJP and equivariance lemma plus a table of measured memory/time. Include the exact reproduction command and note any discrepancy between manual and PyTorch results.
39. Completion criteria
All of: the forward and backward equations derived and the worked numbers reproduced on paper; scratch implementation gradient-checked; multi-head version implemented with correct shapes; causal masking verified to prevent leakage; scaling experiment with recorded numbers; assessment score at least 80%; one failure case reproduced and one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`