Simple Algorithm
Artificial Intelligence · Hidden Layer · 26 min

Attention & Transformers

Queries, keys, values and the architecture behind modern AI.

In 2017, Vaswani and colleagues threw out recurrence altogether. Their transformer alternates just two operations: attention, which moves information between positions, and a small MLP, which processes each position on its own. Here you derive both, assemble the block, and count what it costs to train and to run.

What you’ll learn

  • Compute scaled dot-product attention in matrix form and derive why the scores are divided by dk\sqrt{d_k}.
  • Assemble multi-head attention and the pre-LN transformer block, and count its parameters (about 12d212d^2 per layer).
  • Distinguish encoder, decoder and encoder–decoder transformers, and explain how the causal mask makes training parallel.
  • Analyze attention's O(n2d)\order{n^2d} cost and the memory-for-compute trade of the KV cache in autoregressive decoding.

Scaled dot-product attention

Attention, as the Input Layer put it, is a soft dictionary lookup. Stack the nn token vectors of a sequence as the rows of X∈Rn×dX\in\R^{n\times d}. Three learned matrices map each row to a query, a key and a value: Q=XWQQ=XW_Q and K=XWKK=XW_K in Rn×dk\R^{n\times d_k}, V=XWV∈Rn×dvV=XW_V\in\R^{n\times d_v}. Output row ii is a convex combination of the values, weighted by how well query ii matches each key:

Attn⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)V,zi=∑j=1naijvj,aij=eqi⋅kj/dk+Mij∑leqi⋅kl/dk+Mil\operatorname{Attn}(Q,K,V)=\softmax\!\Big(\frac{QK^\top}{\sqrt{d_k}}+M\Big)V,\qquad \mathbf z_i=\sum_{j=1}^n a_{ij}\mathbf v_j,\quad a_{ij}=\frac{e^{\mathbf q_i\cdot\mathbf k_j/\sqrt{d_k}+M_{ij}}}{\sum_l e^{\mathbf q_i\cdot\mathbf k_l/\sqrt{d_k}+M_{il}}}
The softmax acts on each row. MM is a mask: 00 where attention is allowed, −∞-\infty where it is not (take M=0M=0 for now). This is Bahdanau's attention (Sequence-to-Sequence Models) with dot-product scores, separate values, and every position querying every position of the same sequence: self-attention.
DerivationWhy divide by √d_k?
  1. E[q⋅k]=∑i=1dkE[qi] E[ki]=0,Var⁡(q⋅k)=∑i=1dkVar⁡(qiki)=dk\E[\mathbf q\cdot\mathbf k]=\sum_{i=1}^{d_k}\E[q_i]\,\E[k_i]=0,\qquad\Var(\mathbf q\cdot\mathbf k)=\sum_{i=1}^{d_k}\Var(q_ik_i)=d_k

    Assume, as Vaswani et al. did in a footnote, that the components of q\mathbf q and k\mathbf k are independent with mean 00 and variance 11, roughly the situation at initialization. Each product qikiq_ik_i then has mean 00 and variance E[qi2]E[ki2]=1\E[q_i^2]\E[k_i^2]=1:

  2. ∂ai∂sj=ai(δij−aj) ⟶ 0as a→one-hot\frac{\partial a_i}{\partial s_j}=a_i(\delta_{ij}-a_j)\ \longrightarrow\ 0\qquad\text{as }\mathbf a\to\text{one-hot}

    So raw scores have standard deviation dk\sqrt{d_k}, which is 88 for dk=64d_k=64. Large score gaps push each row of the softmax toward a one-hot vector, where its Jacobian vanishes and almost no gradient reaches WQW_Q and WKW_K:

  3. Var⁡(q⋅kdk)=1\Var\Big(\frac{\mathbf q\cdot\mathbf k}{\sqrt{d_k}}\Big)=1

    Dividing by dk\sqrt{d_k} restores unit variance for every head size, so the softmax starts in its sensitive range. It is the same as a softmax temperature of dk\sqrt{d_k} applied to the raw dot products.

Check your understanding

Without any position information, what does self-attention do with "dog bites man" versus "man bites dog"?

  1. Each word gets exactly the same output vector in both sentences; only the order of the rows differs
  2. The outputs differ, because the attention weights depend on word order
  3. The outputs differ, because the softmax is applied row by row
  4. The outputs differ, because values are weighted by their distance from the query
Show the answer

A. Each word gets exactly the same output vector in both sentences; only the order of the rows differs

Permuting the rows of XX by a permutation matrix PP permutes QQ, KK and VV alike, and softmax⁡(PQK⊤P⊤)PV=P softmax⁡(QK⊤)V\softmax(PQK^\top P^\top)PV=P\,\softmax(QK^\top)V. Self-attention is permutation-equivariant: each output depends on its own token and the multiset of the others, so subject and object are indistinguishable. Positional information breaks the symmetry (Positional Encodings).

Multi-head attention

One softmax gives one weighting per query. To let a token gather several kinds of information at once (the previous token, its syntactic head, its referent), split the width into hh heads of size dk=dv=d/hd_k=d_v=d/h, give each its own projections, concatenate the results and mix them with WO∈Rd×dW_O\in\R^{d\times d}. This is multi-head attention:

MHA⁡(X)=[Z1 ⋯ Zh] WO,Zr=softmax⁡ ⁣(XWQr (XWKr)⊤d/h+M) XWVr\operatorname{MHA}(X)=\big[Z_1\ \cdots\ Z_h\big]\,W_O,\qquad Z_r=\softmax\!\Big(\frac{XW_Q^{r}\,(XW_K^{r})^\top}{\sqrt{d/h}}+M\Big)\,XW_V^{r}
Cut WOW_O into row blocks WOrW_O^r and MHA becomes a sum over heads, ∑rAr X WVrWOr\sum_r A_r\,X\,W_V^rW_O^r with ArA_r the head's attention matrix: each head reads with its own weights and writes into the same dd-dimensional space.

Parameter count. The hh query projections tile one d×dd\times d matrix, and likewise for keys and values; with WOW_O that makes 4d24d^2 weights (plus biases), whatever hh is. Heads are not extra capacity. They factor the same capacity into hh separate attention patterns, each computed from rank-d/hd/h query and key projections. The original transformer used d=512d=512 with h=8h=8 heads of size 6464 (Vaswani et al., 2017).

Think first Why not give every head the full width, dk=dd_k=d?

You could, at hh times the cost and parameters. The standard split keeps MHA as cheap as one full-width head. The price is rank: each head's score matrix XWQr(WKr)⊤X⊤XW_Q^r(W_K^r)^\top X^\top has rank at most d/hd/h, which limits the patterns a single head can express (The Mathematics of Attention makes this precise). Many heads can be pruned after training with little loss (Michel, Levy & Neubig, 2019; Voita et al., 2019), so the right number is an empirical question.

The block and the residual stream

A transformer layer wraps attention and a position-wise MLP in residual connections and layer normalization. In the now-standard pre-LN arrangement, each sublayer reads a normalized copy of the running vectors and adds its output back:

text
TRANSFORMER-LM(tokens x₁ … xₙ)                  // decoder-only, pre-LN
  H ← E[x₁ … xₙ] + P[1 … n]                    // n×d: token and position embeddings
  for ℓ = 1 … L:
      A ← LN(H)
      for r = 1 … h:                             // heads, computed in parallel
          Q, K, V ← A·W_Q^r, A·W_K^r, A·W_V^r     // n×(d/h) each
          Z_r ← softmax_rows(Q·Kᵀ/√(d/h) + M)·V
      H ← H + [Z₁ … Z_h]·W_O                    // attention writes into the stream
      H ← H + GELU(LN(H)·W₁ + b₁)·W₂ + b₂         // MLP d → 4d → d, per position
  return softmax_rows(LN(H)·W_U)                // n next-token distributions

With Mij=−∞M_{ij}=-\infty for j>ij>i this is a decoder (next step). Everything except attention acts on each position separately, so all nn positions are computed in parallel. The original transformer used ReLU and put LN after each residual addition (post-LN), which trains less stably at depth (Normalization & Residual Connections).

Read HH as a residual stream: one dd-dimensional channel per position that every sublayer reads from and adds to (Elhage et al., 2021). Attention is the only operation that moves information between positions; the MLPs, which hold two-thirds of the weights, transform it in place. Per layer there are 4d24d^2 attention weights and 2⋅d⋅4d=8d22\cdot d\cdot4d=8d^2 MLP weights, so

N≈12 L d2non-embedding parameters,plus ∣V∣ d for the token embeddingsN\approx12\,L\,d^2\quad\text{non-embedding parameters},\qquad\text{plus }|V|\,d\text{ for the token embeddings}
Biases and LayerNorm gains add only O(Ld)\order{Ld}. This NN is the one in the scaling laws (Large Language Models: Pretraining & Scaling).
Predict before you look

GPT-3 (Brown et al., 2020) has L=96L=96 layers of width d=12,288d=12{,}288. Estimate its non-embedding parameter count with N≈12Ld2N\approx12Ld^2, in billions.

Show the answer

174 B

12×96×12,2882≈1.74×101112\times96\times12{,}288^2\approx1.74\times10^{11}. The embedding table adds 50,257×12,288≈0.650{,}257\times12{,}288\approx0.6 billion, close to the reported 175 billion. Width enters squared: doubling dd quadruples NN, while doubling LL only doubles it.

Encoders, decoders and the causal mask

The same block serves three architectures, distinguished by the mask and by where keys and values come from:

ArchitectureAttentionTypical objectiveExamples
EncoderM=0M=0: every token sees every tokenmasked-token prediction; classificationBERT (Devlin et al., 2019)
Decodercausal: Mij=−∞M_{ij}=-\infty for j>ij>inext-token predictionthe GPT series (2018 on)
Encoder–decoderbidirectional encoder; causal decoder plus cross-attention, with queries from the decoder and keys and values from the encoder outputsequence to sequence: translation, span corruptionthe original transformer (2017); T5 (Raffel et al., 2020)
Cross-attention is the transformer form of Bahdanau attention. Decoder-only models drop it and simply put the source text in the prompt.

The causal mask is what makes decoder training efficient. Adding −∞-\infty before the softmax gives future positions weight exactly 00 while each row still sums to one, so output row ii depends only on tokens 1,…,i1,\dots,i. One forward pass then yields all nn next-token predictions of a training sequence, each conditioned on the true prefix, and the loss is one cross-entropy summed over positions. An RNN needs nn sequential steps for the same work.

Cost, and the KV cache

Count the floating-point operations of one layer on nn tokens, with a multiply-add as 2 FLOPs. The projections and the MLP are dense products costing 24nd224nd^2; the scores QK⊤QK^\top and the mixing AVAV cost 2n2d2n^2d each:

Clayer≈24 n d2⏟projections, MLP+4 n2d⏟scores, mixing,attention weights to store: O(h n2)C_{\text{layer}}\approx\underbrace{24\,n\,d^2}_{\text{projections, MLP}}+\underbrace{4\,n^2d}_{\text{scores, mixing}},\qquad\text{attention weights to store: }\order{h\,n^2}
The quadratic term wins once n>6dn>6d, about 25,00025{,}000 tokens at d=4096d=4096; a kernel that skips the masked half halves it. In exchange, any two positions interact in one step: the path between tokens has length O(1)\order{1}, against O(n)\order{n} sequential steps in an RNN (Vaswani et al., 2017).

Generation is different. An autoregressive model emits one token per forward pass, and reprocessing the whole prefix each time would cost O(n2)\order{n^2} per new token. But under the causal mask earlier positions never change, so their keys and values can be stored and reused:

text
GENERATE(prompt x₁ … x_m, number of new tokens T)
  run the model on x₁ … x_m, keeping every layer's K and V   // prefill: the KV cache
  for t = m+1 … m+T:
      sample x_t from the output distribution at position t−1
      run x_t alone through the layers; in each layer:
          q, k, v ← projections of position t
          append k and v to the layer's cache               // now t rows
          z ← softmax(q·K_cacheᵀ/√d_k)·V_cache              // one row: O(t·d)
  return x_{m+1} … x_{m+T}

A new token now costs O(d2)\order{d^2} for projections and MLP plus O(t d)\order{t\,d} for attention per layer. The cache trades memory for that compute: 2Ld2Ld stored numbers per token, the keys and values of every layer.

Predict before you look

At 2 bytes per number, how many megabytes of KV cache does GPT-3's configuration (L=96L=96, d=12,288d=12{,}288) need per token of context?

Show the answer

4.7 MB

2×96×12,288×22\times96\times12{,}288\times2 bytes ≈4.7\approx4.7 MB per token, so one 2,048-token context needs about 9.79.7 GB. When many sequences are served at once, the cache can dominate accelerator memory. Sharing keys and values across heads (multi-query and grouped-query attention) shrinks it: see Efficient Attention & Long Context.

Key takeaways

  • Attention computes softmax⁡(QK⊤/dk+M)V\softmax(QK^\top/\sqrt{d_k}+M)V: each output is a convex combination of values weighted by query–key match, and the dk\sqrt{d_k} keeps score variance near 11 so the softmax does not saturate.
  • Multi-head attention splits width dd into hh heads of size d/hd/h, for 4d24d^2 weights whatever hh; a pre-LN block adds attention and an MLP to a residual stream, about 12d212d^2 weights per layer.
  • Without positions, self-attention is permutation-equivariant. Encoders attend both ways, decoders use a causal mask that makes training parallel, and encoder–decoders add cross-attention.
  • A layer costs about 24nd2+4n2d24nd^2+4n^2d FLOPs, so attention dominates beyond n≈6dn\approx6d; generation caches keys and values, 2Ld2Ld numbers per token.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Query and key components are independent with mean 00 and variance 11, and dk=256d_k=256. What is the standard deviation of the unscaled score q⋅k\mathbf q\cdot\mathbf k, and what does the transformer divide it by?

  1. 1616; it divides by 1616
  2. 256256; it divides by 256256
  3. 11; no scaling is needed
  4. 1616; it divides by 256256
Show the answer

A. 1616; it divides by 1616

The variance is a sum of dkd_k unit variances, 256256, so the standard deviation is 1616, and dividing by dk=16\sqrt{d_k}=16 restores unit variance.

Question 2

A layer has width d=1024d=1024. You switch multi-head attention from 88 heads to 1616, keeping dk=d/hd_k=d/h. How does the number of attention weights change?

  1. It doubles
  2. It halves
  3. It stays at 4d24d^2
  4. It grows by d2d^2 per extra head
Show the answer

C. It stays at 4d24d^2

The heads' projections tile one d×dd\times d matrix each for queries, keys and values, plus WOW_O: 4d24d^2 whatever hh is. More heads means more, narrower attention patterns.

Question 3

How does a decoder apply its causal mask?

  1. It sets the weights of future positions to zero after the softmax, without renormalizing
  2. It deletes future tokens from the input sequence
  3. It replaces the values of future positions by zero vectors
  4. It adds −∞-\infty to the scores of future positions before the softmax, so they get weight exactly 00 and the rest still sum to one
Show the answer

D. It adds −∞-\infty to the scores of future positions before the softmax, so they get weight exactly 00 and the rest still sum to one

Masking the scores keeps every row a probability distribution over the allowed positions j≤ij\le i, while the whole sequence is still processed in one pass. That is what makes training parallel.

Question 4

What does the KV cache store, and what does it save?

  1. The attention weights of every earlier step, so the softmax need not be recomputed
  2. Each layer's keys and values for all earlier positions, so a new token needs only its own projections and one attention row per layer
  3. The model's output probabilities, so repeated prompts are answered instantly
  4. Compressed weights, so that the model fits in memory
Show the answer

B. Each layer's keys and values for all earlier positions, so a new token needs only its own projections and one attention row per layer

Under a causal mask, earlier keys and values never change, so each is computed once. A new token then costs O(d2+t d)\order{d^2+t\,d} per layer instead of reprocessing the prefix, at the price of 2Ld2Ld stored numbers per token.

Go deeper

Further reading

  • A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
  • N. Elhage et al., "A mathematical framework for transformer circuits," Transformer Circuits Thread (2021).
  • M. Phuong & M. Hutter, "Formal algorithms for transformers," arXiv:2207.09238 (2022).
  • D. Jurafsky & J. H. Martin, Speech and Language Processing (3rd ed. draft), chapter on transformers, free at web.stanford.edu/~jurafsky/slp3.