Tokenwerk · The LLM textbook

Chapter 17 · III · Building the transformer · 11 minutes

The complete transformer block

Now we build the Lego brick ChatGPT is made of: the transformer block. Attention, a small network and two clever tricks, and then simply stack lots of them.

A Lego brick for language models

A transformer block is a calculation unit you can chain one after another again and again. In goes a list of numbers for every text position, out comes a list of the same length for every position, just “smarter”. That is exactly why blocks can be stacked like Lego bricks. Small models have a few of them, large language models dozens to over a hundred.

Every block contains two things you already know: attention collects information from the context; the positions talk to each other. Then a small neural network keeps processing the numbers at each position; each position thinks for itself for a moment. On top come two helpers so training works even with many stacked blocks: residual connections and normalization.

What a word experiences in the stack

Let's follow the “bank” from “I get money from the bank” through the model:

  1. Start: the bank gets its embedding, the dictionary entry with all meanings at once.
  2. Block 1, attention: the bank listens to “money” and slides toward financial institution (you know this from the attention chapter).
  3. Block 1, small network: afterwards every position thinks for itself for a moment. Now that it is clear which bank is meant, the network can add what fits: account, counter, transfer.
  4. Block 2, 3, …: the same again, but with an already smarter list of numbers. Attention can now ask finer questions, such as: who is getting what here?
  5. At the very top: the list of numbers at the last position becomes the prediction for the next word.

Researchers often observe that lower blocks deal more with word meaning and nearby grammar, and upper blocks more with larger connections. Nobody prescribes that; it emerges during training. For this stacking to work at all, two tricks are needed.

Trick 1: add instead of replace

Imagine the position has the list [2, 5]. Attention computes a change [0.3, -0.2] from it. Instead of throwing the old away, we simply add the change: [2.3, 4.8]. The original is kept; attention only contributes an addition. That is called a residual connection.

A picture: a document gets revised by many people in turn. Instead of each one rewriting the text completely, everyone only adds margin notes and corrections. The original is never lost. That is why the direct path through all blocks is also called the “residual stream”: a stream that every block contributes something to.

This mainly helps training: the backward pass can run unhindered along the direct addition path all the way to the front (remember the forks from chapter 8? Here is one). Deep networks learn much more easily that way. It is still no guarantee that everything always runs stably.

Trick 2: bring numbers back to a normal size

As numbers run through many blocks, they can keep growing or shrinking, like a sound system with feedback. Normalization brings them back to a uniform size along the way.

An example with the list [1, 3]. The average is 2. Subtract it and [-1, 1] is left. The typical deviation from the average (the standard deviation) is 1 here. Divide by it and [-1, 1] remains. [10, 30] would give the same result: normalization removes the level and the scale; what remains is the pattern.

For [2, 2] the deviation would be zero, and you can't divide by zero. So a tiny safety number called epsilon is added first. And so the model isn't forced to always use exactly normalized values, it gets a learnable multiplier and a learnable shift per component. This variant is called LayerNorm.

Important: LayerNorm computes for each position separately. Different positions and different texts are not mixed; otherwise the future could leak through.

LayerNorm as a formula

LN⁡(x)i=γixi−μσ2+ϵ+βi.\operatorname{LN}(x)_i=\gamma_i\frac{x_i-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta_i.
Symbol Meaning in this formula
x List of numbers of one position
i Which component of the list we are computing
μ\mu (mu) Mean of all components of this list
σ2\sigma^2 (sigma squared) Variance: mean of the squared deviations
ϵ\epsilon (epsilon) Small positive safety constant
γi\gamma_i (gamma) Trainable multiplier for component i
βi\beta_i (beta) Trainable shift for component i
LN⁡(x)i\operatorname{LN}(x)_i The finished normalized i-th component

Read from the inside out: subtract the mean, divide by the (protected) standard deviation, multiply by gamma, add beta. The variance is the average squared deviation; its square root is the standard deviation.

The small network in every block

After attention, every position gets a small thinking network of its own: the feed-forward network, also called MLP (multilayer perceptron, i.e. several layers in a row). You know the principle from chapter 5.

It runs in three steps: first the list of numbers is made wider; D numbers become 4D. Then comes an activation function with a kink. Then the list is computed back down to D numbers. With D = 8: 8 → 32 → 8. The widening gives the network room to work, like a big sheet of scratch paper.

As the activation we use GELU. Unlike ReLU it doesn't cut off negative values hard but bends them down gently. What matters is the same property as in chapter 4: the kink makes the network more expressive than a straight line.

python
self.mlp = nn.Sequential(
    nn.Linear(D, 4 * D),
    nn.GELU(),
    nn.Linear(4 * D, D),
)

The same MLP with the same weights is applied to every position, and it doesn't mix positions. Division of labor: attention handles the exchange between positions, the MLP the processing at each position. It is often said that a large part of a model's “knowledge” sits in the MLP. An example: with “The Eiffel Tower is located in”, attention brings the information “Eiffel Tower” to the last position. The MLP holds weights that make “Paris” more likely from this pattern. So attention is the group conversation, and the MLP is the thinking and remembering afterwards, each on their own.

The MLP as a formula

MLP⁡(x)=W2GELU⁡(W1x+b1)+b2.\operatorname{MLP}(x)=W_2\operatorname{GELU}(W_1x+b_1)+b_2.
Symbol Meaning
W1W_1, b1b_1 Weight table and bias of the first layer
W1x+b1W_1x+b_1 Wider intermediate list, here with 4D components
GELU Activation function, applied to each component separately
W2W_2, b2b_2 Weight table and bias of the second layer
MLP(x) Output with D components again

The whole block in four steps

Now everything comes together:

  1. Normalize the input and compute attention.
  2. Add the result to the original input (residual). Let's call the intermediate result u.
  3. Normalize u and send it through the MLP.
  4. Add the result to u. That's the output.

In code that is two lines:

python
x = x + self.attn(self.norm1(x))
x = x + self.mlp(self.norm2(x))
return x

Because the normalization comes before attention and MLP, this design is called pre-norm. The original transformer from 2017 normalized only after the addition; pre-norm later turned out to be more stable (Xiong et al., 2020).

The block as a formula

u=x+Attention⁡(Norm⁡1(x)),u=x+\operatorname{Attention}(\operatorname{Norm}_1(x)),
y=u+MLP⁡(Norm⁡2(u)).y=u+\operatorname{MLP}(\operatorname{Norm}_2(u)).

x is the input, u the intermediate result, y the output. Norm₁ and Norm₂ are two separate LayerNorms with their own weights. In the second step u is added, not the old x again.

How does the model know where a word is?

Remember? Attention only compares contents. “Dog bites man” and “man bites dog” would be the same to it. That is why every position also carries position information.

In the classic design (as in GPT-2, a well-known model from OpenAI from 2019) there is a second learned table for that: the position embedding. Row 0 for the first position, row 1 for the second, and so on. The position list is simply added to the token list. [0.2, 0.5] (token) and [0.1, -0.2] (position) become [0.3, 0.3]. That way every list of numbers carries both: what and where.

python
pos = torch.arange(T, device=ids.device)
x = self.token_embedding(ids) + self.position_embedding(pos)

arange(T) produces the position numbers 0 to T−1. The catch: the table only has a fixed number of rows. With a context length of 256 there is no row for position 10,000. So when generating, the model only keeps the last 256 tokens in view; whatever came before is forgotten for that step. That is the famous context window. Modern models handle this more elegantly; more on that in the chapter on RoPE.

By the way: our model is a decoder, the kind of transformer that produces text from left to right. The original transformer also had an encoder for translation; we don't need it.

The complete decoder

Now the whole model from front to back:

  1. Look up the token IDs (embedding) and add the position information.
  2. Send them through several transformer blocks.
  3. Normalize once more.
  4. A final layer, the output head, turns each list of numbers into one logit per possible token. With 100 tokens in the vocabulary, that is 100 numbers per position.

Softmax turns them into percentages, and a selection strategy (chapter 21) picks the next token. That is the whole transformer. At its core, ChatGPT is no more than this, just much, much bigger and with far more training.

Counting parameters roughly

A table with D by D weights has D² numbers. Q, K, V and the attention output are four such tables: about 4D². The two MLP tables have D by 4D and 4D by D entries: 8D² together. So one block has roughly 12D² weights, plus a few biases and norm parameters.

With L blocks, V tokens, T positions and a shared input/output table:

N≈VD+12LD2+TD.N\approx VD+12LD^2+TD.

With V = 100, D = 8, L = 2 and T = 16, that is 800 + 1536 + 128 = 2464 weights. Interesting: in large models the middle term dominates; almost all parameters sit in the blocks. The code can count exactly by itself: sum(p.numel() for p in model.parameters()).

Build it yourself: in step 4 of part VII you program the block and the complete decoder.

Key points

  • A transformer block = attention (positions exchange information) + MLP (each position computes for itself), each with normalization before it and a residual addition after it.
  • Residual connections add instead of replace and make deep stacks trainable.
  • The whole model: embedding plus position, many blocks, normalization, output head. That's the decoder.