Skip to content

The Illustrated Transformer

optionalcorefundamentalblogrubric 12/122018 · ~45 min

Jay Alammar

Status

TL;DR. A blog post from June 2018 that explains the original Transformer with step-by-step figures. It follows one sentence through embeddings, self-attention, multi-head attention, positional encoding, residual connections, the decoder, and the final softmax. It has been taught in many university courses. An updated, expanded version is chapter 3 of the author’s book (LLM-book.com). Read it alongside the paper: a few details are simplified or wrong.

Why it matters now. Every LLM still uses the blocks shown here. The vectors-and-matrices figures make the shapes concrete, which helps when reading code or debugging an implementation.

The post builds the model in the order below; the numbers match the diagram.

  1. Inputs. Each word becomes a 512-dimensional embedding, plus a positional encoding. Only the bottom encoder sees embeddings; higher layers see the previous layer’s output.
  2. Self-attention in six steps. Make query, key and value vectors of size 64 for each word. Score each query against every key. Divide by 8. Apply softmax. Weight the value vectors. Sum. In matrix form: Z=softmax⁡ ⁣(QK⊤dk)V,dk=64=8.Z=\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V,\qquad \sqrt{d_k}=\sqrt{64}=8.
  3. Multi-head attention. Eight heads, each with its own WQ,WK,WVW^Q, W^K, W^V. The eight outputs are concatenated and multiplied by WOW^O. The post’s example shows one head linking “it” to “the animal” and another to “tired”.
  4. Residual and layer norm. Each sub-layer is wrapped in a residual connection followed by layer normalisation, then a position-wise feed-forward network.
  5. Decoder. Masked self-attention, so a position sees only earlier outputs. Then encoder-decoder attention with queries from the decoder and keys and values from the top encoder.
  6. Output. A linear layer maps to vocabulary-sized logits, a softmax gives probabilities, and training compares them with the one-hot target (the post points to cross-entropy and KL divergence). Decoding is greedy or beam search.

The paper’s positional encoding is

PE(pos,2i)=sin⁡ ⁣(pos/100002i/d),PE(pos,2i+1)=cos⁡ ⁣(pos/100002i/d).PE_{(pos,2i)}=\sin\!\big(pos/10000^{2i/d}\big),\qquad PE_{(pos,2i+1)}=\cos\!\big(pos/10000^{2i/d}\big).
A reading map of The Illustrated Transformer, with three points to read with care Left: one encoder layer and one decoder layer of the original Transformer, labelled with the order in which the post explains them. 1, inputs are embedded to 512 dimensions and a positional encoding is added. 2, self-attention projects each vector to query, key and value vectors of size 64, divides scores by 8 and applies softmax. 3, eight heads are concatenated and multiplied by W O. 4, each sub-layer has a residual connection and layer normalisation, followed by a feed-forward network. 5, the decoder uses masked self-attention, then encoder-decoder attention whose keys and values come from the top encoder. 6, a final linear layer and softmax give a distribution over the vocabulary; decoding is greedy or beam search. Right: three cautions. Sinusoidal positional encodings in the paper are fixed, not learned. A word need not attend most strongly to itself. The positional-encoding heatmap uses the Tensor2Tensor layout with sine and cosine halves concatenated, whereas the paper interleaves them. Encoder ×6 Decoder ×6 self-attention feed-forward masked self-attn enc-dec attention feed-forward add & norm add & norm add & norm embed 512+ positional enc. linear + softmax K, V 1 2 3 4 5 6 1 embed + position · 2 Q, K, V of size 64, scores ÷ 8 · 3 eight heads, concat, W_O 4 residual + layer norm, FFN · 5 masked self-attn, K and V from encoder 6 vocabulary distribution, greedy or beam decoding Read with care Positional encodings Post: a pattern "the model learns". Paper: fixed sinusoids, not learned. Attention to itself A word need not get the highest softmax weight at its own position. Sine / cosine layout The heatmap concatenates halves (Tensor2Tensor); the paper interleaves. The post flags the third point itself.
Original sketch. One encoder and one decoder layer, numbered in the order the post explains them, with three points where the post differs from the paper or overstates what attention does.

This is a tutorial, so its result is clarity rather than numbers. It covers the base model’s sizes: 6 encoder and 6 decoder layers, width 512, 8 heads of 64. For training details and BLEU scores see the paper page. The post links the Tensor2Tensor notebook and Harvard NLP’s Annotated Transformer for code.

  • Dated scope. It describes the 2017 encoder-decoder for translation. It does not cover decoder-only LLMs, pre-norm, RoPE, grouped-query attention or KV caching.
  • Three inaccuracies (diagram, right). The post itself flags the sine/cosine layout difference.
  • Intuition, not evidence. The “it” → “animal” head figure is one example. Attention weights are not a reliable explanation of model behaviour on their own.
  • Training is sketched. The post explains the loss, but not the paper’s learning-rate warm-up, label smoothing or dropout.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    With the post's sizes (model width 512, eight heads, query, key and value vectors of size 64), count the weights in one multi-head self-attention layer, ignoring biases. Compare with a single head of size 512, and explain where the divisor 8 comes from.

    What a strong answer covers
    • Per head, W_Q, W_K and W_V are each 512 × 64. Across 8 heads each kind totals 512 × 512 = 262,144, so the three together are 786,432.
    • W_O maps the concatenated 8 × 64 = 512 values back to 512: another 262,144. Total about 1.05M weights.
    • A single head of size 512 has the same count, so multi-head attention splits capacity across subspaces rather than adding parameters.
    • If query and key components have mean 0 and variance 1, their dot product over 64 dimensions has variance 64, so dividing by the square root, 8, keeps the scores at unit scale and the softmax out of saturation.
  2. Mechanism

    Explain the three kinds of attention in the encoder-decoder Transformer as the post describes them: where queries, keys and values come from in each, and how the decoder is stopped from looking at future tokens during training.

    What a strong answer covers
    • Encoder self-attention: Q, K and V all come from the previous encoder layer, and every position can attend to every other.
    • Decoder self-attention: Q, K and V come from the previous decoder layer, but scores for future positions are set to minus infinity before the softmax, so they get zero weight.
    • Encoder-decoder attention: Q comes from the decoder layer below; K and V come from the output of the top encoder, so each output position can look at the whole input.
    • Masking lets the model train on all target positions in parallel with the true previous tokens as input (teacher forcing), while matching the left-to-right setting at generation time.
  3. Critique

    Identify three statements or figures in the post that differ from the original paper or overstate what attention does, and give the correct version of each.

    What a strong answer covers
    • The post says positional-encoding vectors follow a pattern the model learns. The paper uses fixed sinusoids; it reports learned embeddings as a nearly identical alternative.
    • The post says the word at the current position will clearly have the highest softmax score. Nothing forces this: W_Q and W_K differ, so q_i · k_i need not be the largest score.
    • The positional-encoding heatmap concatenates sine and cosine halves (Tensor2Tensor layout). The paper interleaves them by even and odd dimension; the post notes this itself.
    • None of these affect the main explanation, but they matter if you implement from the post or reason about position.
  4. Research idea

    Design a study that checks, in a trained encoder such as BERT, how often a token gives its largest attention weight to itself, and what that would and would not tell you.

    What a strong answer covers
    • For each layer and head, record whether the argmax of each attention row is the diagonal; report the rate against a uniform-attention baseline of one over sequence length.
    • Separate special tokens such as [CLS] and [SEP], which often absorb attention, from ordinary tokens.
    • Break results down by layer and head, since heads specialise (previous token, next token, delimiter, syntax).
    • Attention weights alone do not show what information is used: value vectors and later layers matter, so complement this with gradient-based or ablation analyses.
  5. Connect

    The post explains a full encoder-decoder model. Which parts do BERT, GPT-style decoders and T5 keep or drop, and how does each choice fit its pretraining objective?

    What a strong answer covers
    • BERT keeps only the encoder (bidirectional self-attention) and trains with masked language modelling, so every token can see both sides.
    • GPT-style models keep only the decoder stack with masked self-attention and no encoder-decoder attention, trained to predict the next token.
    • T5 keeps the full encoder-decoder and trains with span corruption, framing every task as text to text.
    • The final linear layer, softmax and greedy or beam decoding from the post apply directly to GPT and T5 generation.

Done with this page?

Status