Chapter 02 — The Illustrated Transformer

The Illustrated Transformer

The paper "Attention Is All You Need" replaced recurrence with pure self-attention and launched the modern AI revolution. This chapter walks through every component of the Transformer visually — intuition first, equations second, code last.

A High-Level Look

Let's begin by looking at the model as a single black box. In a machine translation application, it takes a sentence in one language and outputs the translation in another.

"Je suis étudiant"
→
THE TRANSFORMER
→
"I am a student"

Popping open that black box, we see an encoding component, a decoding component, and connections between them.

Encoding Component
ENCODERS
→
connections
→
Decoding Component
DECODERS

The Transformer was proposed in the paper "Attention is All You Need". It outperforms previous neural machine translation models and — critically — lends itself to parallelization. This is why Google Cloud recommends the Transformer as a reference model for their TPU hardware.

Encoders & Decoders

The encoding component is a stack of 6 encoders. The decoding component is a stack of 6 decoders. (There's nothing magical about six — you can experiment with other numbers.)

Encoder Stack
Encoder #6
Encoder #5
Encoder #4
Encoder #3
Encoder #2
Encoder #1
↑ Input embeddings
Decoder Stack
Decoder #6
Decoder #5
Decoder #4
Decoder #3
Decoder #2
Decoder #1
↑ Output embeddings

The encoders are all identical in structure (but do not share weights). Each one has two sub-layers:

Single Encoder
Feed-Forward Neural Network
↑
Self-Attention
↑ Input

The encoder's inputs first flow through a self-attention layer — which helps the encoder look at other words in the input sentence as it encodes a specific word. The outputs of self-attention are fed to a feed-forward neural network, applied identically to each position.

The decoder has both those layers, but between them is an encoder-decoder attention layer that helps the decoder focus on relevant parts of the input sentence:

Single Decoder
Feed-Forward Neural Network
↑
Encoder-Decoder Attention
↑
Masked Self-Attention
↑ Input

Bringing Tensors Into the Picture

As in NLP generally, we begin by turning each input word into a vector using an embedding algorithm. Each word is embedded into a vector of size 512.

Je
suis
étudiant
Each word is embedded into a vector of size 512. We represent those vectors with these boxes.

The embedding only happens in the bottom-most encoder. In other encoders, the input is the output of the encoder directly below. The size of this list is a hyperparameter — typically the length of the longest sentence in the training dataset.

After embedding, each word flows through the two layers of the encoder. Here we see one key property: the word in each position flows through its own path. There are dependencies between paths in the self-attention layer, but the feed-forward layer has no such dependencies — so those paths can be executed in parallel.

FFN
↑
FFN
↑
FFN
↑
Self-Attention (all words interact here)
x₁
x₂
x₃
Dependencies exist in self-attention; the feed-forward paths can run in parallel.

Now We're Encoding!

An encoder receives a list of vectors as input. It passes them into a self-attention layer, then into a feed-forward neural network, then sends the output upwards to the next encoder.

z₁
z₂
↑
Feed-Forward Network
(the exact same network applied to each position)
↑
Self-Attention
↑
x₁
x₂

Self-Attention at a High Level

Say we want to translate this sentence:

"The animal didn't cross the street because it was too tired"

What does "it" refer to? The street or the animal? It's simple for a human, but not for an algorithm. Self-attention allows the model to associate "it" with "animal".

As the model processes each word, self-attention lets it look at other positions in the input sequence for clues that help produce a better encoding for that word.

💡 RNN Comparison

If you're familiar with RNNs, think of how maintaining a hidden state allows an RNN to incorporate its representation of previous words. Self-attention is the Transformer's method to bake the "understanding" of all relevant words — not just previous ones — into the one being processed.

The animal didn't cross the street because it ← was too tired
As encoder #5 processes "it", part of the attention mechanism focuses on "animal" and bakes its representation into the encoding of "it".

Self-Attention in Detail

Let's walk through the calculation step by step — first with vectors, then with matrices.

Step 1: Create Q, K, V vectors

For each input vector, we create three vectors: a Query, a Key, and a Value — by multiplying the embedding by three weight matrices trained during training.

Embedding
x₁
dim=512
×
WQ
WK
WV
→
q₁ (dim=64)
k₁ (dim=64)
v₁ (dim=64)
These new vectors are smaller (64) than the embedding vector (512) — an architecture choice for efficient multi-head attention.
💡 What are Q, K, V?

They're abstractions useful for calculating attention. Query = "what am I looking for?", Key = "what do I contain?", Value = "what do I actually provide?". The score between a query and key determines how much of the corresponding value to use.

Step 2: Calculate scores

Score each word against the current word by taking the dot product of the query with each key:

Processing: "Thinking" (position #1)

Score₁ = q₁ · k₁ = 112
Score₂ = q₁ · k₂ = 96

Steps 3 & 4: Scale and Softmax

Divide scores by (for more stable gradients), then apply softmax:

112 / 8 = 14      96 / 8 = 12

softmax([14, 12]) = [0.88, 0.12]

The softmax score determines how much each word will be expressed at this position. The word at this position will naturally have the highest score, but it's useful to attend to relevant other words too.

Step 5: Multiply values by softmax scores

Keep the values of words we want to focus on, and drown out irrelevant words (by multiplying by tiny numbers like 0.001).

Step 6: Sum the weighted values

This produces the output of self-attention for this position:

This vector is sent to the feed-forward neural network.

Matrix Calculation of Self-Attention

In practice, this is done with matrices for speed. Pack all embeddings into a matrix X, multiply by trained weight matrices:

Embeddings
X
n × 512
×
WQ
512×64
WK
512×64
WV
512×64
→
Q
n×64
K
n×64
V
n×64

Steps 2 through 6 condensed into one formula:

The self-attention calculation in matrix form.

The Beast With Many Heads

The paper refines self-attention with "multi-headed" attention, which improves performance in two ways:

  1. It expands the model's ability to focus on different positions. (z₁ could be dominated by the word itself — multiple heads let it also attend to related words.)
  2. It gives the attention layer multiple "representation subspaces". With 8 heads, we get 8 sets of Q/K/V weight matrices, each randomly initialized and trained to project into a different subspace.
8 heads produce 8 different Z matrices:
Z₀
Z₁
Z₂
Z₃
Z₄
Z₅
Z₆
Z₇
↓ Concat
[Z₀ ; Z₁ ; … ; Z₇]   (n × 512)
×
WO   (512 × 512)
↓
Z   (n × 512)
Fed to the feed-forward layer

What do different heads focus on?

When encoding "it" in our example sentence, one head focuses most on "the animal", while another focuses on "tired". The model's representation of "it" bakes in both "animal" and "tired".

Head 1 (encoding "it")
The: 0.08
animal: 0.52
didn't: 0.05
cross: 0.04
the: 0.03
street: 0.06
because: 0.07
it: 0.09
was: 0.03
too: 0.01
tired: 0.02
Head 2 (encoding "it")
The: 0.02
animal: 0.08
didn't: 0.03
cross: 0.04
the: 0.02
street: 0.05
because: 0.06
it: 0.11
was: 0.10
too: 0.07
tired: 0.42
Different heads learn to attend to different relationships.

Representing the Order of the Sequence Using Positional Encoding

Self-attention treats input as a set — it has no notion of word order. To address this, the Transformer adds a positional encoding vector to each input embedding. These vectors follow a specific pattern that helps the model determine position and relative distance.

Word Embedding
+
Positional Encoding
=
Encoder Input

If the embedding has dimensionality 4, a toy positional encoding would look like:

pos=0: [ 0.000, 1.000, 0.000, 1.000 ]
pos=1: [ 0.841, 0.540, 0.010, 1.000 ]
pos=2: [ 0.909, -0.416, 0.020, 1.000 ]
pos=3: [ 0.141, -0.990, 0.030, 0.999 ]
🔑 Why Sinusoidal?

can be represented as a linear function of for any fixed offset k. This lets the model easily learn to attend by relative positions. The left half uses sine, the right half uses cosine — they're concatenated (or interleaved) to form each vector.

The Residuals

Each sub-layer (self-attention, FFN) in each encoder has a residual connection around it, followed by a layer-normalization step:

Input x
↓
Self-Attention
↓
skip
Add & LayerNorm
↓
Feed-Forward
↓
skip
Add & LayerNorm
↓
Output

This also applies to the decoder sub-layers. If we think of a Transformer of 2 stacked encoders and decoders, each sub-layer has the same add-and-normalize wrapper. The residual connection ensures gradients flow directly through the network — this is why Transformers can stack many layers without vanishing gradients.

The Decoder Side

The encoder processes the input sequence. The output of the top encoder is transformed into attention vectors K and V, which are used by each decoder in its "encoder-decoder attention" layer.

Encoder
Encoder #6 (top)
⋮ (5 more below)
↓ produces K, V
→
K, V
Decoder
FFN
↑
Encoder-Decoder Attn
Q=decoder, K,V=encoder
↑
Masked Self-Attention
×6 layers

Each decoding step outputs an element from the output sequence. The output of each step is fed to the bottom decoder in the next time step, and the decoders bubble up their results. Positional encodings are added to decoder inputs too.

Key differences in the decoder:

The Final Linear and Softmax Layer

The decoder stack outputs a vector of floats. How do we turn that into a word? With a Linear layer followed by a Softmax layer.

The Linear layer projects the decoder output into a much larger vector — the logits vector. If the model knows 10,000 English words, the logits vector is 10,000 cells wide, each cell corresponding to the score of a unique word.

The softmax layer turns those scores into probabilities (all positive, all add up to 1.0). The cell with the highest probability is chosen, and the associated word is produced as output.

Decoder Output (512-dim)
↓
Linear Layer → logits (10,000-dim)
↓
Softmax → probabilities
↓
argmax → "I"

Recap of Training

During training, an untrained model goes through the same forward pass. Since we have a labeled dataset, we can compare its output with the actual correct output.

Assume our output vocabulary contains only six words: "a", "am", "i", "thanks", "student", and "<eos>".

a
am
i
thanks
student
<eos>
One-hot encoding: "am" = [0, 1, 0, 0, 0, 0]

Once we define the output vocabulary, we use a vector of the same width to represent each word (one-hot encoding). We can then compare the model's probability distribution against the correct one-hot vector, and tweak all weights using backpropagation.

The Loss Function

Say we're training on a simple example: translating "merci" into "thanks". We want the output to be a probability distribution indicating "thanks". But an untrained model produces random values:

Model Output (untrained)
a: 0.2
am: 0.1
i: 0.3
thanks: 0.05
student: 0.25
<eos>: 0.1
Desired Output
a: 0
am: 0
i: 0
thanks: 1
student: 0
<eos>: 0

We compare using cross-entropy loss — subtract one distribution from the other. For longer sentences (e.g. "je suis étudiant" → "i am a student"), we want each position to output the right probability distribution:

After training on a large dataset for enough time, the produced distributions would converge toward the desired output. Each position gets a little probability even for unlikely words — that's a useful property of softmax which helps the training process.

Inference & Beam Search

Since the model produces outputs one at a time, the simplest approach is greedy decoding: pick the highest-probability word at each step.

A better approach is beam search: keep the top B candidates at each step, running the model for each partial hypothesis, and keeping whichever version produces less total error.

Beam Search (beam_size=2):
Step 1: <BOS> → { "I" (0.55), "a" (0.30) }
Step 2: "I" → { "I am" (0.45) }
        "a" → { "a student" (0.15) }
Step 3: "I am" → { "I am a" (0.42) }
Step 4: "I am a" → { "I am a student" (0.40) }
Step 5: → { "I am a student <EOS>" ✓ }

In this example, beam_size=2 means we keep two partial hypotheses in memory. top_beams=2 means we return the top two complete translations. Both are hyperparameters you can experiment with.

Why The Transformer Works

PropertyRNNCNNTransformer
Max Path LengthO(n)O(log n)O(1)
Parallelizable❌ Sequential✅ Yes✅ Yes
Complexity per LayerO(n · d²)O(k · n · d²)O(n² · d)
Long-Range DependenciesPoorLimited by kernelExcellent

The key advantages are:

  1. O(1) path length: Any two tokens can directly attend to each other — no information needs to travel through intermediate steps.
  2. Full parallelism: All tokens are processed simultaneously during training.
  3. Scalability: The architecture scales well with data and compute, enabling ever-larger models.
🔥 Full Translation Pipeline

End-to-End: "Le chat est noir" → "The cat is black"

Let's trace one complete forward pass through the full encoder-decoder architecture.

Encoder
"Le chat est noir"
↓ tokenize + embed + PE
×6
Self-Attention (bidirectional)
↓ Add & Norm
FFN: 512→2048→512
↓ Add & Norm
Z ∈ ℝ4×512
→ K, V sent to decoder →
Decoder
"<BOS> The cat is black"
↓ tokenize + embed + PE
×6
Masked Self-Attention
↓ Add & Norm
Cross-Attention (Q=dec, K,V=enc)
↓ Add & Norm
FFN: 512→2048→512
↓ Add & Norm
Linear → Softmax → output word
Full encoder-decoder data flow. The dashed cross-attention block bridges the encoder to the decoder.

Training Details

💻 PyTorch Code

Code: Transformer from Scratch

Positional Encoding

Python
class PositionalEncoding(nn.Module):
    def __init__(self, d_model=512, max_len=5000):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len).unsqueeze(1).float()
        div_term = torch.exp(
            torch.arange(0, d_model, 2).float()
            * (-math.log(10000.0) / d_model)
        )
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        self.register_buffer('pe', pe.unsqueeze(0))

    def forward(self, x):
        return x + self.pe[:, :x.size(1)]

Multi-Head Attention

Python
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model=512, n_heads=8):
        super().__init__()
        self.n_heads = n_heads
        self.d_k = d_model // n_heads
        self.W_q = nn.Linear(d_model, d_model)
        self.W_k = nn.Linear(d_model, d_model)
        self.W_v = nn.Linear(d_model, d_model)
        self.W_o = nn.Linear(d_model, d_model)

    def forward(self, q, k, v, mask=None):
        B, T, _ = q.shape
        # Project and reshape to (B, heads, T, d_k)
        Q = self.W_q(q).view(B, T, self.n_heads, self.d_k).transpose(1, 2)
        K = self.W_k(k).view(B, -1, self.n_heads, self.d_k).transpose(1, 2)
        V = self.W_v(v).view(B, -1, self.n_heads, self.d_k).transpose(1, 2)
        # Scaled dot-product attention
        scores = (Q @ K.transpose(-2, -1)) / (self.d_k ** 0.5)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, float('-inf'))
        attn = torch.softmax(scores, dim=-1)
        out = (attn @ V).transpose(1, 2).contiguous().view(B, T, -1)
        return self.W_o(out)

Full Encoder-Decoder Transformer

Python
class Transformer(nn.Module):
    def __init__(self, src_vocab, tgt_vocab, d_model=512):
        super().__init__()
        self.src_embed = nn.Embedding(src_vocab, d_model)
        self.tgt_embed = nn.Embedding(tgt_vocab, d_model)
        self.pos_enc  = PositionalEncoding(d_model)
        self.encoder  = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(d_model, 8, batch_first=True),
            num_layers=6
        )
        self.decoder  = nn.TransformerDecoder(
            nn.TransformerDecoderLayer(d_model, 8, batch_first=True),
            num_layers=6
        )
        self.output = nn.Linear(d_model, tgt_vocab)

    def forward(self, src, tgt):
        # Encode source
        src_emb = self.pos_enc(self.src_embed(src))
        memory  = self.encoder(src_emb)
        # Decode target (with causal mask)
        tgt_emb  = self.pos_enc(self.tgt_embed(tgt))
        tgt_mask = nn.Transformer.generate_square_subsequent_mask(tgt.size(1))
        out = self.decoder(tgt_emb, memory, tgt_mask=tgt_mask)
        return self.output(out)  # (B, tgt_len, tgt_vocab)

Impact & Legacy

The Transformer has become the universal backbone of modern AI:

📄 Go Forth And Transform

Read the "Attention Is All You Need" paper. Explore the Tensor2Tensor repo. Check out Harvard NLP's Annotated Transformer guide with PyTorch implementation. Content inspired by Jay Alammar's Illustrated Transformer.