concept / self-attention
Next task →
University/Generative AI/Transformer architecture/Scaled Dot-Product Self-Attention
Generative AI and LLMs · Transformer architecture · Attention mechanisms

Scaled Dot-Product Self-Attention

Scaled dot-product self-attention maps each token to queries, keys and values, computes softmax of QK⊤/dkQK^\top/\sqrt{d_k}, and returns a convex combination of values — a content-based, permutation-equivariant routing layer with O(n2d)O(n^2d) cost.

39 sectionsadvanced210 minhand-authored · structural 82/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

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 X∈Rn×dmodelX\in\mathbb{R}^{n\times d_{\text{model}}} (nn tokens, model width dmodeld_{\text{model}}), three learned linear maps produce

Q=XWQ,K=XWK,V=XWV,Q=XW_Q,\quad K=XW_K,\quad V=XW_V,

with WQ,WK∈Rdmodel×dkW_Q,W_K\in\mathbb{R}^{d_{\text{model}}\times d_k} and WV∈Rdmodel×dvW_V\in\mathbb{R}^{d_{\text{model}}\times d_v}. The layer output is

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

where softmax is applied row-wise over keys. Row ii of the softmax matrix A∈Rn×nA\in\mathbb{R}^{n\times n} gives the mixture weights with which token ii reads the value vectors; output row ii is yi=∑jAijvjy_i=\sum_j A_{ij}v_j.

The name "self"-attention distinguishes it from encoder–decoder cross-attention: queries, keys and values all come from the same sequence. The factor dk\sqrt{d_k} 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 nn 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 n×nn\times n routing matrix is expressive and hardware-friendly.

The price is quadratic cost in sequence length: O(n2d)O(n^2 d) 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 n2n^2 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 QQ and KK. The 2020s LLM wave is a direct continuation of this line.

4. Fundamental problem

For each query position ii, compute a distribution over nn keys that reflects how relevant each key is to that query, and use it to aggregate values — doing this for all ii simultaneously, differentiably, and with shapes that stay manageable.

Three design questions must be answered:

  1. Score: how to measure query–key compatibility? A dot product qi⊤kjq_i^\top k_j is cheap and, after learned projections, expressive.
  2. Normalisation: convert arbitrary real scores into nonnegative weights summing to 1 — softmax with temperature 1/dk1/\sqrt{d_k}.
  3. Scale: dot-product variance grows with dimension, so unnormalised scores can push softmax into saturation; divide by dk\sqrt{d_k}.

A fourth issue is crucial in generative models: without masking, position ii could read position j>ij>i, leaking the future. A causal mask sets those logits to −∞-\infty.

5. First-principles explanation

Fact 1 (dot product as similarity). For vectors q,kq,k with i.i.d. zero-mean unit-variance components, E[q⊤k]=0\mathbb{E}[q^\top k]=0 and Var(q⊤k)=dk\mathrm{Var}(q^\top k)=d_k. Thus the score magnitude grows as dk\sqrt{d_k} with dimensionality even when tokens are unrelated; the content signal is buried in scale. Dividing by dk\sqrt{d_k} restores unit variance and makes the softmax temperature independent of dkd_k.

Fact 2 (softmax as soft argmax). Row-wise softmax Aij=eSij/∑meSimA_{ij}=e^{S_{ij}}/\sum_m e^{S_{im}} maps logits to a simplex. It is differentiable, shift-invariant (A(z+c1)=A(z)A(z+c\mathbf{1})=A(z)), and becomes sharply peaked as logit gaps grow. Sharpness controls the gradient signal: if one logit dominates by ≫1\gg1, ∂Aij/∂Sik≈0\partial A_{ij}/\partial S_{ik}\approx0 and learning stalls.

Fact 3 (weighted average). yi=∑jAijvjy_i=\sum_j A_{ij}v_j is a convex combination of value rows, so yiy_i 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 X∈Rn×dmodelX\in\mathbb{R}^{n\times d_{\text{model}}}:

Q=XWQ∈Rn×dk,K=XWK∈Rn×dk,V=XWV∈Rn×dv.Q=XW_Q\in\mathbb{R}^{n\times d_k},\quad K=XW_K\in\mathbb{R}^{n\times d_k},\quad V=XW_V\in\mathbb{R}^{n\times d_v}. S=QK⊤dk∈Rn×n,A=softmaxrow(S),Y=AV∈Rn×dv.S=\frac{QK^\top}{\sqrt{d_k}}\in\mathbb{R}^{n\times n},\qquad A=\mathrm{softmax}_{\text{row}}(S),\qquad Y=AV\in\mathbb{R}^{n\times d_v}.

Explicitly, Aij=exp⁡(Sij)∑m=1nexp⁡(Sim)A_{ij}=\dfrac{\exp(S_{ij})}{\sum_{m=1}^{n}\exp(S_{im})} and yi=∑jAijvjy_i=\sum_j A_{ij}v_j.

Causal mask (decoder). Replace Sij←−∞S_{ij}\leftarrow-\infty for j>ij>i; then AA is lower-triangular and each row sums to 1 over j≤ij\le i.

Multi-head. For hh heads with dk=dv=dmodel/hd_k=d_v=d_{\text{model}}/h:

headt=Attention(XWQ(t),XWK(t),XWV(t)),MHA(X)=concat(head1,…,headh)WO.\mathrm{head}_t=\mathrm{Attention}(XW_Q^{(t)},XW_K^{(t)},XW_V^{(t)}),\qquad \mathrm{MHA}(X)=\mathrm{concat}(\mathrm{head}_1,\dots,\mathrm{head}_h)W_O .

Backward formulas. Given upstream dYdY, with dv=dkd_v=d_k for simplicity:

dV=A⊤dY,dA=dYV⊤,dS=A⊙(dA−rowsum(dA⊙A)),dV=A^\top dY,\quad dA=dY V^\top,\quad dS=A\odot\big(dA-\text{rowsum}(dA\odot A)\big), dQ=1dkdS K,dK=1dkdS⊤Q,dX=dQWQ⊤+dKWK⊤+dVWV⊤.dQ=\tfrac{1}{\sqrt{d_k}}dS\,K,\quad dK=\tfrac{1}{\sqrt{d_k}}dS^\top Q,\quad dX=dQW_Q^\top+dKW_K^\top+dVW_V^\top .

8. Notation dictionary

| Symbol | Meaning | Shape / type | |---|---|---| | nn | sequence length (tokens) | integer | | dmodeld_{\text{model}} | model / embedding width | integer | | dk,dvd_k,d_v | per-head key/query and value dimension | integers | | hh | number of attention heads | integer | | XX | input token representations | n×dmodeln\times d_{\text{model}} | | Q,K,VQ,K,V | queries, keys, values | n×dkn\times d_k, n×dkn\times d_k, n×dvn\times d_v | | WQ,WK,WV,WOW_Q,W_K,W_V,W_O | learned projection matrices | dmodel×dkd_{\text{model}}\times d_k etc. | | S=QK⊤/dkS=QK^\top/\sqrt{d_k} | scaled logits (scores) | n×nn\times n | | AA | row-stochastic attention matrix | n×nn\times n | | MM | causal mask (Mij=−∞M_{ij}=-\infty if j>ij>i) | n×nn\times n | | YY | output | n×dvn\times d_v | | dY,dS,…dY,dS,\dots | upstream gradients / adjoints | same shape as forward tensor | | ⊙\odot | elementwise (Hadamard) product | operator |

9. Step-by-step derivation

Step 1 — projections. Q=XWQQ=XW_Q etc. are affine maps; their backward is a matrix multiply by W⊤W^\top, and the weight gradients are X⊤dQX^\top dQ, etc.

Step 2 — scores. Sij=qi⊤kj/dkS_{ij}=q_i^\top k_j/\sqrt{d_k}. Differentiating: dSdS accumulates into dQ=dSK/dkdQ=dS K/\sqrt{d_k} and dK=dS⊤Q/dkdK=dS^\top Q/\sqrt{d_k} (check shapes: (n×n)(n×dk)→n×dk(n\times n)(n\times d_k)\to n\times d_k).

Step 3 — softmax Jacobian. For one row ss, a=softmax(s)a=\mathrm{softmax}(s) has Jacobian J=diag(a)−aa⊤J=\mathrm{diag}(a)-aa^\top. Therefore, for upstream row dada:

ds=J⊤da=a⊙da−a(a⊤da)=a⊙(da−∑mamdam).ds=J^\top da=a\odot da-a(a^\top da)=a\odot\big(da-\textstyle\sum_m a_m da_m\big).

Vectorised over rows: dS=A⊙(dA−rowsum(dA⊙A))dS=A\odot(dA-\mathrm{rowsum}(dA\odot A)). Note ∑jdSij=0\sum_j dS_{ij}=0 — softmax is invariant to adding a constant to a row, so the gradient has zero row-sum.

Step 4 — value aggregation. Y=AVY=AV gives dV=A⊤dYdV=A^\top dY and dA=dYV⊤dA=dYV^\top (shapes (n×dv)(dv×n)→n×n(n\times d_v)(d_v\times n)\to n\times n).

Step 5 — temperature check. If qi,kjq_i,k_j have independent unit-variance entries, Var(qi⊤kj)=dk\mathrm{Var}(q_i^\top k_j)=d_k, so SijS_{ij} has variance 1 after dividing by dk\sqrt{d_k}. For dk=64d_k=64 the unscaled logit standard deviation would be 8, driving exp⁡\exp toward overflow / one-hot attention.

Step 6 — causal mask. Adding Mij=−∞M_{ij}=-\infty for future positions makes Aij=0A_{ij}=0 exactly there; −∞-\infty contributes no gradient, so information cannot flow backward from the future either.

10. Proofs and proof intuition

Lemma 1 (softmax shift invariance). softmax(s+c1)=softmax(s)\mathrm{softmax}(s+c\mathbf{1})=\mathrm{softmax}(s) for any scalar cc. Proof. Each component becomes esi+c/∑mesm+c=ecesi/(ec∑mesm)e^{s_i+c}/\sum_m e^{s_m+c}=e^c e^{s_i}/(e^c\sum_m e^{s_m}), and ece^c cancels. □\square This is why implementations subtract max⁡jsj\max_j s_j before exponentiating.

Lemma 2 (softmax VJP). With a=softmax(s)a=\mathrm{softmax}(s), ∂L∂s=a⊙(da−⟨a,da⟩1)\frac{\partial L}{\partial s}=a\odot(da-\langle a,da\rangle\mathbf{1}) where da=∂L/∂ada=\partial L/\partial a. Proof. ai=esi/Za_i=e^{s_i}/Z with Z=∑mesmZ=\sum_m e^{s_m}. Then ∂ai/∂sj=aiδij−aiaj\partial a_i/\partial s_j=a_i\delta_{ij}-a_i a_j. Multiplying by daida_i and summing over ii: dsj=ajdaj−aj∑iaidaids_j=a_j da_j-a_j\sum_i a_i da_i. □\square

Lemma 3 (permutation equivariance). Without positional information and masks, for any permutation matrix Π\Pi, Attention(ΠX)=Π Attention(X)\mathrm{Attention}(\Pi X)=\Pi\,\mathrm{Attention}(X). Proof. ΠXWQ=ΠQ\Pi XW_Q=\Pi Q and similarly for K,VK,V, so scores become (ΠQ)(ΠK)⊤/dk=ΠQK⊤Π⊤=ΠSΠ⊤(\Pi Q)(\Pi K)^\top/\sqrt{d_k}=\Pi QK^\top\Pi^\top=\Pi S\Pi^\top. Row-wise softmax commutes with row/column permutation: A′=ΠAΠ⊤A'=\Pi A\Pi^\top. Then A′(ΠV)=ΠAΠ⊤ΠV=ΠAVA'(\Pi V)=\Pi A\Pi^\top\Pi V=\Pi AV. □\square Consequence: positional encodings are required to distinguish token order.

Lemma 4 (convex-combination bound). Each output row yiy_i lies in the convex hull of the value rows. Proof. Aij≥0A_{ij}\ge0 and ∑jAij=1\sum_j A_{ij}=1, and yiy_i is exactly such a weighted sum. □\square

11. Geometric interpretation

Each query locates a soft pointer into the sequence: the attention row AiA_i is a distribution over positions, and yiy_i is the expected value under that distribution. Geometrically, yiy_i is a barycentric coordinate combination of value vectors — attention can only interpolate, never extrapolate, beyond their convex hull.

In the n×nn\times n matrix AA, 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 hh 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 AA as an n×nn\times n heatmap with tokens on both axes. Hover a cell (i,j)(i,j) to see the logit SijS_{ij}, its softmax weight, and the contribution AijvjA_{ij}v_j to the output. Toggle: (i) causal mask — the upper triangle blanks out; (ii) temperature — remove dk\sqrt{d_k} 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 (0.40,0.20,0.40)(0.40,0.20,0.40), (0.20,0.40,0.20)(0.20,0.40,0.20), (0.33,0.33,0.33)(0.33,0.33,0.33); with a causal mask the first row becomes (1,0,0)(1,0,0). Overlay the convex hull of the three value vectors to show that all outputs lie inside it.

13. Numerical worked example

Take n=3n=3, dk=dv=2d_k=d_v=2, dk=1.4142\sqrt{d_k}=1.4142, and (already projected) vectors q1=(1,0), q2=(0,1), q3=(1,1),k1=(1,0), k2=(0,1), k3=(1,0),q_1=(1,0),\ q_2=(0,1),\ q_3=(1,1),\qquad k_1=(1,0),\ k_2=(0,1),\ k_3=(1,0), v1=(1,0), v2=(0,1), v3=(0,0).v_1=(1,0),\ v_2=(0,1),\ v_3=(0,0). Unscaled scores qi⋅kjq_i\cdot k_j give rows (1,0,1)(1,0,1), (0,1,0)(0,1,0), (1,1,1)(1,1,1). After dividing by 1.41421.4142, the logits are 0.70710.7071 or 00. Since e0.7071=2.0281e^{0.7071}=2.0281 and e0=1e^0=1:

| Row | Logits | Softmax weights | Output yi=∑jAijvjy_i=\sum_j A_{ij}v_j | |---|---|---|---| | i=1i=1 | (0.7071,0,0.7071)(0.7071,0,0.7071) | (0.4011,0.1977,0.4011)(0.4011,0.1977,0.4011) | (0.4011,0.1977)(0.4011,0.1977) | | i=2i=2 | (0,0.7071,0)(0,0.7071,0) | (0.1977,0.4011,0.1977)(0.1977,0.4011,0.1977) | (0.1977,0.4011)(0.1977,0.4011) | | i=3i=3 | (0.7071,0.7071,0.7071)(0.7071,0.7071,0.7071) | (1/3,1/3,1/3)(1/3,1/3,1/3) | (1/3,1/3)(1/3,1/3) |

Because v3=(0,0)v_3=(0,0), token 3 contributes nothing despite weight 0.40110.4011 — attention weights alone do not determine influence; the value magnitude matters too.

Backward check. Suppose dY1=(1,0)dY_1=(1,0). Then dA1=dY1V⊤=(1,0,0)dA_1=dY_1V^\top=(1,0,0) and ∑jA1jdA1j=0.4011\sum_j A_{1j}dA_{1j}=0.4011, so dS1=A1⊙((1,0,0)−0.4011)=(0.2402,−0.0793,−0.1609),dS_1=A_1\odot\big((1,0,0)-0.4011\big)=(0.2402,-0.0793,-0.1609), whose entries sum to 00 as predicted. Then dQ1=(1/2)dS1K=(0.7071)(0.0793,−0.0793)=(0.0561,−0.0561)dQ_1=(1/\sqrt2)dS_1K=(0.7071)(0.0793,-0.0793)=(0.0561,-0.0561). A finite-difference check on y1y_1 matches to ~10−610^{-6}.

Causal mask. Row 1 loses positions 2 and 3: logits (0.7071,−∞,−∞)(0.7071,-\infty,-\infty), so A1=(1,0,0)A_1=(1,0,0) and y1=v1=(1,0)y_1=v_1=(1,0) — 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 10−610^{-6}.

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 n×nn\times n 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 Q,K,V,S,AQ,K,V,S,A because the backward needs them: softmax derivative needs AA, and dKdK needs QQ. attention_backward implements the four VJPs in reverse order: Y→A→S→Q,K,V→XY\to A\to S\to Q,K,V\to X. 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 n×nn\times n 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 AA for inspection — do not use it in production training because it costs O(n2)O(n^2) memory.

19. Tensor and memory analysis

The dominant tensor is the score/attention matrix of shape B×h×n×nB\times h\times n\times n. In fp16 (2 bytes), for B=1B=1, h=32h=32, n=4096n=4096: 1⋅32⋅40962⋅2 bytes=32⋅16,777,216⋅2≈1.07×109 bytes≈1.07 GB1\cdot32\cdot4096^2\cdot2\ \text{bytes}=32\cdot16{,}777{,}216\cdot2\approx1.07\times10^9\ \text{bytes}\approx1.07\ \text{GB} per layer if both SS and AA are kept (about 2.1 GB). Activations Q,K,V,YQ,K,V,Y cost only 4⋅Bndmodel⋅2≈644\cdot B n d_{\text{model}}\cdot2\approx64 MB. Projections cost 3dmodel23d_{\text{model}}^2 parameters (~50 M for d=4096d=4096, ~100 MB in fp32 with Adam states ~400 MB).

FlashAttention avoids storing SS and AA: it keeps running row maxima/sums and the output in SRAM, reducing attention activation memory from O(n2)O(n^2) to O(n)O(n), 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, QK opQK^\ op costs 2n2dk2n^2d_k FLOPs and AVAV costs 2n2dv2n^2d_v; with dk=dv=d extmodel/hd_k=d_v=d_{\ ext{model}}/h and hh heads, attention costs ≈4n2d extmodel\approx4n^2d_{\ ext{model}}. The three projections cost ≈6nd extmodel2\approx6nd_{\ ext{model}}^2. For n=2048n=2048, d extmodel=2048d_{\ ext{model}}=2048: attention ≈4(2048)2(2048)≈3.4 imes1010\approx4(2048)^2(2048)\approx3.4\ imes10^{10} FLOPs, projections ≈6(2048)(2048)2≈5.2 imes1010\approx6(2048)(2048)^2\approx5.2\ imes10^{10} FLOPs. Attention dominates once n> frac32d extmodeln>\ frac32 d_{\ ext{model}}. Backward costs about 2 imes2\ imes forward. Linear alternatives reduce the n2n^2 term to O(nd2)O(n d^2) but change the function.

21. Space complexity

Naive implementation stores SS and AA (O(Bhn2)O(Bhn^2)) plus O(Bndmodel)O(Bnd_{\text{model}}) activations and O(dmodel2)O(d_{\text{model}}^2) weights. With FlashAttention the quadratic tensors are never stored: memory is O(Bndmodel+Bhn)O(Bnd_{\text{model}}+Bhn) — linear in nn. During training, checkpointing entire transformer blocks reduces layer activation memory further at ~33% extra compute. For autoregressive decoding, the KV cache stores K,VK,V for all past tokens: O(Bhndk)O(B h n d_k) per layer, which for 7B models and n=32n=32k 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 10−610^{-6}. (2) Gradient check: perturb one entry of QQ by h=10−4h=10^{-4} and compare (L(Q+h)−L(Q−h))/(2h)(L(Q+h)-L(Q-h))/(2h) with the analytic dQdQ; relative error should be <10−5<10^{-5} in float64. (3) Temperature ablation: run with and without 1/dk1/\sqrt{d_k} for dk=64d_k=64 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 n=512,1024,2048,4096n=512,1024,2048,4096 with and without the fused kernel; expect ~4×4\times growth in memory and time per doubling of nn for the naive implementation.

23. Benchmark results

Illustrative measurements (single A100, fp16, h=16h=16, dk=64d_k=64, B=1B=1): naive PyTorch attention at n=4096n=4096 uses ~2 GB of attention activations and takes tens of milliseconds per layer; FlashAttention reduces attention activation memory to O(n)O(n) 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 n=512n=512 the difference is small; at n=4096n=4096 it is decisive. Do not treat these numbers as universal — they depend on GPU generation, kernel versions and shape. Always report nn, hh, dkd_k, precision, and whether the n2n^2 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 O(n2)O(n^2) attention is wasteful for tasks needing only local context.

25. Failure scenarios

  1. Label leakage: forgetting the causal mask in a decoder lets position ii read future tokens; validation perplexity looks excellent but generation is nonsense.
  2. Overflow in fp16: exponentiating unmasked logits can overflow; subtract the row max before exp.
  3. All-masked row: masking every key in a row makes the softmax denominator zero and produces NaNs that propagate through the whole network.
  4. Missing scale factor: with dk=128d_k=128 unscaled logits have standard deviation ~11, so softmax is effectively one-hot and training stalls.
  5. 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.
  6. KV-cache mismatch: using a cache built with a different positional offset or head layout yields plausible-looking but wrong continuations.
  7. OOM at long context: materialising Bhn2Bhn^2 scores for n=32n=32k 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 dkd_k; 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, O(n2d)O(n^2 d) but more expensive per pair.
  • Cross-attention: queries from one sequence, keys/values from another (encoder–decoder, retrieval).
  • Linear / kernel attention: approximate exp⁡(q⋅k)\exp(q\cdot k) with feature maps to get O(nd2)O(n d^2).
  • Sparse patterns (Longformer, BigBird, Child et al.): local + global/dilated connections, O(nn)O(n\sqrt n) or O(n)O(n).
  • State-space models / Mamba: recurrent-like mixing with O(nd)O(n d) 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

  1. Implement attention_forward and attention_backward in NumPy from the formulas; gradient-check every input against finite differences at float64.
  2. Reproduce the 3-token numerical example by hand and in code, including the causal-masked row.
  3. Implement multi-head attention as a reshape/transpose wrapper around your single-head function; verify shapes for B=2,h=4,n=5,dmodel=16B=2,h=4,n=5,d_{\text{model}}=16.
  4. Plot attention entropy versus dkd_k with and without the 1/dk1/\sqrt{d_k} scale; explain the trend using variance arguments.
  5. Train a tiny transformer on a copy task and inspect whether any head develops an induction pattern.
  6. Benchmark naive vs fused attention at n=512,1024,2048n=512,1024,2048 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 VV instead of SS.
  • Gradients of QQ 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 n=4096n=4096: you materialised SS and AA; switch to the fused kernel.
  • Fused and manual attention disagree: check whether dropout, masking conventions or scaling differ.

34. Advanced exercises

  1. Prove the softmax VJP and permutation-equivariance lemmas from section 10 on paper.
  2. Implement an online-softmax (FlashAttention-style) forward pass in NumPy using tiling, and verify bit-level closeness to the naive result.
  3. Derive the gradient with respect to WQ,WK,WVW_Q,W_K,W_V for multi-head attention and implement it.
  4. Compare RoPE, ALiBi and learned absolute positions on a length-extrapolation task; plot perplexity versus context length.
  5. Implement linear attention with the feature map ϕ(x)=elu(x)+1\phi(x)=\mathrm{elu}(x)+1 and compare its complexity and accuracy to softmax attention.
  6. Measure which heads are redundant by ablation and quantify the accuracy drop when removing the least important 25%.

35. Interview questions

  • Derive the 1/dk1/\sqrt{d_k} factor from the variance of a dot product.
  • Write the shapes of Q,K,V,S,A,YQ,K,V,S,A,Y and the backward tensors dQ,dK,dV,dS,dAdQ,dK,dV,dS,dA.
  • 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 dS=A⊙(dA−rowsum(dA⊙A))dS=A\odot(dA-\mathrm{rowsum}(dA\odot A)).
  • 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 n2n^2 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 10−510^{-5}; (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, nn-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.`

Research papers linked to this concept