Labeled data is expensive: a few thousand annotated sentences for named entity recognition, a few hundred thousand for natural language inference. Unlabeled text, on the other hand, is practically unlimited. Pre-training uses the unlabeled text to learn general knowledge about language, so that each task only has to learn what is specific to it.
This reading covers BERT (Devlin et al., 2019), the model that made “pre-train, then fine-tune” the standard recipe in NLP, and RoBERTa (Liu et al., 2019), which showed how much BERT could gain from a more careful pre-training recipe. Both are encoder-only Transformers: they read a whole text and produce a contextual vector for every token.
1Pre-training and fine-tuning
The recipe has two stages:
- Pre-train a model on a large dataset for a task X whose labels come for free from the text itself (a self-supervised objective), such as predicting missing words.
- Fine-tune the same model on a (much smaller) labeled dataset for the task Y we actually care about.
If doing well on X requires knowledge that also helps with Y, which is true for word prediction and almost any language task, the pre-trained model is a far better starting point than random initialization. Without pre-training, every task (part-of-speech tagging, entity recognition, question answering) trains its own model from scratch on its own data.
We have already met two forms of pre-training. Word2vec pre-trains word vectors by predicting context words, and ELMo pre-trains contextual representations with language models. Both pre-train only the features; the task model on top is still designed and trained from scratch. The models in this reading pre-train the whole network.
| Features | Task model | Example | |
|---|---|---|---|
| No pre-training | task-specific (n-grams, TF-IDF) | trained from scratch | logistic regression on TF-IDF |
| Feature-based | pre-trained, frozen | trained from scratch | word2vec, GloVe, ELMo |
| Fine-tuning | the whole pre-trained network is updated; only a small output layer is new | BERT, RoBERTa | |
Transformer pre-training comes in three architectural families: encoder-only models trained to reconstruct masked tokens (BERT), encoder–decoder models trained to regenerate corrupted spans (e.g., T5, BART), and decoder-only models trained to predict the next token (GPT). This reading covers the first.
2BERT
BERT (Bidirectional Encoder Representations from Transformers) is a stack of Transformer encoder layers: every token attends to every other token in both directions, in every layer. It was pre-trained on English Wikipedia (about 2.5 billion words) and BooksCorpus (about 0.8 billion words) with two self-supervised objectives: masked language modeling and next sentence prediction.
Input representation
- Text is split into subwords with WordPiece (a vocabulary of about 30,000 pieces); rare words are broken into pieces marked with
##. - A special
[CLS]token is placed first; its output vector serves as a summary of the whole input for classification. A[SEP]token ends each segment. - The input vector of each token is the sum of three embeddings: a token embedding, a segment embedding (sentence A or B), and a position embedding (learned, up to 512 positions).
bert-base-uncased tokenization of a sentence pair. Each column's input vector is the sum of the token, segment, and position embeddings in that column. Below: how WordPiece splits rare words into known pieces.3Masked language modeling
BERT's main objective: randomly choose 15% of the input tokens, hide them, and train the model to predict the original tokens from their output vectors (a softmax over the vocabulary). To predict a hidden word, the model must combine information from the context on both sides, exactly the skill that downstream tasks need.
Why not an ordinary language model?
A left-to-right language model only sees the left context. Simply letting every layer attend in both directions would not work for next-word prediction: through the layers, each position could see the very word it is supposed to predict. Masking solves this: the target words are hidden in the input, so the model can use both directions in every layer. This is BERT's deep bidirectionality, in contrast to ELMo, which only concatenates a separate forward and backward model at the end.
The 80/10/10 rule
The [MASK] token appears during pre-training but never during fine-tuning. To reduce this mismatch, each of the selected 15% of tokens is
- replaced with
[MASK]80% of the time, - replaced with a random token 10% of the time,
- left unchanged 10% of the time,
and in all three cases the model must predict the original token. Since the model never knows which visible tokens might be wrong, it has to build a good representation of every token.
bert-base-uncased: the selected token is replaced by [MASK] and the bars show BERT's top-5 predictions for that position. Try function words, nouns, and subword pieces.4Next sentence prediction
Many tasks (question answering, natural language inference) involve the relationship between two texts, which masked language modeling alone does not directly train. BERT's second objective, next sentence prediction (NSP), feeds two segments A and B and asks the model, using the output at [CLS], whether B really follows A in the original text:
- 50% of the time B is the actual next sentence (IsNext):
[CLS] the man went to [MASK] store [SEP] he bought a gallon [MASK] milk [SEP]; - 50% of the time B is a random sentence from the corpus (NotNext):
[CLS] the man [MASK] to the store [SEP] penguin [MASK] are flightless birds [SEP].
NSP trains the [CLS] representation to capture something about the pair as a whole. Whether it is actually needed was questioned soon after; see RoBERTa below.
5Using BERT
Fine-tuning
To apply BERT to a task, add a small output layer and train the entire network on the task's labeled data. Pre-training provides an excellent weight initialization, so fine-tuning typically takes only 2–4 epochs with a small learning rate (around $2\times10^{-5}$ to $5\times10^{-5}$).
- Sentence-level tasks: a classifier on the
[CLS]output, for a single sentence (e.g., sentiment) or a sentence pair separated by[SEP](e.g., natural language inference). - Token-level tasks: a classifier on every token's output (e.g., BIO tags for named entity recognition), or, for extractive question answering, two vectors that score each paragraph token as the start and end of the answer span.
BERT as a feature extractor
BERT can also be used like ELMo: freeze it and feed its contextual vectors into a separate task model. Each of its layers gives a different representation, so which one should we use? The BERT paper compared options on named entity recognition (CoNLL-2003, development set F1):
Model sizes
| Model | Layers | Hidden size | Attention heads | Parameters |
|---|---|---|---|---|
| BERT-base | 12 | 768 | 12 | ≈110M |
| BERT-large | 24 | 1024 | 16 | ≈340M |
Each comes in an uncased version (text is lowercased and accents are removed) and a cased version (capitalization is kept, which helps tasks where it carries information, such as named entity recognition). Inputs are limited to 512 tokens.
Results
On GLUE, a benchmark of nine sentence-understanding tasks (sentiment, paraphrase, inference, and others), BERT-large reached an average of 82.1, compared with 74.0 for the previous state of the art and 75.1 for OpenAI GPT. The largest gains were on small datasets such as CoLA (8.5k examples: 35.0 → 60.5) and RTE (2.5k examples: 61.7 → 70.1), exactly where pre-trained knowledge matters most.
6RoBERTa
RoBERTa (a Robustly optimized BERT approach) keeps BERT's architecture but re-examines its pre-training choices one by one. The main finding: BERT was significantly under-trained.
| BERT | RoBERTa | |
|---|---|---|
| Masking | static: masks chosen during preprocessing (data duplicated 10 times with different masks) | dynamic: a new mask every time a sequence is fed to the model |
| Next sentence prediction | yes | removed; inputs are full sequences of contiguous sentences |
| Tokenizer | WordPiece, 30K vocabulary | byte-level BPE (as in GPT-2), 50K vocabulary |
| Data | 16GB (Wikipedia + BooksCorpus) | 160GB (adds news, web text, stories) |
| Batch size / steps | 256 sequences, 1M steps | 8K sequences, up to 500K steps |
- Dynamic masking performed comparably to or slightly better than static masking, and avoids duplicating the data.
- Removing NSP matched or slightly improved downstream results, as long as the inputs were long, contiguous text.
- Byte-level BPE can encode any text without unknown tokens. The larger vocabulary increases the parameter count to about 125M (base) and 355M (large).
- More data, bigger batches, longer training gave the largest gains: on the same Books + Wikipedia data, RoBERTa-large already beat BERT-large (e.g., MNLI 89.0 vs. 86.6), and with 160GB of data and 500K steps it reached 90.2 on MNLI and 96.4 on SST-2.
Limitations and what came next
Encoder-only models are excellent for understanding tasks, but they are not language models in the usual sense: they predict masked tokens using context on both sides, so they cannot directly generate text left to right. Generation needs a decoder, leading to encoder–decoder models (T5, BART) and decoder-only models (GPT). Other encoder models continued to improve efficiency and accuracy, e.g., ALBERT (parameter sharing), ELECTRA (detecting replaced tokens instead of predicting masked ones), and DeBERTa (an improved attention mechanism).
7Summary
- Pre-train on unlabeled text with a self-supervised objective, then fine-tune the whole network on each task.
- BERT is a Transformer encoder; its input is WordPiece tokens with
[CLS]/[SEP]and token + segment + position embeddings. - Masked language modeling (15%, with the 80/10/10 rule) makes deep bidirectional representations possible.
- Next sentence prediction trains
[CLS]on sentence pairs; RoBERTa showed it is unnecessary. - Fine-tuning adds a small output layer on
[CLS](sentence tasks) or on every token (token tasks, span start/end). - RoBERTa: dynamic masking, no NSP, byte-level BPE, 10× data, bigger batches, longer training.
8Practice
Exercise 1: masking
An input has 200 tokens. Under BERT's masking scheme, about how many tokens are replaced with [MASK], replaced with a random token, and left unchanged but still predicted?
[MASK], 3 become random tokens, and 3 stay unchanged. All 30 are prediction targets.
Exercise 2: fine-tuning heads
Describe the output layer for (a) sentiment classification with 3 labels, (b) named entity recognition with 9 BIO tags, (c) extractive question answering. Use BERT-base (hidden size 768).
[CLS] output. (b) A $768\times 9$ linear layer + softmax applied to every token's output. (c) Two vectors in $\mathbb{R}^{768}$, a start vector and an end vector; each paragraph token's output is dotted with them, and a softmax over tokens gives the start and end probabilities.
Exercise 3: why mask?
Why can't BERT simply be trained as a left-to-right language model with bidirectional attention in every layer?
Quick quiz
9Further reading
- Devlin, Chang, Lee & Toutanova (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL.
- Alammar. The Illustrated BERT, ELMo, and co.
- Liu et al. (2019). RoBERTa: A Robustly Optimized BERT Pretraining Approach.
- Hugging Face. LLM Course, Chapter 3: Fine-tuning a pretrained model. (Hands-on fine-tuning in code.)
- Rogers, Kovaleva & Rumshisky (2020). A Primer in BERTology: What We Know About How BERT Works. TACL.