The transformer architecture in detail: multi-head self-attention

The Transformer Architecture in Depth

A complete explanation of the transformer architecture as in "Attention Is All You Need": query, key and value, scaled dot-product attention and why we divide by the square root, multiple heads, positional encoding, the feedforward network, residual connections and layer normalization, the causal mask, and computing the parameter count and complexity, with modern improvements (RoPE, Pre-LN, SwiGLU and FlashAttention).

Lesson 22 of 38Advanced1 hours

Lesson objectives

  • Compute scaled dot-product attention with matrices and explain the role of each component.
  • Estimate the parameter count and computational complexity of a transformer block.
  • Distinguish between the encoder, the decoder, cross-attention and the causal mask.
Page contents
  1. The central idea
  2. Query, key and value
  3. Scaled dot-product attention
  4. Multi-head attention
  5. Positional encoding
  6. The feedforward network
  7. Residual connections and layer normalization
  8. The encoder and the decoder
  9. Number of parameters
  10. Computational complexity
  11. Training in the original paper

The central idea

Vaswani et al. (2017) proposed an architecture that drops recurrence and convolution altogether and relies on self-attention: each word computes its new representation by looking directly at all the words in the sentence. The result: a path of length one between any two words, and fully parallel computation across positions during training. The architecture achieved the best translation results of its time (WMT 2014 English–German and English–French) at a much lower training cost.

The Transformer architecture Transformer (Vaswani et al., 2017)
N×Multi-HeadSelf-AttentionAdd & NormFeed-Forward(FFN)Add & NormEmbedding + PositionalInputs (source)EncoderN×Masked Multi-HeadSelf-AttentionAdd & NormCross-Attention(Q dec, K/V enc)Add & NormFeed-Forward (FFN)Add & NormEmbedding + PositionalOutputs (shifted right)Linear + Softmax

Encoder: multi-head self-attention followed by a feed-forward network, with residual connections and normalization. Decoder: masked self-attention, then cross-attention over the encoder outputs, then feed-forward. The blocks repeat N times.

Query, key and value

Each token has a representation \mathbf{x}_i \in \mathbb{R}^{d_{\text{model}}}. We project the matrix X \in \mathbb{R}^{n \times d_{\text{model}}} with three learned matrices:

Q = X W^Q, \qquad K = X W^K, \qquad V = X W^V

A useful analogy is a soft database lookup: each word poses a query (what am I looking for?), and each word offers a key (what do I hold?) and a value (what information do I give if chosen?). The match score between the query and the key decides how much of the value we take.

Scaled dot-product attention

\text{Attention}(Q, K, V) = \text{softmax}\!\left( \frac{Q K^\top}{\sqrt{d_k}} \right) V
  • QK^\top is an n \times n matrix of scores: row i measures the relevance of word i to every word.
  • The softmax on each row turns it into weights that sum to 1.
  • Multiplying by V gives each word a weighted average of the values of all words.

Why divide by \sqrt{d_k}?

If the components of \mathbf{q} and \mathbf{k} are independent variables with mean 0 and variance 1, then \mathbf{q} \cdot \mathbf{k} = \sum_{i=1}^{d_k} q_i k_i has variance d_k. With d_k = 64 the standard deviation is 8, so some scores come out very large, the softmax saturates (a weight close to 1 for a single item), and its gradients become almost zero. Dividing by \sqrt{d_k} brings the variance back to 1.

A small example

Two words with d_k = 2: \mathbf{q}_1 = (1, 0), \mathbf{k}_1 = (1, 0), \mathbf{k}_2 = (0, 1), \mathbf{v}_1 = (1, 2), \mathbf{v}_2 = (3, 4).

  • Scores: \mathbf{q}_1 \cdot \mathbf{k}_1 = 1, \mathbf{q}_1 \cdot \mathbf{k}_2 = 0, and after dividing by \sqrt{2}: (0.707,\ 0).
  • Softmax: \frac{(e^{0.707}, 1)}{e^{0.707} + 1} = \frac{(2.028, 1)}{3.028} \approx (0.670,\ 0.330).
  • Output: 0.670(1, 2) + 0.330(3, 4) = (1.66,\ 2.66).

Multi-head attention

A single head gives one kind of average. So we run h heads in parallel, each with its own projections of dimension d_k = d_{\text{model}} / h:

\text{head}_i = \text{Attention}(X W_i^Q,\ X W_i^K,\ X W_i^V)
\text{MultiHead}(X) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\, W^O

In the base transformer: d_{\text{model}} = 512, h = 8, d_k = 64. Analysis studies showed that different heads specialize: one head follows the previous word, one links a verb to its subject, and one links a pronoun to its antecedent. But caution is needed: attention weights are not always a faithful explanation of the model's decision.

Positional encoding

Attention does not know order: if we swap two words, the outputs are only swapped in the same way. So a vector representing the position is added to each token's embedding. In the original paper, with sinusoidal functions:

PE_{(pos, 2i)} = \sin\!\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right), \qquad PE_{(pos, 2i+1)} = \cos\!\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right)

Each dimension is a wave with a different frequency, and a relative offset is represented by a linear transformation. BERT and GPT-2 used learned positional embeddings. Modern models mostly use rotary encoding (RoPE) (Su et al., 2021), which rotates the query and key vectors by an angle proportional to the position, so their dot product depends only on the relative distance, which makes it easier to extend the context window.

The feedforward network

After attention, each word passes independently through a two-layer network:

\text{FFN}(\mathbf{x}) = \max(0,\ \mathbf{x} W_1 + \mathbf{b}_1)\, W_2 + \mathbf{b}_2

with inner dimension usually d_{ff} = 4 \times d_{\text{model}} (2048 in the original). Attention mixes information across positions, and the feedforward network processes each position; it is thought to store a large part of the factual "knowledge". Modern models mostly use SwiGLU (Shazeer, 2020) instead of ReLU.

Residual connections and layer normalization

Each sublayer (attention or feedforward) is wrapped in:

\text{Post-LN (original)}: \quad \mathbf{x} \leftarrow \text{LayerNorm}(\mathbf{x} + \text{Sublayer}(\mathbf{x}))
\text{Pre-LN (common today)}: \quad \mathbf{x} \leftarrow \mathbf{x} + \text{Sublayer}(\text{LayerNorm}(\mathbf{x}))

The residual connection lets the gradient pass directly through dozens of layers. Layer normalization (Ba et al., 2016) normalizes the vector components of each token separately. Xiong et al. (2020) showed that Pre-LN makes training more stable and reduces the need for a long learning-rate warm-up phase. Many modern models use the simpler RMSNorm.

The encoder and the decoder

  • The encoder: N blocks (6 in the original), with bidirectional self-attention (every word sees everything).
  • The decoder: N blocks, each with three sublayers:
  1. Causally masked self-attention: position i sees only positions \le i. This is done by adding -\infty to the scores above the diagonal before the softmax.
  2. Cross-attention: the queries come from the decoder, and the keys and values from the encoder's outputs; it is the heir of Bahdanau attention.
  3. A feedforward network.
  • Then a linear layer and a softmax over the vocabulary.

Three families grew out of this design: encoder-only (BERT) for understanding, decoder-only (GPT) for generation, and encoder–decoder (T5, BART) for transformation.

Number of parameters

For one block (ignoring biases and normalization):

  • Attention: 4\, d_{\text{model}}^2 (the matrices W^Q, W^K, W^V, W^O).
  • Feedforward network: 2\, d_{\text{model}}\, d_{ff} = 8\, d_{\text{model}}^2 when d_{ff} = 4 d_{\text{model}}.
  • The total is about 12\, d_{\text{model}}^2 per block.

Check: BERT-Base has 12 layers and d_{\text{model}} = 768: 12 \times 12 \times 768^2 \approx 85 million, plus the vocabulary embedding 30{,}522 \times 768 \approx 23 million, the positional embeddings and the rest, so the total approaches the announced 110 million.

Computational complexity

LayerComplexity per layerSequential operationsLongest path
Self-attentionO(n^2 \cdot d)O(1)O(1)
RecurrentO(n \cdot d^2)O(n)O(n)
ConvolutionalO(k \cdot n \cdot d^2)O(1)O(\log_k n)

(The table is based on the table in the original paper.) Attention is faster when n < d, which is usually the case for sentences, but being quadratic in n becomes the obstacle with long contexts (tens of thousands of tokens). Solutions include:

  • FlashAttention (Dao et al., 2022): computes the same exact attention but with clever tiling that reduces memory reads and writes, so it is faster and uses less memory without approximation.
  • Sparse and windowed attention: each token attends to local neighbors and global tokens.
  • The key–value cache (KV Cache) during generation: storing K and V for previous tokens instead of recomputing them, and multi-query attention (MQA/GQA) to reduce the size of this cache.

Training in the original paper

  • The Adam optimizer with a learning-rate schedule that rises linearly during warm-up (4000 steps) and then decreases with the inverse square root of the step number.
  • Label smoothing of 0.1, and dropout of 0.1.
  • Beam search with width 4 for translation.

To go deeper: read Jay Alammar's "The Illustrated Transformer" (in the references), then re-derive the parameter count of the small GPT-2 (12 layers, 768 dimensions, 50,257 tokens) and compare it with the announced figure of about 124 million.

Lesson summary

  • Attention = softmax(QKᵀ/√d_k)·V, and every word attends to every word in a single step.
  • Multiple heads learn different kinds of relations in parallel.
  • Block = attention + feedforward network, each with a residual connection and layer normalization.
  • The cost of attention is quadratic in sequence length, which motivates efficiency research.

Check what you understood

Choose an answer for each question to see the correction and the reasoning. Your answers are not sent anywhere.

  1. Why do we divide QKᵀ by √d_k?

  2. What is the role of the causal mask in the decoder?

  3. What is the complexity of self-attention with respect to sequence length n?

References

  1. Vaswani, A. et al. (2017). Attention Is All You Need. NeurIPS arxiv.org/abs/1706.03762
  2. Ba, J. L., Kiros, J. R. & Hinton, G. E. (2016). Layer Normalization arxiv.org/abs/1607.06450
  3. Xiong, R. et al. (2020). On Layer Normalization in the Transformer Architecture. ICML arxiv.org/abs/2002.04745
  4. Su, J. et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding arxiv.org/abs/2104.09864
  5. Shazeer, N. (2020). GLU Variants Improve Transformer arxiv.org/abs/2002.05202
  6. Dao, T. et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS arxiv.org/abs/2205.14135
  7. Alammar, J. The Illustrated Transformer jalammar.github.io/illustrated-transformer/