The original Transformer, step by step, with a single-file implementation and its self-tests
Most explanations of the Transformer either stop at the block diagram or jump straight to a production codebase. This one sits in between. It follows one tiny example, the sentence “她 喜欢 红 苹果” translated to “She likes red apples”, through the original encoder-decoder model of Attention Is All You Need (I call it “the paper” below), and writes down the shape of every tensor on the way.
Who this is for. You write Python, you have seen a matrix multiplication and a softmax, and you have run a neural network. You want to know what each step of a Transformer computes.
What you can do after reading. Draw the whole structure and say the input and output shape of
every sub-layer. Explain why training and inference run differently. Read, and run, a single-file
implementation that needs only PyTorch: transformer_minimal.py.
Its self-tests check the claims in this post that a computer can check: shapes, that the causal
mask lets nothing leak from the future, that padding changes nothing, the parameter counts, and
a few more.
1. The overall structure
The model is an encoder-decoder. The encoder reads the source sentence. The decoder writes the target sentence one token at a time. Each side is a stack of N = 6 identical blocks (the paper calls them layers).
An analogy: the encoder is a reader who goes through the Chinese original again and again and fills the margins with notes. The decoder is a translator who, before each English word, looks at what has been written so far and then looks up the reader’s notes.
1.1 One translation, end to end
- Input representation. Each of the four tokens becomes a 512-dimensional vector, and a position encoding is added. The result is a matrix X of shape n × 512, with n = 4.
- Encoding. X goes through the 6 encoder blocks in turn. Every block returns a matrix of the same shape as its input. The output of the last block is called the memory, still 4 × 512.
- Decoding. The decoder receives the memory and starts from the begin symbol
<Begin>. At each step it predicts the next token:<Begin>gives “She”,<Begin> Shegives “likes”, and so on until it predicts<end>. - Output. A linear layer on top of the decoder maps each vector to the vocabulary size, and a softmax turns those scores into probabilities.
The memory goes into every decoder block, not only the first.
Data flows from the bottom up. The encoder on the left runs once and produces the memory. Each decoder block on the right reads the same memory through its cross-attention sub-layer.
1.2 Training and inference differ
The flow above is inference. Training is different, and this is where many readers ask why the correct answer is fed into the decoder.
| Phase | Decoder input | How it is computed | What stops it from seeing the answer |
|---|---|---|---|
| Training | The whole correct answer <Begin> She likes red apples, shifted right by one |
All 5 positions are computed in parallel, in one pass | The causal mask |
| Inference | Only the tokens generated so far | One token at a time, a loop of n steps | Future tokens do not exist yet |
Feeding the correct answer during training is called Teacher Forcing. RNNs are trained with Teacher Forcing too, but an RNN still needs the previous step’s result before it can compute the next one, so it goes position by position. The Transformer has no such recurrence. Together with the causal mask (each position sees only itself and the tokens to its left, Section 6.1), that lets all positions of the sentence be computed at once. That is why training is so much faster than for an RNN. At inference there is no answer to feed, so generation goes step by step, as it does for an RNN. Section 7 gives the code for both.
1.3 The code skeleton
The Annotated Transformer (Harvard NLP,
MIT licence) splits the model into the parts used below. The code in this post is based on it,
with four differences: Pre-LN instead of the paper’s Post-LN (Section 5.3), optional weight sharing, one
function that builds both kinds of mask, and a label-smoothed loss written out in a few lines.
Everything is in one file, transformer_minimal.py, which needs only PyTorch. The self-tests run
on a CPU, and so does the small copy-task training run. Every code block below assumes these
imports and token ids:
1 | import copy, math |
The skeleton of the whole model:
1 | class EncoderDecoder(nn.Module): |
2. The input
The input vector of each token is x = token embedding + position embedding. Both have 512 dimensions and are added element by element.
2.1 Token embedding
A token embedding is a lookup table. If the vocabulary has V tokens, the table is a V × 512 matrix and each token owns one row. Earlier systems often used pre-trained Word2Vec or GloVe vectors. In the Transformer paper the table is trained from scratch together with the model.
Read the figure from left to right. The source tokens are written in pinyin: ta is 她 (she), xihuan 喜欢 (likes), hong 红 (red) and pingguo 苹果 (apples). Looking up a token is only picking a row, with no arithmetic; the ids, and the rows they pick, need not be in order. The four rows are then scaled and added to the position encoding of Section 2.2, and the sum is the matrix X, 4 × 512, that enters the first encoder block. The scaling is the first detail below.
“Word” really means token. I say “word” for convenience. The model’s input unit is a token, produced by a tokenizer that cuts text into sub-words. The paper uses byte-pair encoding (BPE) with one vocabulary of about 37000 tokens shared by English and German. A rare word may become two or three tokens, and a common phrase may become one. “她喜欢红苹果” is not necessarily 4 tokens under every tokenizer. Every n below counts tokens, not characters.
The paper has two details that are easy to miss.
- Multiplying by √d_model. The looked-up vectors are multiplied by √512 ≈ 22.6 before the
position encoding is added. The paper does not say why. A common explanation is that it brings
the embedding to the same scale as the position encoding, whose values lie in [-1, 1], so that
position does not drown out meaning. Whether that holds depends on the initialisation. The code
here uses Xavier initialisation (each weight is drawn so that its standard deviation is √(2 / (fan-in + fan-out))) for every parameter with more than one dimension. For a
37000 × 512 table that gives a standard deviation of about 0.0073, which becomes about 0.165
after the multiplication, still below the root mean square of the position encoding (the square root of the mean of
its squares; a sine and a cosine of one frequency square to 1 together, so the mean is 1/2 and
the root is about 0.707). PyTorch’s default
nn.Embeddinginitialisation has a standard deviation of 1, and after the multiplication the embedding is far larger than the position encoding. - Weight sharing. The source embedding, the target embedding and the linear layer at the top of the decoder use one and the same matrix (paper, Section 3.4). This saves parameters and puts input vectors and output vectors in one space. It requires one vocabulary for both sides. The paper’s English-German experiments used a shared BPE vocabulary of about 37000 tokens. In a Chinese-to-English example the two sides have different vocabularies, so the source embedding cannot be shared; only the target embedding and the output layer can.
1 | class Embeddings(nn.Module): |
2.2 Position embedding (position encoding)
Why it is needed. Self-attention compares every token with every other token and does not care about order. Without position information, “猫吃鱼” (the cat eats the fish) and “鱼吃猫” (the fish eats the cat) look the same to the model: a bag of words.
The paper computes the position encoding directly with sine and cosine functions. Nothing is trained:
Here pos is the position of the token in the sentence (0, 1, 2, …), i runs from 0 to d_model/2 − 1, even dimensions use sine and odd dimensions use cosine.
An intuition. Think of a row of clock hands that turn at different speeds. Dimensions 0 and 1 turn fastest, with a period of about 6.3 positions. Higher dimensions turn more slowly. For the paper’s d_model = 512 the periods of dimensions 0, 16, 64, 256 and 510 are 6.3, 8.4, 19.9, 628 and about 60,600 positions. Each position gets a combination of hand angles that no other position has, the way seconds, minutes and hours together name a time of day.
The horizontal axis is the position of the token. Each curve is one of the 512 dimensions. Cut the plot vertically at any position and the values you read are the encoding of that position. The fast curves tell neighbouring tokens apart, and the slow curves tell distant tokens apart.
What this design buys.
- Relative positions are easy to compute. By the angle-addition formulas of trigonometry, PE(pos + k) is a linear transformation of PE(pos), and the matrix depends only on the offset k. The paper’s authors hypothesised that this helps the model attend by relative position.
- Longer sentences are possible in principle. The formula works for any pos. In practice, quality still drops clearly when the length is far beyond that of the training set.
- The paper also tried learned position embeddings and got nearly identical results (its Table 3, row E). It chose the sinusoidal version because it may let the model extrapolate to longer sequences.
1 | class PositionalEncoding(nn.Module): |
What recent models use. Sinusoidal encoding adds the position to the embedding. Many recent models, including LLaMA, Qwen and DeepSeek, use RoPE (rotary position embedding, Su et al., 2021) instead. RoPE adds nothing to x. It makes the clock hands actually turn, and applies the rotation to Q and K: for the token at position pos, each pair of components of its Q and K vectors is rotated by the angle pos·θᵢ. The dot product of two tokens then depends only on their relative distance, so relative position enters the attention score directly and takes no embedding dimensions. It keeps the idea of dimensions turning at different speeds and replaces addition with rotation.
3. Self-attention
Self-attention lets each token look at all the others and collect their information, weighted by how relevant each is. The result is a new vector for each token that mixes in context. In “The cat sat because it was tired”, attention can let the word “it” pull more information from “cat”.
3.1 The intuition behind Q, K and V
Think of a library search. These are the three matrices:
- Query: what I am looking for. The question each token asks.
- Key: what I can offer. The label on each book’s spine.
- Value: my actual content. What is written in the book.
Compare one token’s query with every token’s key by dot product: the better the match, the higher the score. Turn the scores into weights, then add up all the values in proportion to those weights.
A dot product multiplies two vectors element by element and adds the products; on the left the four products add up to 3. On the right, look at the angle between the arrows: the dot product is large and positive when they point the same way, 0 when they are perpendicular, and negative when they point apart. That is why it works as a match score. The dot product also grows with the lengths of the two vectors: it is the product of their lengths times the cosine of the angle between them. The opposite pair on the right has the longer k, which is why its -3.20 is larger in size than the 2.64 of the pair pointing the same way. Section 3.4 returns to this.
Why three matrices and not x itself? Because the features used for matching and the content that is passed along need not be the same. Three separate projections let the model learn how to ask, how to be found, and what to hand over.
3.2 Computing Q, K and V
The input matrix X (n × d_model) is multiplied by three learned matrices:
Panel (a) is the rule behind every product in this post: entry (i, j) of the result is row i of the left matrix times column j of the right one. Panel (b) applies it to X times W^Q. Row i of Q depends only on row i of X, and every token is multiplied by the same W^Q, so rows do not mix: a projection never moves information from one token to another. Attention is the only step that does that.
Every row of X, Q, K and V belongs to one token. The three W matrices start random and are updated by gradient descent. With a single head, d_k can equal d_model. With multiple heads, d_k = d_model / h = 64 (Section 4).
3.3 The output of self-attention
In computation order there are four steps, here for 4 tokens:
- Score. QKᵀ gives a 4 × 4 score matrix. Entry (i, j) is how much token i attends to token j.
- Scale. Divide by √d_k (= 8).
- Normalise. Apply a softmax to each row, so each row becomes weights that sum to 1.
- Weighted sum. Multiply the weight matrix by V. If row 1 of the weights is [0.3, 0.2, 0.2, 0.3] (an illustrative row), then z₁ = 0.3·v₁ + 0.2·v₂ + 0.2·v₃ + 0.3·v₄.
The vectors in the figure have 2 numbers instead of 64 so that they can be drawn, and the values are made up. On the right, each value is shrunk by its weight and the pieces are laid head to tail; the output z is the arrow from the start to the end. A large weight lets that token’s value pull z towards itself.
The left matrix’s column count must equal the right matrix’s row count, which is why Q (4 × 64) can meet Kᵀ (64 × 4). Follow the highlighted row of the first token. It goes from one row of Q to one row of scores, then to one row of weights, and finally to one row of Z. For an animated version, LLM Visualization draws the same operations as a 3D grid.
The cost is O(n²). The score matrix is n × n. Doubling the sentence length quadruples the compute and memory of this step. That is the root of why long inputs are hard for Transformers. Sparse attention and linear attention try to reduce the n² compute. FlashAttention is a different kind of method: it computes exact attention, and the compute is still O(n²). What it improves is memory traffic and footprint, since it no longer stores the whole n × n score matrix.
3.4 Why divide by √d_k
The usual answer is “to keep the dot products from getting too large”. Here is why large values hurt:
- Assume the components of q and k are independent with mean 0 and variance 1. Then q·k is a sum of d_k terms and its variance is d_k. For d_k = 64 the standard deviation of a score is about 8.
- When scores differ by a lot, the softmax gives nearly all the weight to the largest one, and the output is close to one-hot. The softmax is saturated, its gradient is almost 0, and the model learns badly.
- Dividing by √d_k brings the variance back to 1 and keeps the softmax in a range with healthy gradients.
The left panel shows what a softmax does to one row of scores: exponentiate, then divide by the sum. The right panel is one example draw (d_k = 64, one query, 8 keys, all entries standard normal), chosen to show the typical behaviour. Over 100,000 such draws, the standard deviation of q·k is 8.0 and that of q·k / 8 is 1.0. The largest softmax weight has a median of 0.96 on the raw scores (above 0.9 in about 63% of the draws) and 0.33 after dividing by 8 (above 0.9 in 0.03%). This snippet recomputes them:
1 | import numpy as np |
It prints a standard deviation of 8.00 and 1.00, a median largest weight of 0.96 and 0.33, and 62.89% and 0.02% of the draws above 0.9. The last digit depends on the seed: the run behind the figure (another seed, in chunks) gives 62.94% and 0.025%.
3.5 Code
The Annotated Transformer implements it in a few lines. The mask argument is used in Section 6.
1 | def attention(query, key, value, mask=None, dropout=None): |
4. Multi-head attention
Multi-head attention cuts the 512 dimensions into 8 slices of 64. Each slice does its own self-attention. The results are glued back into 512 dimensions and passed through one more linear map. The total compute is about that of one 512-dimensional head, but the model can look at the relations between tokens from 8 angles at once.
4.1 Why several heads
Two tokens usually relate in more than one way. In “她喜欢红苹果” one can imagine a head for the subject-verb relation (她 to 喜欢), one for the adjective-noun pairing (红 to 苹果), and one for neighbouring tokens. This is an illustration, not a finding: what each head of a real model learns can only be found out by dedicated analysis, and the division of labour is rarely this clean. A single attention gives one set of weights, like looking with one eye. Several heads give the model several sets at once.
4.2 How the dimensions are split
The shapes for n = 4 tokens:
| Step | Operation | Shape |
|---|---|---|
| Input | X | 4 × 512 |
| Projection per head | Qᵢ = XWᵢ^Q (same for K and V), Wᵢ^Q is 512 × 64 | 4 × 64 |
| Attention per head | headᵢ = Attention(Qᵢ, Kᵢ, Vᵢ) | 4 × 64 |
| Concatenate 8 heads | Concat(head₁, …, head₈) | 4 × 512 |
| Output projection | multiply by Wᴼ (512 × 512) | 4 × 512 |
In the figure, the same number from top to bottom is one head. A head works only inside its own 64 columns, until the multiplication by Wᴼ mixes all eight.
The paper’s formula:
What Wᴼ does. Concatenation only puts the eight results side by side, so the heads have not yet exchanged anything. Wᴼ mixes them, so that what different heads found can be combined. Its output has the same shape as the input X, which is what lets the residual connection (Section 5.1) add the two.
Two things that are easy to misread:
- Heads are not layers. The 8 heads run in parallel. They are not stacked.
- The input is not always the same X. In the decoder’s cross-attention, Q comes from one place and K and V from another (Section 6). So the accurate statement is that Q, K and V each go through h projections.
4.3 Code: one projection, then a split into 8
The paper describes 8 small projection matrices. Code usually applies one 512 × 512 matrix and cuts the result into 8 slices. The two are mathematically the same: cutting the big matrix by columns gives eight 512 × 64 matrices. It is written this way so the GPU does it in one go.
In the figure, one small box stands for 64 numbers. view only re-reads each row of 512 numbers as 8
consecutive pieces of 64; no number changes. transpose(1, 2) then swaps the token index and the
head index, so head 1 holds its own piece of every token. The figure draws one sentence, so its shapes
begin with B, the number of sentences in a batch (1 here); that leading index is why the code counts
indices from 1. The code below does exactly this.
1 | class MultiHeadedAttention(nn.Module): |
5. The encoder
Each encoder block has two sub-layers: multi-head self-attention and a feed-forward network. Each sub-layer is wrapped in a residual connection and a LayerNorm, the “Add & Norm” of the diagram.
5.1 Add: the residual connection
A residual connection adds the sub-layer’s input to its output: x + Sublayer(x). It opens a direct lane for information and for gradients. If a sub-layer has learned nothing useful yet, the original information still passes through unchanged, and in backpropagation the gradient flows straight back to earlier layers. Without it, deep stacks of layers are hard to train.
It is also why every sub-layer must return the same dimension as its input (512 here): otherwise the two could not be added.
The figure at the end of Section 5.2 shows the addition and the normalisation on one vector.
Another useful way to look at it: the chain of “x plus something, plus something” through the layers is a shared channel. Every attention and feed-forward sub-layer reads from the channel once and adds its result back. Layers do not connect to each other directly; everything goes through the channel. This view is the source of the term “residual stream” in A Mathematical Framework for Transformer Circuits. It fits Pre-LN (Section 5.3) better: in the paper’s Post-LN the channel is normalised again after every sub-layer, so it is rescaled each time.
5.2 Norm: layer normalisation
LayerNorm normalises the 512 numbers of one token by themselves: subtract their mean, divide by their standard deviation (in the implementation √(variance + ε), where ε is a tiny constant that prevents division by zero), then multiply by a learned scale γ and add a learned shift β. It does not involve the other sentences of the batch or the other tokens, so it does not depend on batch size or sentence length, which suits variable-length sequences.
The figure uses a vector of 8 entries instead of 512, with made-up numbers, in the order of the paper: add first, then normalise. It shows two things. The addition keeps all of x and adds the sub-layer’s output to it. LayerNorm then moves the mean of this one vector to 0 and its standard deviation to 1 (the standard deviation here is the population one, and γ = 1, β = 0). Section 5.3 compares this order with the opposite one.
5.3 Post-LN and Pre-LN: where the LayerNorm goes
The LayerNorm can come after the sub-layer or before it. Both are common.
- Post-LN: add, then normalise: LayerNorm(x + Dropout(Sublayer(x))). The paper uses this.
- Pre-LN: normalise, then run the sub-layer: x + Dropout(Sublayer(LayerNorm(x))), plus one more LayerNorm at the very end of the encoder and of the decoder. The Annotated Transformer and the code in this post use this.
Xiong et al. (ICML 2020) explain the difference theoretically. At initialisation, the gradients of Post-LN near the output layer are large, and learning-rate warm-up is needed to keep them in check. The gradients of Pre-LN are well behaved from the start, and warm-up can be dropped. GPT-2 moved the LayerNorm to the input of each sub-block.
The encoder and decoder code below is Pre-LN. To switch to Post-LN you also remove the final
nn.LayerNorm at the end of the encoder and of the decoder, because every sub-layer already
ends with a normalisation.
1 | class SublayerConnectionPostLN(nn.Module): |
5.4 Feed forward: the position-wise network
Two fully connected layers with a ReLU between them. The inner size in the paper is 2048: the 512 dimensions are widened by a factor of 4 and then squeezed back to 512.
The figure follows one token. The vector is widened to 2048 numbers, the negative entries are set to 0 (six made-up entries show this), and W₂ squeezes the result back to 512. The same W₁ and W₂ are used for every token. The figure leaves out the bias terms.
“Position-wise” means each token goes through the network on its own; tokens do not talk to each other, but all positions share the same parameters. A way to remember the division of labour: attention exchanges information between tokens, and the feed-forward network lets each token digest what it received. In one encoder block of the paper’s base size, the feed-forward network has 2.10 M parameters and attention has 1.05 M, so the feed-forward network is 67%, two thirds.
1 | class PositionwiseFeedForward(nn.Module): |
5.5 The padding mask: the other kind of mask
Sentences in a batch have different lengths, so shorter ones are filled at the end with <pad> to
make them equal. Padding positions are not real tokens and must not be attended to. The encoder’s
attention therefore also uses a mask, which hides the columns of every <pad>. This is not the
decoder’s causal mask. In code:
1 | src_mask = (src != pad_id).unsqueeze(-2) # shape (B, 1, n), False at pad |
5.6 Assembling the encoder
1 | class EncoderLayer(nn.Module): |
6. The decoder
Each decoder block has three sub-layers, each with its own Add & Norm:
- Masked multi-head self-attention. The target tokens look at one another, but each sees only itself and the tokens on its left.
- Cross-attention (encoder-decoder attention). Q comes from the output of the sub-layer below; K and V come from the encoder’s memory.
- Feed forward. The same as in the encoder.
6.1 The first sub-layer: the causal mask
In training, the whole answer <Begin> She likes red apples goes in at once (positions 0 to 4). Position
i has to predict token i + 1. If it could see the tokens on its right, it would simply be reading
the answer. The causal mask (also called the subsequent mask) hides them.
The mask is a lower-triangular matrix. 1 means “may look”, 0 means “hidden”:
1 | 0 1 2 3 4 <- the token being looked at |
A degenerate case helps. Normalise each row of this matrix by the number of ones in it, and multiply by V: each token ends up with the average of itself and everything to its left. Attention only replaces these uniform weights with weights learned from Q and K. The shape of the mask does not change.
How the matrix is applied is what matters. Set the scores at hidden positions to −∞ (the code uses −10⁹), because e^(−∞) = 0 and only then are the weights after the softmax exactly 0. If you multiply the scores by 0 instead, the hidden scores become 0, e⁰ = 1, the softmax still gives them weight, and the future leaks in. One row of scores shows the difference (the row of position 1, which may see positions 0 and 1):
| Method | Scores of the row (the last 3 are hidden) | Weights after softmax |
|---|---|---|
| Wrong: multiply by 0 | [2.0, 1.0, 0, 0, 0] | [0.56, 0.21, 0.08, 0.08, 0.08]; the hidden tokens still hold 22.9% |
| Right: set to −∞ | [2.0, 1.0, −∞, −∞, −∞] | [0.73, 0.27, 0, 0, 0] |
Read the figure row by row. The coloured cells are the range a token can see, and it widens as you go down.
1 | def subsequent_mask(size): |
(PAD is the padding token id, defined with the imports above.) The mask the decoder actually uses is the padding
mask AND the causal mask.
6.2 The second sub-layer: cross-attention
This is where the decoder looks back at the source. Its Q, K and V come from different places, so strictly it is not self-attention but cross-attention:
- Q comes from the output of the first sub-layer (masked self-attention plus Add & Norm) in the same decoder block. It says: “this is how far I have written, which part of the source do I need?”
- K and V come from the encoder’s memory. All 6 decoder blocks use the same memory.
Compare this with the shapes in Section 3.3. The score matrix is 5 × 4, not square: its rows are the five target positions and its columns are the four source tokens. Follow the highlighted row of “She”. It becomes one row of scores over the source tokens, one row of weights, and one row of Z.
This layer needs no causal mask: the source sentence is fully known, so every target token may
look at all of it. Only the padding mask is applied, to hide the <pad> tokens of the source.
6.3 Assembling the decoder
In src_attn below, Q is x (the output of the previous sub-layer in this block), and K and V are
both m (the memory).
1 | class DecoderLayer(nn.Module): |
6.4 The output layer: Linear and softmax
Two steps take the decoder output to next-token probabilities:
- Linear. Map each 512-dimensional decoder output to the vocabulary size (for example
37000). The resulting scores are called logits. This matrix can share weights with the target
embedding (Section 2.1;
tie_weightsin Section 7.1 turns that on). - Softmax. Turn the logits into probabilities. The most probable token in row i is the prediction for token i + 1.
In training, the 5 rows for positions 0 to 4 give 5 predictions at once: “She”, “likes”, “red”, “apples”
and <end>. Each is compared with the answer to compute the loss.
1 | class Generator(nn.Module): |
It returns log-probabilities because they are numerically more stable than probabilities.
7. Training and inference
So far this was structure. To run a Transformer you also need to know how it is trained and how it generates.
7.1 Putting the model together
1 | def make_model(src_vocab, tgt_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1, tie_weights=False): |
The paper’s base model has about 65 million parameters (its Table 3) and was trained for 12 hours
on 8 P100 GPUs. With a 37000-token vocabulary, this code has 101.0 M parameters when the weights
are not shared (the default). With tie_weights on, where the two embeddings and the output layer
use one matrix, it has 63.1 M, close to the paper’s figure. The self-tests count both.
7.2 Training: Teacher Forcing
In training the target sentence is shifted by one position. One copy is the decoder’s input and the other is the answer to predict:
| Position | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Decoder input | <Begin> |
She | likes | red | apples |
| Prediction target | She | likes | red | apples | <end> |
This is what “Outputs (shifted right)” means in the paper’s diagram. With the causal mask, one forward pass computes the predictions of all 5 positions.
1 | tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:] |
Here tgt contains <Begin> and <end>. Build tgt_mask from tgt_in, not from tgt, or its
length will not match the decoder input.
7.3 Three training tricks
The paper uses three.
- Learning-rate warm-up. For the first 4000 steps the learning rate rises linearly, then it falls with the inverse square root of the step. At the start the parameters are random, and a large learning rate can make training diverge. The analysis of Xiong et al. in Section 5.3 points out that this is mainly a Post-LN problem: with Pre-LN the warm-up can be shortened or left out. The optimiser is Adam with β₁ = 0.9, β₂ = 0.98 and ε = 10⁻⁹.
- Dropout = 0.1. It is applied to the output of each sub-layer (before the residual addition) and to the sum of embedding and position encoding. The code here also applies it to the attention weights.
- Label smoothing = 0.1. The training target is not “the correct token with 100%” but “the correct token with about 90%, and the remaining 10% spread evenly over the whole vocabulary”. The model becomes less confident, perplexity gets worse, and BLEU improves.
The learning-rate formula:
1 | def rate(step, model_size=512, factor=1.0, warmup=4000): |
The label-smoothed loss is short:
1 | class LabelSmoothingLoss(nn.Module): |
7.4 Inference: one token at a time
At inference there is no answer to feed. Start from <Begin>; at every step send the whole
sequence generated so far through the decoder and take the prediction at the last position as
the next token. The encoder runs once, and the memory is reused at every step.
The simplest strategy picks the most probable token at every step. That is greedy decoding:
1 |
|
This version always produces max_len tokens for the whole batch, and the caller cuts each row at
the first <end>. A decoder for real use would stop a sequence once it emits <end>.
The paper itself uses beam search with a beam of 4: at each step it keeps the 4 most probable partial sequences instead of 1, and in the end picks the one with the best overall score.
Is the mask still needed at inference? The intuitive answer, no, is half right. The code above recomputes all generated positions at every step, and it still passes the causal mask so that the earlier positions are computed exactly as in training. Modern implementations use a KV cache: they store the K and V of earlier positions and compute only the new token each step. Then “cannot see the future” holds by construction, and the mask can be dropped.
8. Three variants: how this structure relates to GPT and BERT
The paper was designed for translation, which is why it has an encoder and a decoder. Most later models keep only one half. By what they keep, they fall into three groups:
| Variant | What is kept | Attention | Typical models | Good at |
|---|---|---|---|---|
| Encoder-decoder | Both halves | Bidirectional in the encoder, causal in the decoder, cross-attention between | The original Transformer, T5, BART, T5Gemma | Translation, summarisation |
| Encoder-only | The left half | Bidirectional self-attention, no causal mask | BERT, RoBERTa | Classification, extraction, retrieval |
| Decoder-only | The right half, without cross-attention | Causal self-attention only | The GPT series, LLaMA, Qwen, DeepSeek | Text generation, chat |
The three differ only in the masks and whether there is cross-attention. The computation inside each sub-layer is exactly what this post described. A decoder-only model translates by putting “source + separator + translation” into one sequence, and causal self-attention does both the reading and the writing, so there is no separate encoder and no memory.
Take Section 6 and remove the cross-attention of Section 6.2, and you have the skeleton of GPT. GPT-2 and its successors also use Pre-LN, the GELU activation and learned position embeddings. Encoder-only models keep the encoder and use bidirectional attention, which gives one vector per token and generates no text. LLM Visualization shows the decoder-only structure.
Decoder-only is not the only choice. In 2025 Google released T5Gemma and T5Gemma 2, which convert pre-trained decoder-only models back into encoder-decoder models. T5Gemma (July 2025) reports comparable or better quality than the decoder-only Gemma at equal inference compute. T5Gemma 2 (December 2025) reports better post-training results than its decoder-only counterparts, without inference-compute measurements. Encoder-decoder models did not leave; they are just no longer the default for large models.
Summary
- A Transformer is an encoder and a decoder with 6 blocks each. Each block is (multi-head) attention and a feed-forward network, wrapped in Add & Norm.
- Self-attention uses Q, K and V to let each token collect information from the others by relevance. Dividing by √d_k keeps the softmax out of its saturated range.
- Training uses Teacher Forcing and the causal mask to compute a whole sentence in parallel; inference generates one token at a time.
- There are two kinds of mask: the padding mask hides
<pad>, and the causal mask hides tokens on the right. Both work by setting the score to −∞, not by multiplying by 0. - Remove the cross-attention and you have the skeleton of GPT; keep only the encoder and you have the skeleton of BERT.
Where to go next
- KV cache: store K and V of earlier positions at inference and compute only the new token (mentioned at the end of Section 7.4).
- Attention memory against length: FlashAttention and related methods (Section 3.3).
- Modern position encodings: RoPE (end of Section 2.2).
- Hands on: run
transformer_minimal.py, change N, d_model and the number of heads, and see how fast the copy task is learned.
Try it
python transformer_minimal.py first runs the self-tests described below, which print one line
each. Then it trains a 2-layer model (d_model 64, 4 heads, weights tied, vocabulary of 12 tokens)
on a copy task: the source is a random token sequence and the target is the same sequence. It
prints the loss during training and the exact-match accuracy of greedy decoding on 200 new
sequences before and after. --steps sets the number of training steps (400 by default). The
self-tests print the lines below. The training that follows, on an x86 server CPU with four
threads and PyTorch 2.13, goes from a loss of 5.49 at step 1 through 1.45, 0.75 and 0.66 at steps
100, 200 and 300 to 0.62 at step 400, and greedy decoding then copies 99.5% of 200 new sequences
exactly. The 400 steps take 13 seconds and the whole script under 30 seconds; two runs gave identical losses. On a 6-core ARM
single-board computer with PyTorch 2.8 the same script reaches 98.0% (loss 0.635 at step 400); its
400 training steps take about 35 minutes while the board is busy with other jobs. Different PyTorch versions and
CPUs draw different random numbers, so the exact figures differ from machine to machine; the
script stops with an error if the accuracy ends below 90%.
1 | self-tests |
References
Basics
- Attention Is All You Need: the original paper.
- The Annotated Transformer (Harvard NLP,
harvardnlp/annotated-transformeron GitHub, MIT licence): the code in this post is based on it. - LLM Visualization: every step of a decoder-only model as a 3D animation.
Further reading
- Phuong and Hutter, Formal Algorithms for Transformers, 2022. The whole Transformer in about 50 lines of pseudocode; the clearest side-by-side of the three variants.
- Xiong et al., On Layer Normalization in the Transformer Architecture, ICML 2020. A theoretical analysis of Pre-LN and learning-rate warm-up.
- Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding, 2021. The RoPE paper.
- Elhage et al., A Mathematical Framework for Transformer Circuits, Anthropic, 2021. Where the residual-stream view comes from.
Reproduce
The code is at rockyshi-dev/transformer-minimal
(MIT licence): transformer_minimal.py and a README. It needs only PyTorch and runs on a CPU: I ran it on an x86 server CPU and on a small ARM board. The
numbers in this post that a program can produce come from its self-tests (python transformer_minimal.py): the parameter counts (101.0 M untied, 63.1 M tied, for the paper’s base
size with a 37000-token vocabulary), the split of one encoder block (2.10 M in the feed-forward
network, 1.05 M in attention), the 22.9% of weight left on hidden positions by multiplying with 0,
and the position-encoding periods. The standard deviations in Section 2.1 follow from the Xavier
formula for a 37000 × 512 matrix. The small vectors and matrices in the figures use made-up numbers
chosen to be easy to follow. The right panel of the softmax figure is one example draw, and the
statistics quoted with it are computed over 100,000 random draws; the snippet in Section 3.4
recomputes them. The nine checks are:
- shapes: memory, decoder output and log-probabilities have the shapes of Sections 1 to 6;
- the causal mask is exactly the lower triangle;
- changing later decoder inputs leaves the outputs at earlier positions unchanged;
- the attention weights above the diagonal are exactly 0;
- appending
<pad>to the source leaves the encoder output at real positions unchanged; - setting masked scores to −∞ leaves 0% of the weight on hidden positions, multiplying them by 0 leaves 22.9%;
- the parameter counts of the base model, untied and tied;
- the split of one encoder block into feed-forward and attention parameters;
- the position-encoding periods of dimensions 0, 16, 64, 256 and 510.