Contents The Transformer Era Code Course home

Chapter 18Pretrained Transformers: BERT and GPT

Two doors from one building block

Chapter 16 built a block, and this chapter builds the two families that came out of it. The only real difference between them is what each one is allowed to see.

Take the attention of Equation (16.2), apply the causal mask of Equation (16.3) and each position sees only its past, whereas leaving the mask off lets each position see the whole sentence. That single choice is the fork between GPT and BERT and most of what follows is downstream of it, although the table below shows the two also differ in the objective they train against.

GPT BERT
attention masked, left to right unmasked, both directions
objective predict the next token predict masked tokens
natural use generation understanding, labelling
can it generate? yes no

The last row is not a limitation anyone chose, because it falls out of the second row, and Section 18.3.3 explains why.

GPT: pretraining by prediction

GPT (Radford et al. 2018) is a stack of decoder blocks trained on the oldest objective in this book, which is to predict the next token given the tokens so far. That is Equation (10.1) from Chapter 10, with a transformer in place of the count table:

ℒ=−∑ilog⁡p(wi∣w1,…,wi−1).(18.1)\begin{equation} \mathcal{L} \;=\; -\sum_i \log p\big(w_i \mid w_1, \ldots, w_{i-1}\big). \label{eq:gpt-loss} \quad\text{(18.1)} \end{equation}

Nothing in that equation is new, since the n-gram model of Chapter 10 minimised the same quantity and so did the recurrent language model of Chapter 12. What changed is the machinery computing the probability, and how much data it could be fed.

Why the causal mask is not optional here

Without the mask, position ii could attend to position i+1i+1 and read the answer it is being asked to predict, so the loss would fall to nearly zero and the model would learn nothing. This is the reasoning that made </s> a scored token in Chapter 10, because an objective that can be satisfied trivially is the wrong objective. The mask is therefore what makes the task hard enough to be worth solving.

What prediction turns out to teach

The surprise of the GPT line is how much falls out of so little. To predict the next token well across a large corpus a model has to represent a great deal, including syntax, facts, discourse structure and something that functions like reasoning. None of that was asked for, and all of it is instrumental to the one objective.

That claim was made repeatedly and doubted repeatedly, and the evidence for it is in Chapter 19, where models trained this way answer questions they were never trained on.

BERT: pretraining by filling gaps

BERT (Devlin et al. 2019) drops the mask and therefore needs a different objective, because if every position can see every other then next-token prediction is trivial. So BERT hides tokens instead and predicts those, which is masked language modelling, and it is the cloze task from language teaching.

The masking budget

Two numbers define it, and both are trades worth seeing. The first is how much to hide, so take a sequence of 512512 tokens.

rate masked visible gradients per sequence context left
1% 5 507 5 99%
15% 76 436 76 85%
50% 256 256 256 50%
90% 460 52 460 10%

At one per cent you pay for a full forward pass over 512512 tokens and collect five predictions, which is correct and very slow. At ninety per cent you collect plenty of predictions with almost no context to make them from, so the task degenerates into guessing.

BERT chose 1515 per cent, which gives 7676 gradients per sequence with 8585 per cent of the sentence still readable. Later work has found higher rates workable on larger models, so this is a balance point rather than a constant.

The mismatch, and the fix

The second number is subtler, and it repairs a problem the first one creates. The token [MASK] appears in every pretraining batch and never once at fine-tuning time, so a model that keyed on it would break the moment it was used for real. Of the 1515 per cent chosen, BERT therefore does three different things.

treatment share per 100 chosen
replaced with [MASK] 80% 80
replaced with a random token 10% 10
left unchanged 10% 10

The last two rows carry the argument. Because a chosen position might be left unchanged, the model cannot tell which positions were chosen, so it has to build a usable representation of every token rather than only the obviously missing ones.

The random-token row teaches something else again, since it forces the model to notice when a token does not fit its context, and no amount of [MASK] prediction would ever require that.

Why BERT cannot generate

Generation means producing token ii from tokens 11 to i−1i-1, then i+1i+1 from 11 to ii, and so on down the sequence. Every layer of BERT attends in both directions, so position ii has been built from the whole sequence, including positions that do not exist yet during generation.

You could mask BERT at inference time, and it would then be used in a configuration it was never trained in, where it performs badly. This is the same restriction the bidirectional RNN had in Chapter 12, for the same reason: reading both ways and generating left to right are incompatible requirements, and a model has to choose.

The same objective, scaled

The GPT line’s later chapters are mostly one experiment repeated with more of everything in it.

model year parameters context
GPT 2018 117 million 512
GPT-2 2019 1.5 billion 1,024
GPT-3 2020 175 billion 2,048

The architecture barely changed across that table and the objective did not change at all, so what changed was scale, and something unexpected came with it. At GPT-3’s size the model could perform tasks from a description and a few examples in its prompt, with no gradient update at all (Brown et al. 2020).

That is in-context learning and nobody designed it. It is the behaviour that turned language models from a component into a product, and Chapter 19 is about using it.

Where the parameters go

The counting of Chapter 16 scales up unchanged. For a transformer with model dimension DD, LL layers and feed-forward size H=4DH = 4D, each layer costs roughly 12D212D^2, which is 4D24D^2 for the four attention projections and 8D28D^2 for the two feed-forward ones.

configuration DD LL parameters, layers only
BERT base 768 12 85 million
BERT large 1024 24 302 million
GPT-3 12288 96 174 billion

The quadratic in DD is why width is expensive and the linear in LL is why depth is comparatively cheap. Both are dwarfed by the third row, where each of the 9696 layers costs 1.81.8 billion parameters on its own.

What a pretrained model is for

There are two ways of using one, and the field has moved from the first to the second. Fine-tuning continues training on a labelled task, updating all the weights, which is what BERT was designed for, and it works well with a few thousand examples while producing one model per task. Prompting leaves the weights alone and describes the task in the input, so it needs no labelled data and no training run, and one model serves every task.

Fine-tuning generally scores higher when you have the labels, and prompting wins on everything else, while Chapter 24 shows how to get most of fine-tuning’s benefit at a fraction of its cost.

The deeper shift is in what a model is. Before pretraining a model was built for a task, and after it a model is a general capability that tasks are requested from. Part V is about making those requests well, checking the answers, and living with what the model learned from its corpus.

Further reading.

The first GPT paper is Radford et al. (2018), and Brown et al. (2020) reported in-context learning. For BERT itself go to Devlin et al. (2019), whose ablations on the masking scheme are worth the read on their own. Vaswani et al. (2017) remains the architecture both are built from. Jurafsky and Martin (2025) cover the pretraining and fine-tuning pattern with more task detail. Both families are served by transformers, where the choice between them is the difference between AutoModelForMaskedLM and AutoModelForCausalLM, which is the whole of this chapter in two class names.

One mask, two families. State the single architectural difference between GPT and BERT, then derive from it, in order: their objectives, their natural applications, and why one can generate and the other cannot.

The masking budget. For a sequence of 256256 tokens, tabulate masked count, visible count and gradients per sequence at rates of 55, 1515, 4040 and 8080 per cent. Argue for a choice, and name the quantity your argument trades off.

Why not always [MASK]. BERT replaces only 8080 per cent of chosen positions with [MASK]. Explain what each of the other two treatments teaches the model, and predict what would degrade if both were dropped.

Trivial objectives. Explain why next-token prediction without a causal mask has a loss near zero, and connect this to why Chapter 10 insisted that </s> be a scored token.

Count a model. Using 12D212D^2 per layer, compute the layer parameters for D=768,L=12D = 768, L = 12 and for D=1024,L=24D = 1024, L = 24. Confirm the table in this chapter. Which change buys more parameters per unit of DD, doubling depth or increasing width by a third?

Fine-tune or prompt. You have 200200 labelled examples for a niche classification task and no compute budget for training. Argue for one approach. Now you have 50,00050{,}000 examples and a GPU. Argue again, and name what changed your mind.

Ask each model to fill a gap. Give the same sentence with one word removed to a masked model through AutoModelForMaskedLM and to a causal model through AutoModelForCausalLM. Only one of them can use the words after the gap. Report the top five candidates from each, construct a sentence where the right answer is impossible to find without the right context, and show that the causal model cannot find it.

Code for this chapter

Each one reproduces the tables above. Open it in Colab, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.