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

  1. 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.
  2. 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.
  3. 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> She gives “likes”, and so on until it predicts <end>.
  4. 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.

Encoder and decoder with six blocks each; the encoder output, called memory, feeds the cross-attention sub-layer of every decoder block; Linear and softmax appear once, at the top of the decoder. The source tokens are written in pinyin.

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
2
3
4
5
import copy, math
import torch
import torch.nn as nn

PAD, BOS, EOS = 0, 1, 2 # token ids used by the masks, the loss and the decoding loop

The skeleton of the whole model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class EncoderDecoder(nn.Module):
def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):
super().__init__()
self.encoder, self.decoder = encoder, decoder
self.src_embed, self.tgt_embed = src_embed, tgt_embed # token embedding + position encoding
self.generator = generator # Linear + log-softmax

def encode(self, src, src_mask):
return self.encoder(self.src_embed(src), src_mask) # memory

def decode(self, memory, src_mask, tgt, tgt_mask):
return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)

def forward(self, src, tgt, src_mask, tgt_mask):
return self.decode(self.encode(src, src_mask), src_mask, tgt, tgt_mask)

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.

Four token ids each pick one row of the embedding table; the four rows are multiplied by the square root of 512, about 22.6, and added to a 4 by 512 position-encoding matrix, which gives X. The source tokens are written in pinyin.

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.Embedding initialisation 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
2
3
4
5
6
7
8
class Embeddings(nn.Module):
def __init__(self, d_model, vocab):
super().__init__()
self.lut = nn.Embedding(vocab, d_model) # lookup table, vocab x d_model
self.d_model = d_model

def forward(self, x): # x: token ids, (batch, n)
return self.lut(x) * math.sqrt(self.d_model)

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:

PE(pos, 2i)=sin⁡(pos100002i/dmodel),PE(pos, 2i+1)=cos⁡(pos100002i/dmodel)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)

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.

Sine curves of dimensions 0, 16, 64 and 256 over positions 0 to 40: low dimensions turn fast and high dimensions turn slowly.

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
2
3
4
5
6
7
8
9
10
11
12
13
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout, max_len=5000):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1) # pos
div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)) # 1 / 10000^(2i/d)
pe[:, 0::2] = torch.sin(position * div_term) # even dimensions
pe[:, 1::2] = torch.cos(position * div_term) # odd dimensions
self.register_buffer("pe", pe.unsqueeze(0)) # not trained

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

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.

Left: q equal to 1, 2, 0, minus 1 and k equal to 2, 1, 3, 1 give four element-wise products whose sum is 3. Right: two vectors pointing the same way give a large positive dot product, perpendicular vectors give 0, and opposite vectors give a negative one.

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:

Q=XWQ,K=XWK,V=XWV,WQ,WK∈Rdmodel×dk,  WV∈Rdmodel×dvQ = XW^Q, \quad K = XW^K, \quad V = XW^V, \qquad W^Q, W^K \in \mathbb{R}^{d_{\text{model}} \times d_k},\; W^V \in \mathbb{R}^{d_{\text{model}} \times d_v}

Panel a: entry row 1, column 2 of a 2 by 3 matrix times a 3 by 2 matrix is row 1 of the first times column 2 of the second, 1 times 0 plus 2 times 1 plus 3 times 1, which is 5. Panel b: in 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.

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

Attention(Q,K,V)=softmax(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

In computation order there are four steps, here for 4 tokens:

  1. Score. QKᵀ gives a 4 × 4 score matrix. Entry (i, j) is how much token i attends to token j.
  2. Scale. Divide by √d_k (= 8).
  3. Normalise. Apply a softmax to each row, so each row becomes weights that sum to 1.
  4. 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₄.
Four 2-D value vectors, v1 equal to 4, 1, v2 equal to 1, 4, v3 equal to minus 3, 2 and v4 equal to 3, minus 3, are scaled by the weights 0.3, 0.2, 0.2 and 0.3 and placed head to tail; the arrow from the start to the end is z equal to 1.7, 0.6. The numbers are illustrative.

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.

X of 4 by 512 times three 512 by 64 matrices gives Q, K and V of 4 by 64; Q times K transposed gives 4 by 4 scores, which are scaled by 8 and passed through a row-wise softmax; the weights times V give Z of 4 by 64. Box sizes grow with the dimensions but are not to scale.

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.
Left: the scores 2, 1, 0.5, 0 become the exponentials 7.39, 2.72, 1.65, 1.00 with sum 12.76, and the weights 0.58, 0.21, 0.13, 0.08. Right: one example draw with d_k equal to 64 and 8 keys; without scaling nearly all the weight, 0.99, sits on one key, and with the scores divided by 8 the weight is spread over several keys.

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np

rng = np.random.default_rng(0)
N, d_k, n_keys = 100_000, 64, 8 # 100,000 draws of one query and 8 keys
q = rng.standard_normal((N, 1, d_k), dtype=np.float32)
k = rng.standard_normal((N, n_keys, d_k), dtype=np.float32)
scores = (q * k).sum(-1) # q . k for every key: shape (N, 8)

def softmax(s):
e = np.exp(s - s.max(-1, keepdims=True))
return e / e.sum(-1, keepdims=True)

for name, s in (("raw q.k", scores), ("q.k / 8", scores / np.sqrt(d_k))):
top = softmax(s).max(-1) # the largest weight in each draw
print(f"{name}: std {s.std():.2f}, median largest weight {np.median(top):.2f}, "
f"above 0.9 in {100 * (top > 0.9).mean():.2f}% of the draws")

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
2
3
4
5
6
7
8
9
def attention(query, key, value, mask=None, dropout=None):
d_k = query.size(-1)
scores = query @ key.transpose(-2, -1) / math.sqrt(d_k) # score, then scale
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9) # masked positions get a very small score
p_attn = scores.softmax(dim=-1) # softmax over each row
if dropout is not None:
p_attn = dropout(p_attn)
return p_attn @ value, p_attn

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
Q, K and V of 4 by 512 are cut by columns into 8 heads of 64 columns; each head attends separately and gives 4 by 64; the heads are concatenated to 4 by 512 and multiplied by W O, giving an output of the same shape as the input.

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:

MultiHead(Q,K,V)=Concat(head1,…,headh) WO,headi=Attention(QWiQ, KWiK, VWiV)\mathrm{MultiHead}(Q,K,V) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\,W^O, \qquad \mathrm{head}_i = \mathrm{Attention}(QW_i^Q,\, KW_i^K,\, VW_i^V)

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.

Each 512-number row of the projected matrix is cut by view into 8 consecutive pieces of 64 numbers, which changes no number, and transpose swaps the token index and the head index, so that head 1 owns its piece of every token: the shape goes from n by 512 to n by 8 by 64 to 8 by n by 64. One small box stands for 64 numbers.

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
super().__init__()
assert d_model % h == 0
self.d_k, self.h = d_model // h, h
self.linears = nn.ModuleList([nn.Linear(d_model, d_model) for _ in range(4)]) # W^Q, W^K, W^V, W^O
self.attn = None
self.dropout = nn.Dropout(p=dropout)

def forward(self, query, key, value, mask=None):
if mask is not None:
mask = mask.unsqueeze(1) # the same mask for every head
B = query.size(0)
# 1) one projection, then split into h heads: (B, n, d_model) -> (B, h, n, d_k)
query, key, value = [
lin(x).view(B, -1, self.h, self.d_k).transpose(1, 2)
for lin, x in zip(self.linears, (query, key, value))
]
# 2) all heads attend in parallel
x, self.attn = attention(query, key, value, mask=mask, dropout=self.dropout)
# 3) concatenate: (B, h, n, d_k) -> (B, n, d_model)
x = x.transpose(1, 2).contiguous().view(B, -1, self.h * self.d_k)
# 4) multiply by W^O
return self.linears[-1](x)

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.

LayerNorm(x)=γ⊙x−μσ2+ϵ+β,μ,σ2 are the mean and variance of the 512 components of x\mathrm{LayerNorm}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta, \qquad \mu, \sigma^2 \text{ are the mean and variance of the 512 components of } x

An example vector of 8 entries instead of 512, with illustrative numbers: the input x has mean 0.49 and standard deviation 1.03, the sub-layer output has mean 0.51 and standard deviation 0.60, their sum has mean 1.00 and standard deviation 1.24, and after LayerNorm the mean is 0.00 and the standard deviation is 1.00.

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class SublayerConnectionPostLN(nn.Module):
"""The paper: LayerNorm(x + Dropout(Sublayer(x)))."""
def __init__(self, size, dropout):
super().__init__()
self.norm = nn.LayerNorm(size)
self.dropout = nn.Dropout(dropout)

def forward(self, x, sublayer):
return self.norm(x + self.dropout(sublayer(x)))


class SublayerConnection(nn.Module):
"""Pre-LN: x + Dropout(Sublayer(LayerNorm(x))). The encoder and the decoder then end with one more LayerNorm."""
def __init__(self, size, dropout):
super().__init__()
self.norm = nn.LayerNorm(size)
self.dropout = nn.Dropout(dropout)

def forward(self, x, sublayer):
return x + self.dropout(sublayer(self.norm(x)))

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.

FFN(x)=max⁡(0,  xW1+b1) W2+b2,W1∈R512×2048,  W2∈R2048×512\mathrm{FFN}(x) = \max(0,\; xW_1 + b_1)\,W_2 + b_2, \qquad W_1 \in \mathbb{R}^{512 \times 2048},\; W_2 \in \mathbb{R}^{2048 \times 512}

A token vector of 512 numbers times W1 of 512 by 2048 gives 2048 numbers; ReLU sets the negative entries to 0, shown on six example entries 0.8, minus 1.3, 0.2, minus 0.4, 1.5, minus 0.7 that become 0.8, 0, 0.2, 0, 1.5, 0; W2 of 2048 by 512 brings the vector back to 512 numbers. The bias terms are left out of the figure.

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
2
3
4
5
6
7
8
9
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super().__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)

def forward(self, x):
return self.w_2(self.dropout(self.w_1(x).relu()))

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class EncoderLayer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout):
super().__init__()
self.size = size
self.self_attn, self.feed_forward = self_attn, feed_forward
self.sublayer = nn.ModuleList([SublayerConnection(size, dropout) for _ in range(2)])

def forward(self, x, mask):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) # Q = K = V = x
return self.sublayer[1](x, self.feed_forward)


class Encoder(nn.Module):
def __init__(self, layer, N):
super().__init__()
self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(N)])
self.norm = nn.LayerNorm(layer.size)

def forward(self, x, mask):
for layer in self.layers:
x = layer(x, mask)
return self.norm(x) # this is the memory

6. The decoder

Each decoder block has three sub-layers, each with its own Add & Norm:

  1. Masked multi-head self-attention. The target tokens look at one another, but each sees only itself and the tokens on its left.
  2. Cross-attention (encoder-decoder attention). Q comes from the output of the sub-layer below; K and V come from the encoder’s memory.
  3. 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
2
3
4
5
6
     0  1  2  3  4   <- the token being looked at
0 [ 1 0 0 0 0 ] <Begin> sees only itself
1 [ 1 1 0 0 0 ] She sees <Begin> and She
2 [ 1 1 1 0 0 ] likes sees 0 to 2
3 [ 1 1 1 1 0 ]
4 [ 1 1 1 1 1 ] apples sees everything

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]
Three 5 by 5 grids: raw scores, the upper triangle set to minus infinity, and the weights after the row-wise softmax in which the upper triangle is exactly 0 and every row sums to 1.

Read the figure row by row. The coloured cells are the range a token can see, and it widens as you go down.

1
2
3
4
5
6
7
8
9
10
11
def subsequent_mask(size):
"""Lower triangle True (may look), upper triangle False (hidden)."""
return torch.triu(torch.ones(1, size, size), diagonal=1) == 0


def make_masks(src, tgt_in, pad_id=PAD):
"""src: (B, n_src) token ids. tgt_in: (B, n_tgt) the decoder input, i.e. the target shifted right by one.
Returns src_mask (B, 1, n_src) and tgt_mask (B, n_tgt, n_tgt): padding mask AND causal mask."""
src_mask = (src != pad_id).unsqueeze(-2)
tgt_mask = (tgt_in != pad_id).unsqueeze(-2) & subsequent_mask(tgt_in.size(-1)).to(tgt_in.device)
return src_mask, tgt_mask

(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.
Q of 5 by 64 from the decoder times K transposed of 64 by 4 from the source memory gives a 5 by 4 score matrix whose rows are the five target positions and whose columns are the four source tokens; after dividing by 8 and a row-wise softmax, the 5 by 4 weights times V of 4 by 64 give Z of 5 by 64. The row of the target position, She, is highlighted in every matrix.

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class DecoderLayer(nn.Module):
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
super().__init__()
self.size = size
self.self_attn, self.src_attn, self.feed_forward = self_attn, src_attn, feed_forward
self.sublayer = nn.ModuleList([SublayerConnection(size, dropout) for _ in range(3)])

def forward(self, x, memory, src_mask, tgt_mask):
m = memory
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask)) # causal self-attention
x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask)) # Q = x, K = V = memory
return self.sublayer[2](x, self.feed_forward)


class Decoder(nn.Module):
def __init__(self, layer, N):
super().__init__()
self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(N)])
self.norm = nn.LayerNorm(layer.size)

def forward(self, x, memory, src_mask, tgt_mask):
for layer in self.layers:
x = layer(x, memory, src_mask, tgt_mask) # every layer reads the same memory
return self.norm(x)

6.4 The output layer: Linear and softmax

Two steps take the decoder output to next-token probabilities:

  1. 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_weights in Section 7.1 turns that on).
  2. 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
2
3
4
5
6
7
class Generator(nn.Module):
def __init__(self, d_model, vocab):
super().__init__()
self.proj = nn.Linear(d_model, vocab) # d_model -> vocabulary size

def forward(self, x):
return self.proj(x).log_softmax(dim=-1) # log-probabilities

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 with the defaults. tie_weights=True shares one matrix between the two embeddings and
the output layer (paper, section 3.4); it needs src_vocab == tgt_vocab."""
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model, dropout)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
position = PositionalEncoding(d_model, dropout)
model = EncoderDecoder(
Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),
Decoder(DecoderLayer(d_model, c(attn), c(attn), c(ff), dropout), N),
nn.Sequential(Embeddings(d_model, src_vocab), c(position)),
nn.Sequential(Embeddings(d_model, tgt_vocab), c(position)),
Generator(d_model, tgt_vocab),
)
if tie_weights:
assert src_vocab == tgt_vocab, "weight sharing needs one vocabulary for both sides"
model.src_embed[0].lut.weight = model.tgt_embed[0].lut.weight
model.generator.proj.weight = model.tgt_embed[0].lut.weight
for p in model.parameters(): # Xavier initialisation
if p.dim() > 1:
nn.init.xavier_uniform_(p)
return model

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
2
3
4
tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:]
src_mask, tgt_mask = make_masks(src, tgt_in, pad_id)
log_probs = model.generator(model(src, tgt_in, src_mask, tgt_mask))
loss = criterion(log_probs, tgt_out)

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:

lr=dmodel−0.5⋅min⁡(step−0.5,  step⋅warmup−1.5),warmup=4000lr = d_{\text{model}}^{-0.5} \cdot \min\left(step^{-0.5},\; step \cdot warmup^{-1.5}\right), \qquad warmup = 4000

1
2
3
def rate(step, model_size=512, factor=1.0, warmup=4000):
step = max(step, 1) # avoid 0 to a negative power
return factor * model_size ** -0.5 * min(step ** -0.5, step * warmup ** -1.5)

The label-smoothed loss is short:

1
2
3
4
5
6
7
8
9
10
11
12
13
class LabelSmoothingLoss(nn.Module):
"""Cross-entropy on log-probabilities, with the target distribution (1 - eps) on the right token and eps spread
evenly over the vocabulary; positions whose target is padding are ignored."""
def __init__(self, smoothing=0.1, pad_id=PAD):
super().__init__()
self.smoothing, self.pad_id = smoothing, pad_id

def forward(self, log_probs, target): # (B, n, V), (B, n)
nll = -log_probs.gather(-1, target.unsqueeze(-1)).squeeze(-1)
uniform = -log_probs.mean(dim=-1)
loss = (1 - self.smoothing) * nll + self.smoothing * uniform
keep = target != self.pad_id
return (loss * keep).sum() / keep.sum()

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
2
3
4
5
6
7
8
9
10
11
12
@torch.no_grad()
def greedy_decode(model, src, src_mask, max_len, start_symbol=BOS):
"""Greedy decoding for a whole batch. The encoder runs once; the decoder re-reads everything generated so far at
every step (the causal mask keeps each earlier position computed as in training). Returns (B, max_len),
starting with <Begin>."""
memory = model.encode(src, src_mask)
ys = torch.full((src.size(0), 1), start_symbol, dtype=src.dtype)
for _ in range(max_len - 1):
out = model.decode(memory, src_mask, ys, subsequent_mask(ys.size(1)).to(src.device))
next_word = model.generator(out[:, -1]).argmax(dim=-1, keepdim=True) # last position only
ys = torch.cat([ys, next_word], dim=1)
return ys

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
Encoder-decoder keeps both halves; encoder-only keeps bidirectional self-attention and the feed-forward network and outputs one vector per token; decoder-only keeps causal self-attention and the feed-forward network, with no cross-attention.

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
2
3
4
5
6
7
8
9
10
self-tests
ok shapes: memory (B, n_src, d), decoder output (B, n_tgt, d), log-probs (B, n_tgt, V)
ok subsequent_mask(5) is the lower triangle
ok causal mask: changing positions 3-4 leaves outputs at positions 0-2 unchanged
ok attention weights above the diagonal are exactly 0
ok padding: appending <pad> to the source leaves the encoder output at real positions unchanged
ok multiply by 0 leaves 22.9% of the weight on hidden positions; -inf leaves 0%
ok base model, vocabulary 37000: 101.0 M parameters untied, 63.1 M with the three matrices tied (paper: 65 M)
ok one encoder block: feed-forward 2.10 M, attention 1.05 M (67% feed-forward)
ok position-encoding periods: dim 0 -> 6.3, 16 -> 8.4, 64 -> 19.9, 256 -> 628, 510 -> 60611 positions

References

Basics

Further reading

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:

  1. shapes: memory, decoder output and log-probabilities have the shapes of Sections 1 to 6;
  2. the causal mask is exactly the lower triangle;
  3. changing later decoder inputs leaves the outputs at earlier positions unchanged;
  4. the attention weights above the diagonal are exactly 0;
  5. appending <pad> to the source leaves the encoder output at real positions unchanged;
  6. setting masked scores to −∞ leaves 0% of the weight on hidden positions, multiplying them by 0 leaves 22.9%;
  7. the parameter counts of the base model, untied and tied;
  8. the split of one encoder block into feed-forward and attention parameters;
  9. the position-encoding periods of dimensions 0, 16, 64, 256 and 510.