Attention & Transformers
Attention replaces fixed wiring with content-based routing: every position reads from every other through a soft, learned dot-product lookup. We derive scaled dot-product attention and its correction, build it into multi-head self-attention, inject order with positional encodings, and stack the whole thing into the Transformer block that displaced recurrence and convolution alike.
╌╌╌╌
A recurrent network reads a sequence one step at a time, squeezing the entire past into a single hidden state . That bottleneck is the defect: information from position reaches position only after sequential hops, and the gradient connecting them decays along the way: the very problem LSTMs and GRUs only partially patch. Attention removes the hops entirely. Instead of routing information through a chain, every position reads directly from every other position in one step, weighting what it reads by learned, content-dependent relevance.1
Queries, keys, and values
The vocabulary is borrowed from retrieval. A query is what a position is looking for; a key advertises what each position offers; a value is the content actually returned. All three are linear projections of the inputs, so the mechanism is fully learned: three weight matrices determine what each token searches for, what it exposes for matching, and what content it returns.
| Object | Symbol | Shape | Role |
|---|---|---|---|
| Query | what this position is searching for | ||
| Key | what each position offers for matching | ||
| Value | the content returned when a key matches | ||
| Score | scalar | raw compatibility of the query with key | |
| Weight | scalar in | softmax-normalized score, |
Compatibility is measured by a dot product: is large when the query and key point the same way. Normalizing the scores with a softmax turns them into a probability distribution over positions, and the output is the expectation of the values under that distribution,
Scaled dot-product attention
Stack the queries into the rows of , the keys into the rows of , and the values into the rows of . Keeping the query count and the key/value count separate matters: in self-attention , but in cross-attention a decoder of length reads an encoder of length . Queries and keys must share a width so their dot product is defined; values carry an independent width . The shapes chain as follows.
Every query-key score is a single matrix product : entry is the dot product of query with key . Divide by , run a softmax along each row so that row becomes a probability distribution over the keys, and right-multiply by . The inner dimension cancels in , so an weight matrix times an value matrix returns an output — one -vector per query, exactly the input query count. The whole operation collapses to one expression.
The only unexplained piece is the factor. It is essential: without it the softmax saturates and gradients vanish.2
Why the scaling
Treat the entries of a query and a key as independent random variables with mean and variance . The dot product is a sum of such products, and we can compute the variance of that sum exactly.
So the raw scores have standard deviation , which grows with the model dimension. Feed scores of magnitude into a softmax and, for in the hundreds, the largest entry dwarfs the rest: the softmax saturates onto one position, approaching a one-hot vector. In that regime its Jacobian is nearly zero, and almost no gradient flows back to the queries and keys. Dividing by rescales the scores to unit variance, , keeping the softmax in its sensitive, high-gradient region regardless of dimension.
- 1raw scores
- 2unit-variance correction
- 3if masked thendecoder self-attention
- 4for each with do
- 5forbid attending to the future
- 6for each row do
- 7weights sum to
- 8returnblend the values
A worked example
Push numbers through the formula. Take three tokens with , and, to keep the arithmetic legible, let the queries and keys coincide, so this is self-attention:
Step 1 — raw scores . Each entry is . Row is query dotted against the three keys: , , . Filling in all nine,
Step 2 — scale by . Every score shrinks by the same factor, pulling the logits toward zero before the softmax:
Step 3 — row-wise softmax. Work row explicitly. Exponentiate: , , , summing to . Dividing gives for the first and third keys and for the second. Doing the same to every row,
and each row sums to , as a distribution over the three keys must. Notice the third token — whose query aligns with every key — spreads its weight most evenly but still favours itself (key , weight ), because is the largest score in that row.
Step 4 — blend the values, . Row of the output is . All three outputs:
Each output row is a point inside the triangle spanned by the three value vectors — a convex combination, never an extrapolation beyond them. That is the geometric signature of attention: the output can only ever be a weighted average of the values it was given.
Self-attention
When the queries, keys, and values are all linear projections of the same sequence , attention becomes self-attention: each position attends to every other position in its own input, including itself.
Its central object is the attention matrix
a row-stochastic matrix () that is a soft, content-based,
all-pairs routing table: row says where token gathers its information.
Unlike a convolution's fixed local stencil or a recurrence's strictly leftward
chain, every entry is non-zero and learned from content: the word it
can
route directly to the noun it refers to, however far back.
Permutation equivariance
Self-attention has no notion of order. Permuting the rows of permutes the rows of the output identically and changes nothing else; the mechanism treats its input as a set, not a sequence.
Equivariance renders position invisible: dog bites man
and man bites dog
produce the same set of outputs, merely reordered. Order
must therefore be injected explicitly, the job of positional encoding below.
Multi-head attention
A single attention function forces every position to mix all of its relationships into one set of weights. Multi-head attention runs attention functions in parallel, each with its own projections, so different heads can specialize: one tracking syntactic agreement, another long-range coreference, another local adjacency.3
The shapes are worth tracing once. Fix and heads, and set the per-head width (so heads of a model each work in dimensions). For head the projections are , so from an input ,
each head returns an block. Concatenating the blocks along the width rebuilds a full matrix, which mixes back into the model width:
Because , the total projection and attention cost is the same as one full-width head; heads split the width rather than add to it. The expressive gain is that the model holds distinct routing tables at once instead of averaging them into one — one head can lock onto the previous token while another tracks long-range coreference, and learns how to combine their outputs.
Positional encoding
Because self-attention is permutation-equivariant, the model cannot tell position from position unless we tell it. The fix is to add a position-dependent vector to each input embedding before the first layer, so that order rides along in the representation itself.4
The geometric spread of frequencies is the key property: low-index dimensions oscillate quickly to distinguish neighbors, high-index dimensions oscillate slowly to distinguish distant regions. The encoding also admits relative shifts, since is a fixed linear function of , so the model can learn to attend by offset, not just absolute index.
Learned positional embeddings — a trainable lookup table indexed by position — are the common alternative; they fit the data more tightly but, unlike the sinusoids, do not extrapolate to sequences longer than those seen in training.
| Scheme | Form | Generalizes past training length? | Cost |
|---|---|---|---|
| Sinusoidal | fixed of position | yes (deterministic for any ) | none |
| Learned | trainable table | no (undefined for ) | params |
| Relative | bias on scores by offset | yes | per-head bias |
The Transformer block
Self-attention mixes information across positions; it does no nonlinear processing within a position. The Transformer block pairs the two: a multi-head self-attention sublayer followed by a position-wise feed-forward network, each sublayer wrapped in a residual connection and layer normalization.5
Each sublayer is wrapped identically, . The residual skip lets gradients reach early layers undiminished — the same mechanism that powers residual networks — and LayerNorm holds each position's activations at a stable scale across depth.
Encoder and decoder
The original Transformer is an encoder-decoder. The encoder stacks identical blocks with unrestricted self-attention — every position sees every other. The decoder adds two twists that make it a valid autoregressive generator.
| Component | Self-attention | Cross-attention | Sees the future? |
|---|---|---|---|
| Encoder block | full (all-pairs) | — | yes (whole input visible) |
| Decoder block | masked | attends to encoder output | no (causal mask) |
- Masked self-attention. To generate token using only tokens , the decoder sets for before the softmax (the masking branch of the algorithm above), forcing on the future. Generation stays causal.
- Cross-attention. A second attention sublayer takes its queries from the decoder but its keys and values from the encoder's output, letting each generated token read the entire source sequence — the channel through which a translation model reads the sentence it is translating.
Cross-attention is the setting where the shapes matter. In an encoder of length and a decoder generating length , the decoder supplies while the encoder supplies , so the score matrix is a rectangular lookup — every output position against every source position. Self-attention is the special case from one sequence, giving the square matrix; cross-attention keeps queries and keys from different sequences.
The causal mask
The mask is a single additive matrix applied to the scaled scores before the softmax: for and for . Adding to a logit sends , so the softmax assigns those future positions weight exactly — the reason for the rather than merely a large negative number. For four tokens,
leaving a lower-triangular weight matrix: token attends only to tokens . The mask costs nothing at training time (one addition), yet it is what lets the decoder train on a whole target sequence in parallel while still predicting each token from its prefix alone.
Recurrence vs. convolution vs. self-attention
Why did attention displace both recurrence and convolution for sequences? Compare the three on the costs that matter: how far information must travel to connect two positions (maximum path length, which bounds how easily long-range gradients flow), how much of the work is inherently sequential, and the per-layer compute.
| Layer type | Per-layer complexity | Sequential ops | Max path length |
|---|---|---|---|
| Recurrent | |||
| Convolutional (kernel ) | |||
| Self-attention |
Two columns decide it. Self-attention's maximum path length is : any two positions interact directly, so the gradient between them never has to pass through a long chain. Its sequential depth is , so the whole layer parallelizes across positions on a GPU, unlike the strictly stepwise recurrence. The price is the term: the attention matrix is quadratic in sequence length, cheap when (the usual regime) but the dominant cost for long sequences, the bottleneck that later efficient-attention variants attack.
Where attention came from
Attention postdates Goodfellow's 2016 text, so the primary sources carry the detail Goodfellow cannot.
- Where attention came from. The dot-product form here is the streamlined
version. The idea started as additive attention (Bahdanau et al., ICLR 2015),
which scored a query against each key with a small MLP, , to let a translation decoder read every encoder
state instead of one fixed vector. Vaswani et al.,
Attention Is All You Need
(NeurIPS 2017), replaced the MLP with the cheap scaled dot product, added the correction derived above, and removed recurrence entirely. - Reducing the cost. The quadratic score matrix is the target of a whole line of work. Two directions matter. Sparse and linear approximations — Longformer (Beltagy et al., 2020) with sliding-window attention, and the Performer/linear-attention family — reduce the asymptotic cost to or by never forming the full matrix. Exact but IO-aware kernels — FlashAttention (Dao et al., NeurIPS 2022) — keep the exact softmax but tile the computation so the matrix never leaves fast on-chip memory, cutting the memory footprint from to with no change to the result. The second approach is now the default in production Transformers.
- Relative and rotary position. The additive sinusoidal encoding is only the first of several schemes. Shaw et al. (2018) added learned relative-position biases inside the scores; RoPE (Su et al., 2021) rotates the query and key vectors by an angle proportional to position, so a dot product depends only on the relative offset — the standard choice in modern decoder-only LLMs.
The full architecture built from this mechanism — the stacked encoder–decoder, causal masking, and the parameter/compute accounting — is the subject of the next lesson.
Takeaways
- Attention is a differentiable soft lookup: a query scores a set of keys, a softmax turns the scores into weights, and the output is the weighted blend of the values, .
- The scaling cancels the dot product's variance growth (), keeping the softmax out of its saturated, zero-gradient regime.
- Self-attention ( from one sequence) yields an all-pairs routing matrix ; being permutation-equivariant, it needs positional encoding — sinusoidal or learned — to know order.
- Multi-head attention runs parallel attentions in -dimensional subspaces, capturing several relationship patterns at once for the cost of one.
- The Transformer block = multi-head self-attention + position-wise FFN, each in a residual + LayerNorm wrapper; decoders add a causal mask and cross-attention.
- Against recurrence and convolution, self-attention wins on path length () and parallelism ( sequential ops), paying an per-layer cost — the trade that made it the dominant sequence architecture.
Footnotes
- Goodfellow, Deep Learning, §10.11 — Explicit Memory & attention over memory cells: content-based addressing as a differentiable soft lookup (the Transformer itself postdates the 2016 text). ↩
- Chollet, Deep Learning with Python, Ch. 11 — Deep Learning for Text: scaled dot-product attention, the correction, and the
softmax(QK^T/\sqrt{d_k})Vcore of the Transformer. ↩ - Chollet, Deep Learning with Python, Ch. 11 — Multi-Head Attention: parallel attention functions in -dimensional subspaces, concatenated and projected by . ↩
- Chollet, Deep Learning with Python, Ch. 11 — Positional encoding: injecting order into a permutation-equivariant model, sinusoidal versus learned embeddings. ↩
- Chollet, Deep Learning with Python, Ch. 11 — The Transformer encoder block: multi-head self-attention plus a position-wise feed-forward network, each in a residual + normalization wrapper. ↩
╌╌ END ╌╌