CSCE 471 Natural Language Processing · Spring 2027

Pre-Trained Encoder Models

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

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.

After reading this, you should be able to explain the pre-train/fine-tune paradigm · compare feature-based and fine-tuning approaches · describe BERT's input representation · explain masked language modeling, including the 80/10/10 rule, and why it enables deep bidirectionality · explain next sentence prediction and why RoBERTa removed it · fine-tune BERT for token-level and sentence-level tasks · list RoBERTa's changes to BERT's pre-training

1Pre-training and fine-tuning

The recipe has two stages:

  1. 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.
  2. 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.

FeaturesTask modelExample
No pre-trainingtask-specific (n-grams, TF-IDF)trained from scratchlogistic regression on TF-IDF
Feature-basedpre-trained, frozentrained from scratchword2vec, GloVe, ELMo
Fine-tuningthe whole pre-trained network is updated; only a small output layer is newBERT, 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

WordPiece examples
Figure 1. The real 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

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.

■ [MASK]  ■ random token  ■ unchanged (still predicted)
Figure 2 (interactive). Masking a 37-token passage. Each click selects about 15% of positions and applies the 80/10/10 rule. Over many samples, the proportions approach 12% / 1.5% / 1.5% of all tokens.
Sentence:Click a token to mask it
Figure 3 (interactive). Real masked-word predictions from 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:

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}$).

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):

Figure 4. BERT-base on named entity recognition (Devlin et al., 2019, Table 7). Fine-tuning the whole model works best, but concatenating the last four layers as frozen features comes close. The embedding layer alone, which is not contextual, is far behind.

Model sizes

ModelLayersHidden sizeAttention headsParameters
BERT-base1276812≈110M
BERT-large24102416≈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.

BERTRoBERTa
Maskingstatic: 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 predictionyesremoved; inputs are full sequences of contiguous sentences
TokenizerWordPiece, 30K vocabularybyte-level BPE (as in GPT-2), 50K vocabulary
Data16GB (Wikipedia + BooksCorpus)160GB (adds news, web text, stories)
Batch size / steps256 sequences, 1M steps8K sequences, up to 500K steps

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

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?

15% of 200 = 30 selected tokens: about 24 become [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).

(a) A $768\times 3$ linear layer + softmax on the [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?

With full bidirectional attention, the representation at position $t$ can attend to the input token at position $t+1$, so predicting the next token becomes trivial copying. Masked language modeling hides the target tokens in the input, so bidirectional attention can be used without leaking the answer.

Quick quiz

9Further reading