Architectures/Attention & Transformers

Lesson 6.52,602 words

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 dk\sqrt{d_k} 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.

ObjectSymbolShapeRole
Querywhat this position is searching for
Keywhat each position offers for matching
Valuethe content returned when a key matches
Scorescalarraw compatibility of the query with key
Weightscalar 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 as a dataflow: queries and keys give scaled scores, a softmax turns them into weights, and multiplying by blends the values.

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.

Without the correction the softmax saturates: large-variance scores (black) collapse onto one key, while scaled scores (blue) stay usable.
Algorithm:ScaledDotProductAttention(Q,K,V)\textsc{ScaledDotProductAttention}(Q, K, V) — soft content-based lookup
  1. 1
    SQKTS \gets Q K^{T}
    n×nn \times n raw scores
  2. 2
    SS/dkS \gets S / \sqrt{d_k}
    unit-variance correction
  3. 3
    if masked then
    decoder self-attention
  4. 4
    for each i,ji, j with j>ij > i do
  5. 5
    SijS_{ij} \gets -\infty
    forbid attending to the future
  6. 6
    for each row ii do
  7. 7
    Aisoftmax(Si)A_{i} \gets \softmax(S_{i})
    weights sum to 11
  8. 8
    return AVA V
    blend 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.

A self-attention matrix. Each row is a token's query and darker cells carry more weight; here "it" attends strongly to "animal", resolving the reference in one hop.

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

Multi-head attention. The input is projected into subspaces, each running its own scaled dot-product attention; the outputs are concatenated and mixed by .

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.

Multi-head width bookkeeping for , . Each head projects the input down to , attends there, and the blocks concatenate back to before .

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.

Sinusoidal positional encodings. Each curve is one embedding dimension over position : low dimensions (blue) oscillate fast, high ones (red) slowly.

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.

SchemeFormGeneralizes past training length?Cost
Sinusoidalfixed of positionyes (deterministic for any )none
Learnedtrainable table no (undefined for ) params
Relativebias on scores by offset yesper-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.

A Transformer encoder block: multi-head self-attention then a position-wise FFN, each wrapped in an add-and-normalize. The two curved skips are the residual connections.

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.

ComponentSelf-attentionCross-attentionSees the future?
Encoder blockfull (all-pairs)yes (whole input visible)
Decoder blockmaskedattends to encoder outputno (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.

The causal mask. Below and on the diagonal (blue) a token may attend; above it (crossed) the score is set to so the softmax weight is . Row sees only tokens .

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 typePer-layer complexitySequential opsMax 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.

Connectivity, not just cost. Self-attention (left) links every token pair directly at path length ; a recurrence (right) leaves distant tokens hops apart.

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

  1. 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).
  2. 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})V core of the Transformer.
  3. Chollet, Deep Learning with Python, Ch. 11 — Multi-Head Attention: parallel attention functions in -dimensional subspaces, concatenated and projected by .
  4. Chollet, Deep Learning with Python, Ch. 11 — Positional encoding: injecting order into a permutation-equivariant model, sinusoidal versus learned embeddings.
  5. 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 ╌╌