Contents The Transformer Era Code Course home

Chapter 19Pretrained Transformers: BERT and GPT

After this chapter you will be able to

  • say how one change of mask separates GPT, BERT and the encoder-decoder family;

  • compute the masking budget of BERT and explain the 80/10/1080/10/10 treatment;

  • explain why BERT cannot generate and why GPT’s objective is not trivial;

  • count the parameters of a transformer from DD and LL;

  • choose between fine-tuning and prompting for a task.

This chapter builds on Chapter 17 and Chapter 18, which supply the block.

Two doors from one building block

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

Take the attention of Equation (17.2), apply the causal mask of Equation (17.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. The table below shows that 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 19.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. This is Equation (10.1) from Chapter 10, with a transformer in place of the count table. The loss is the negative log likelihood:

ℒ=−∑ilog⁡p(wi∣w1,…,wi−1).(19.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{(19.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. The loss would fall to nearly zero and the model would learn nothing. 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. Remove it and the model has learned only to copy.

What prediction teaches

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 20, 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, a fill-in-the-blank exercise.

The masking budget

Two numbers define it, and both are trades. 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%
Figure 19.1. The masking budget for a sequence of 512512 tokens. A higher rate gives more predictions and leaves less to read. The two bars cross near 5050 per cent, and BERT sits at 1515.

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 (when the model is trained further on a labelled task), so a model that keyed on it would break the moment it was used on a task. 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 and not 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 later models of the GPT line 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. 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).

This is in-context learning, and it was not designed. It is the behaviour that turned language models from a component into a product, and Chapter 20 is about using it.

Where the parameters go

The counting of Chapter 17 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.

A third family: encoder and decoder together

The two doors are not the only ones. Translation, in Chapter 14, used an encoder that reads the source and a decoder that writes the target while attending to the encoder. Pretraining the same arrangement gives a third family, which keeps both masks in one model: the encoder is unmasked, the decoder is causal, and the decoder also attends to every encoder state.

Figure 19.2. Which positions each query row may attend to, shaded where attention is allowed. BERT sees every position. GPT sees itself and its past. The decoder of an encoder-decoder uses the causal pattern over its own tokens and, in addition, attends to every encoder state.

The two models of this family that matter most differ in their pretraining objective. Raffel et al. (2020) cast every task as text to text and pretrain T5 by span corruption. Contiguous spans of the input are replaced by sentinel tokens, and the decoder writes out the missing spans in order. Lewis et al. (2020) pretrain BART as a denoising autoencoder. The input is corrupted by masking, deleting, infilling or permuting, and the decoder reconstructs the original text. Take the sentence the cat sat on the mat today. A span-corruption pair looks like this:

encoder input the <X> on the <Y> today
decoder target <X> cat sat <Y> mat <Z>

The encoder sees the whole corrupted sentence in both directions, which is BERT’s advantage. The decoder produces text left to right, which is GPT’s. The model can therefore both understand and generate, and the price is two stacks to train and serve. The table below places the three families side by side.

BERT GPT T5 and BART
encoder, unmasked yes no yes
decoder, causal no yes yes
objective masked tokens next token corrupted spans
natural use labelling, retrieval open generation translation, summarisation

Tasks that map one text to another, such as translation and summarisation, suit the third family because the source has a natural encoder. Open-ended generation and chat have been taken over by the decoder-only family, mostly because one stack scales more simply and prompting makes the encoder unnecessary. Chapter 26 returns to the third family for summarisation.

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. Chapter 25 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.

Summary

One transformer block gives three families depending on what each position may see. A causal decoder, GPT, predicts the next token and can generate. An unmasked encoder, BERT, predicts masked tokens. It hides 1515 per cent of a sequence to balance predictions against context, and it replaces only 8080 per cent of those with a mask token so that it cannot tell which positions were chosen. It cannot generate because every layer reads the future. An encoder and decoder together, as in T5 and BART, are pretrained by reconstructing corrupted text and suit tasks that map one text to another. Scaling the decoder-only model with the same objective produced in-context learning at 175175 billion parameters. A layer costs about 12D212D^2 parameters, so width is expensive and depth is cheaper. A pretrained model is used by fine-tuning on labels or by prompting.

Key terms

masked language modelling. predicting tokens hidden from the input, using context on both sides.

causal language modelling. predicting each token from the tokens before it.

span corruption. replacing spans of the input with sentinels that the decoder must reproduce.

in-context learning. performing a task from a description and examples in the prompt, with no weight update.

fine-tuning. continuing training of a pretrained model on a labelled task.

prompting. describing a task in the input of a frozen model.

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, two class names that carry the whole chapter.

Practice problems

19.1 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.

19.2 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.

19.3 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.

19.4 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?

19.5 A span-corruption pair. Corrupt the sentence the dog chased the ball across the park by replacing two spans of your choice with sentinels. Write the encoder input and the decoder target, and say which of the three families of this chapter could be trained on the pair.

Build and measure

19.6 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.

19.7 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.

19.8 Predict, then probe the mask. Before running, predict how the top candidates for a masked word change when you leave the sentence unchanged but replace the mask token by a random word. Then run the experiment on a masked model and compare.

19.9 The corrupted sentence. Use a BART or T5 checkpoint to reconstruct a sentence with a span removed. Try three span lengths, and say at which length the reconstruction stops matching the original and what it writes instead.

In practice

19.10 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.

19.11 Which family? Choose a family of this chapter for each task and justify the choice: a search engine that must embed ten million documents, a tool that rewrites a paragraph in a different tone, and a chat assistant. Name one cost for each choice.

19.12 Scale and cost. A model’s width doubles and its depth stays fixed. Estimate the change in layer parameters and in the memory for weights at sixteen-bit precision, and say what you would still need to measure to estimate the change in latency.

Code for this chapter

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

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