cat /en/llm-transformer-and-training/
MDN-119:25

The Transformer and its training

· Artificial Intelligence · 7 min read

In the previous parts we looked at the pieces one at a time: text becomes tokens, tokens become embeddings, and attention lets each token look at the others. Now it is time to assemble the complete engine. The result is called the Transformer, the architecture proposed in “Attention Is All You Need” (Vaswani et al., 2017), and it is the heart of almost every large language model.

In this part we follow a sentence through the model, from the input to the prediction of the next word, and then we look at how such a thing is trained and why it takes so much computation.

From the input to the first block

GPT-style models use only the “decoder” half of the original Transformer: a stack of identical blocks that read text from left to right. Take the sentence “the cat sleeps on”. The journey starts like this:

  1. Tokens. The tokenizer splits the text and gives each piece a number, its index in a vocabulary that usually holds tens of thousands of entries.
  2. Embedding. Each index selects a row from a large table of learned numbers: the token becomes a vector of d dimensions (the model’s “width”). Four tokens become a 4 × d matrix.
  3. Position. Attention on its own knows nothing about order: to it, “the cat sleeps” and “sleeps the cat” are the same set of vectors. That is why information about position is added. The 2017 paper added to each embedding a vector made of sines and cosines at different frequencies; many later models use learned positions instead, or “rotary” encodings, which rotate the vectors according to their position. The form changes, the need is the same.

Inside a block, up to the output

The matrix enters the first block, which contains two main parts.

  • Masked multi-head self-attention. Each token gathers information from the tokens before it. The causal mask forbids it from looking ahead: during training the model has to predict the next word and must not peek at the answer. There is more than one head, and each can specialise in different relationships.
  • Feed-forward network. This is a small MLP applied to each token separately: it widens the vector (usually to 4 times the width), applies a non-linearity and returns to the original size. If attention mixes information between tokens, the MLP processes it within each token.

Around these two parts there are two crucial tricks. Residual connections add the input of each sub-block to its output: the signal always has a “shortcut”, and the gradient can pass through dozens of blocks without fading away. Layer normalisation brings each vector back to a controlled scale. In 2017 normalisation came after the sum (“Add & Norm”, as in the demo); later GPT models moved it before each sub-block, a variant that makes training more stable.

The most important detail is that a block’s output has the same shape as its input. That is why blocks can be stacked: 12, 48, 96… Each block refines the representation of every token in the light of the context.

At the top of the stack we take the vector of the last token, the one for “on”, and multiply it by a matrix that produces a score (logit) for every entry in the vocabulary. Often this matrix is the embedding table itself, transposed. Softmax turns the scores into probabilities that add up to 1: “the”, “a”, “my”… One token is chosen, appended to the text, and the process starts again. This is how an LLM generates, one token at a time.

In the demo you can follow this journey stage by stage on a toy model, looking at the shape of the data at every step. In the right-hand panel you can instead “build” a real model on paper and estimate its parameters.

DEMO The Transformer step by step · about this demo · full screen ↗

What to try in the demo

  • Press Auto and watch how the shape stays 4 × 8 throughout the blocks, except inside the MLP, where it widens to 4 × 32.
  • Stop at attention: the top-right triangle is empty, that is the causal mask. Notice that the first row always gives weight 1 to the first token, because it has nothing else to look at.
  • Choose the GPT-2 · 124M preset and then GPT-2 · 1.5B: the sizes published in 2019 give about 124 million and 1.5 billion parameters with the formula ≈ 12·L·d² + V·d.
  • Double the width d, then the number of layers: in the first case the block parameters quadruple, in the second they double.
  • Change the heads and the context: the parameter count does not move, but the number of attention scores to compute grows.

How it is trained: guessing the next word

A freshly created Transformer has random weights and produces meaningless probabilities. Pre-training teaches it one single thing: predicting the next token, on huge amounts of text. Every sentence in the corpus provides thousands of exercises for free: given “the cat sleeps”, what is the next token? Thanks to the causal mask, in a single pass the model makes the prediction for every position in the sequence.

The error is measured with cross-entropy: the negative logarithm of the probability given to the correct token. If the model gives 90% to the right word the loss is small; if it gives it 1%, the loss is large. The gradient of this loss, computed with backpropagation, updates all the weights; the optimiser is almost always a variant of Adam. This is repeated for hundreds of thousands of steps, on thousands of GPUs, for weeks or months.

Why GPUs in particular? Almost all the work of a Transformer consists of matrix multiplications, and GPUs are built to carry out thousands of multiplications and additions in parallel. Moreover, unlike recurrent networks, during training the Transformer processes all the tokens of a sequence at the same time: it is precisely this parallelism that made such large models possible.

What grows when models grow

When a model is said to be “bigger”, four knobs are involved: the number of layers, the width d, the number of heads and the length of the context. The parameters, now counted in billions, depend mostly on the first two: each block has about 12·d² of them, one third in attention and two thirds in the MLP.

Kaplan et al. (2020) observed that the loss falls in a regular, predictable way, following a power law, as parameters, data and compute grow: the so-called scaling laws. Hoffmann et al. (2022), with the “Chinchilla” model, refined the recipe: for a given amount of compute, parameters and data should grow together, in the order of twenty training tokens per parameter. Many models of the time were too large for the data they had been trained on.

People also talk about emergent abilities: skills, such as doing simple arithmetic or following a multi-step argument, that seem to appear suddenly beyond a certain size. The idea is debated: some studies show that the jump depends partly on how it is measured, and that with more gradual metrics the improvement looks continuous.

In Python

Here is a minimal decoder block in PyTorch, in the variant with normalisation before each sub-block:

import torch
import torch.nn as nn

class DecoderBlock(nn.Module):
    def __init__(self, d_model=64, n_heads=4):
        super().__init__()
        self.ln1 = nn.LayerNorm(d_model)
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
        self.ln2 = nn.LayerNorm(d_model)
        self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(),
                                 nn.Linear(4 * d_model, d_model))

    def forward(self, x):
        T = x.size(1)
        # causal mask: True = forbidden position (the future)
        mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
        h = self.ln1(x)
        a, _ = self.attn(h, h, h, attn_mask=mask)
        x = x + a                       # residual connection
        x = x + self.mlp(self.ln2(x))   # MLP on each token, plus residual
        return x

block = DecoderBlock()
x = torch.randn(2, 10, 64)   # 2 sequences, 10 tokens, d_model = 64
print(block(x).shape)
print(sum(p.numel() for p in block.parameters()))

The program prints torch.Size([2, 10, 64]), the same shape as the input, and 49984 parameters: almost exactly 12 · 64² = 49,152, plus biases and norms. Stack many of these blocks, add embeddings and a final layer, and you have a small GPT.

To me, the most surprising thing about the Transformer is its simplicity: a few ingredients, repeated many times and trained on an elementary task. But a model that can only continue a text is not yet an assistant that answers questions. How we get from one to the other is the subject of the next part: from model to assistant. If you want to go deeper into the architecture, chapter 10 of my book “Deep Learning con Keras e Tensorflow” (in Italian) covers generative models, attention and Transformers.

The “Inside an LLM” series

  1. From text to numbers: tokenization
  2. Meaning as geometry: embeddings
  3. Predicting the next word
  4. Attention, explained
  5. The Transformer and its training
  6. From model to assistant: fine-tuning, RLHF and RAG