Transformer by hand II

The classic encoder–decoder as a zoomable map, with real shapes

The inner mechanisms

Diagram of the classic Transformer, drawn as boxes. Two inputs, source and target, each go into a pink Token Embedding box labelled vocab 37000 by d 512. A sine-wave circle for positional encoding is added to each. The source goes into a box Encoder times 6, the target into a box Decoder times 6, and an arrow runs from the encoder to the decoder. The decoder feeds a trapezoid LM Head, tied by dashed lines to both embeddings, then a softmax bar chart and the word probabilities.

The whole model, collapsed: the overview image published by the site, linked to the interactive diagram by Prof. Tom Yeh. Its LM Head label reads “×72”; the live diagram, in the screenshots below, reads “512 → 37K”, and that is the shape we use.

Transformer by hand (part I) computes one simplified block with a pencil. It leaves out positional encoding, multi-head attention, layer norm and the residual connections. This is part II: those pieces, and the rest. We read a diagram: the classic encoder–decoder Transformer of 2017, with its real shapes, from the whole model down to a single attention block.

How it differs from the flagship: Evolution of LLM Architecture is the story across time, why each idea replaced the last. Here time is frozen at 2017. It is anatomy only, no history.

Credit

The diagram this page follows is by Prof. Tom Yeh: Transformer, an interactive diagram from AI by Hand. Open it next to this page and click through the boxes. Thank you, Tom Yeh, for making it and sharing it.

Diagram of the classic Transformer, drawn as boxes. Two inputs, source and target, each go into a pink Token Embedding box labelled vocab 37000 by d 512. A sine-wave circle for positional encoding is added to each. The source goes into a box Encoder times 6, the target into a box Decoder times 6, and an arrow runs from the encoder to the decoder. The decoder feeds a trapezoid LM Head, tied by dashed lines to both embeddings, then a softmax bar chart and the word probabilities.

The Transformer (Vaswani et al., 2017), whole model, collapsed. Diagram by Prof. Tom Yeh, AI by Hand: click it to open the interactive original.

How to read the diagram

The diagram shows context and detail in the same place: where each piece sits in the whole model, and the real shapes inside each piece. It does this with zoom. The whole model is a handful of boxes. Click a box and it opens into the layer inside. Click again and it opens into the attention inside that. The map stays in view, and a box never hides what is inside it.

Everyday example

It works like a map app. At the highest zoom you see the country and the big cities. Zoom in and you see streets. Zoom in again and you see the shop doors. You never open a second map. The diagram does the same for a Transformer: one drawing, four zoom levels, always the same place.

We follow the same four levels, top to bottom.

Level 0: the whole model

Dark-theme screenshot of the collapsed Transformer diagram: source and target token embeddings of vocab 37K by d 512, positional encoding added to each, Encoder times 6 and Decoder times 6, a tied LM Head 512 to 37K, softmax and probabilities.

Level 0 as the live site shows it, in dark theme. Look at the numbers: 37K, 512.

Read the figure from the top.

  1. Two inputs. Source is the sentence we read (say, English). Target is the sentence we are writing (say, French), the tokens written so far.
  2. Token Embedding, vocab 37K × d 512. Each token is an id from a vocabulary of about 37,000. The embedding is a table with 37,000 rows. Each row is a vector of 512 numbers. Pick the row, and the token becomes a vector. The page Tokenization and embeddings is about this step.
  3. PositionalEncoding, then +. Attention has no sense of order by itself. So a fixed wave pattern, a sine and cosine for each position, is added to every embedding. After the plus, each vector says both which token and where it is.
  4. Encoder × 6 reads the whole source and produces one vector per source position.
  5. Decoder × 6 writes the target. It sees the target so far, and it looks at the encoder’s output (the arrow between the two boxes).
  6. LM Head, 512 → 37K. One vector of 512 numbers goes in; 37,000 scores come out, one per word in the vocabulary.
  7. Softmax → probabilities. The 37,000 scores become 37,000 probabilities that add up to 1. The next token is chosen from them.

Two details the figure shows in one glance. The dashed lines say the LM Head is tied to both embeddings: it is the same 37,000 × 512 table, used backwards. One table does three jobs. And the × 6 says each stack is the same layer repeated six times, each with its own weights.

How a language model turns those probabilities into text is in What is a language model?.

Level 1: one encoder layer

Dark-theme screenshot with the Encoder times 6 box expanded. Inside, top to bottom: a purple SelfAttention box, an Add and Norm box, a blue hexagon FeedForward d 2048, and a second Add and Norm box. Two white lines run from before each sub-layer down to its Add and Norm box.

Level 1: one encoder layer. Six of these in a row make the encoder.

Click Encoder × 6 and the box opens. Inside is the layer that is repeated. It has two sub-layers:

  • SelfAttention. Every source position looks at every source position, and mixes what it finds. This is the “across positions” job.
  • FeedForward, d 2048. A small two-layer network, applied to each position on its own: 512 up to 2048, a non-linearity, then 2048 back down to 512. This is the “across features” job. It is the same two jobs as in Transformer by hand, now with real sizes.

Around each sub-layer sits Add & Norm, layer (d). The white line that skips the sub-layer is the residual: the input is added back to the output, and then the sum is normalised over the \(d = 512\) numbers of each position. The residual is why a stack of six layers still trains. If a layer has nothing to say, the signal passes through.

Every arrow in this layer carries a vector of 512 numbers per position. The encoder never changes that width. It only changes what the numbers say.

Level 2: one decoder layer

Dark-theme screenshot with the Decoder times 6 box expanded. Inside, top to bottom: a purple MaskedSelfAttention box, Add and Norm, a purple CrossAttention box fed by a line coming from the Encoder, Add and Norm, a blue hexagon FeedForward d 2048, and a last Add and Norm. Residual lines skip each sub-layer.

Level 2: one decoder layer. The encoder layer plus one more sub-layer in the middle.

Click Decoder × 6. It is the encoder layer with one extra sub-layer, and the first sub-layer is masked. Three sub-layers, each wrapped in Add & Norm:

  1. MaskedSelfAttention. Like the encoder’s attention, but over the target tokens, and with a causal mask: position \(t\) may look at positions \(1 \dots t\), never at later ones. When we are writing the fifth word, the sixth does not exist yet. The mask is the rule that keeps that true in training too. We open this box in the next level.
  2. CrossAttention. The decoder asks, the encoder answers. The queries come from the decoder’s own stream. The keys and values come from the encoder’s output: that is the line that comes in from the left, from the Encoder box. This is where the source sentence is looked up while the target is written.
  3. FeedForward, d 2048. The same as in the encoder.

The picture makes the split between the three attentions easy to remember: self attention reads one stream; masked self-attention reads one stream and is not allowed to peek forward; cross attention reads from the other stream.

Level 3: one masked attention block

Dark-theme screenshot with MaskedSelfAttention expanded inside the Decoder. Three green boxes Q, K and V, each 512 to 512, at the top. Q and K go into a MatMul box, then a circled multiplication sign for the scale, then a small triangular Causal mask picture, then a Softmax bar chart. The result and V go into a second MatMul, then a green Out box 512 to 512, then Add and Norm.

Level 3: the attention itself. Every box has a real shape.

The last click opens MaskedSelfAttention. This is the whole mechanism, top to bottom.

  1. Q, K, V, each 512 → 512. Three learned projections of the same input. \(Q\) is what am I looking for, \(K\) is what do I offer, \(V\) is what I hand over if you pick me.
  2. MatMul of \(Q\) and \(K\): a score for every pair of positions, how well a query matches a key.
  3. × (scale). Divide by \(\sqrt{d_k}\), so the scores do not grow with the size of the vectors and the softmax stays smooth.
  4. Causal mask. The little triangle. The scores for “later” positions are blanked out, so a position can only listen to itself and the past.
  5. Softmax. Each row of scores becomes shares that add up to 1. This is the attention weight matrix \(A\) from Transformer by hand, now produced instead of given.
  6. MatMul with \(V\): each position’s new vector is the weighted mix of the values.
  7. Out, 512 → 512. One last projection, and then Add & Norm.

In symbols, the whole block is the paper’s formula, with the mask added:

\[ \operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}} + M\right)V \]

where \(M\) is \(0\) where looking is allowed and \(-\infty\) where it is not.

The diagram draws one wide box, 512 → 512. In the paper the 512 numbers are cut into 8 heads of 64, which attend side by side and are glued back together before Out. The shapes are the same. How the heads are shared, saved or cached, and how later models changed that, is the story of The evolution of attention and Evolution of LLM Architecture.

Dark-theme screenshot with the SelfAttention box of the encoder expanded. Green boxes Q, K and V, each 512 to 512, at the top. Q and K go into a MatMul, then a circled multiplication sign for the scale, then a Softmax bar chart with no mask. The result and V go into a second MatMul, then a green Out box 512 to 512, then Add and Norm.

Encoder SelfAttention opened. The same block as below, with no mask.

The same block, without the mask

Open SelfAttention in the encoder and you see the same seven steps, with one difference: there is no causal mask. The source sentence is complete before the model reads it, so every position may listen to every other position, the ones before it and the ones after it. \(Q\), \(K\) and \(V\) are all projections of the same stream, the source with its positions added.

Dark-theme screenshot with the decoder CrossAttention box expanded. Green boxes Q, K and V, each 512 to 512. Q comes from the decoder stream above. A line from the left, from the encoder, feeds K and V. Then MatMul, scale, Softmax with no mask, a second MatMul with V, and an Out box 512 to 512.

Decoder CrossAttention opened. Q comes from the decoder; the line from the left, from the encoder, feeds K and V.

The same block, fed by the encoder

Open CrossAttention in the decoder and the block is again the same, with one change in where its inputs come from. \(Q\) is a projection of the decoder’s own stream, the target written so far. \(K\) and \(V\) are projections of the encoder’s output: that is the line that comes in from the left. The scores are therefore a table with one row per target position and one column per source position: how much each word we are writing looks at each word we read. There is no mask here either, because the whole source is known.

Dark-theme screenshot with the encoder FeedForward box expanded. Top to bottom: a trapezoid Linear 512 to 2048, a ReLU curve, a second trapezoid Linear 2048 to 512, then Add and Norm.

The FeedForward box opened: Linear 512 → 2048, ReLU, Linear 2048 → 512.

The feed-forward block

Open FeedForward and there is no attention in it. It is two Linear layers with a ReLU between them:

  1. Linear, 512 → 2048. Each position’s vector of 512 numbers is widened to 2048.
  2. ReLU. Negative values become 0, the rest pass through. This is the non-linearity.
  3. Linear, 2048 → 512. The vector is narrowed back to 512, so the layer can add it to its input in Add & Norm.

It acts on every position on its own, with the same weights for all positions. The two matrices hold \(2 \times 512 \times 2048 = 2{,}097{,}152\) weights, which is why this box is twice the size of an attention block in the table below.

The real shapes, counted

Because every box has a shape, we can count the weights with a pencil. Biases and the norms’ small scales are left out.

Piece Shape Weights
Token embedding (tied with the LM Head) \(37{,}000 \times 512\) \(18{,}944{,}000\)
One attention block (\(Q\), \(K\), \(V\), Out) \(4 \times (512 \times 512)\) \(1{,}048{,}576\)
One feed-forward \(512 \times 2048 + 2048 \times 512\) \(2{,}097{,}152\)
One encoder layer attention + feed-forward \(3{,}145{,}728\)
One decoder layer two attentions + feed-forward \(4{,}194{,}304\)
Encoder × 6 \(18{,}874{,}368\)
Decoder × 6 \(25{,}165{,}824\)
Total one embedding table, counted once about 63 million

The paper reports about 65 million parameters for this base model. The gap is the biases, the norm parameters and the other small things we skipped. The point is in the table: the embedding table is as large as the whole encoder, and each feed-forward is twice an attention block. The shapes tell you where the weights live.

Where the diagram stops

The diagram is the model of 2017: an encoder and a decoder, sinusoidal positions, layer norm after each sub-layer, a ReLU feed-forward, and a head tied to the embeddings. It is the starting point, not the end. What changed afterwards, and why each change was made, is not retold here. It is the whole story of Evolution of LLM Architecture. The 2017 section of that page points back here when you want to see the anatomy.

FAQ

Why are there two Token Embedding boxes?

One for the source tokens and one for the target tokens. In this model they share one table (that is what the dashed lines say), so there is only one set of weights, used twice at the input and once more, backwards, at the output.

Is the LM Head a new table?

No. It is the embedding table used in reverse: 512 numbers in, 37,000 scores out. That is why the diagram draws it as a trapezoid, a narrowing in reverse, and ties it with a dashed line.

What is the difference between SelfAttention and CrossAttention?

Where the keys and values come from. In self-attention, \(Q\), \(K\) and \(V\) all come from the same stream. In cross-attention, \(Q\) comes from the decoder and \(K\) and \(V\) come from the encoder’s output.

Why a mask only in the decoder?

The encoder reads a sentence that is already complete, so every source position may look at every other. The decoder is writing: it must not use words it has not written yet.

Does the model write all the words at once?

In training it can score all the target positions at once, because the mask hides the future. When it writes for real, it still goes one token at a time: predict, append, predict again.

Credit

The diagram and its zoom levels are by Prof. Tom Yeh, published as the interactive diagram Transformer on pro.byhand.ai, part of AI by Hand and By Hand Research. The text on this page is our own. To go further, open the original, click through the boxes yourself, and read his newsletter.

His spreadsheet exercises are the other half of this story: see Transformer by hand, and AI by hand on our resources page.

Diagram and screenshots: Prof. Tom Yeh, AI by Hand, pro.byhand.ai/d/transformer-classic

See also

References

Back to top