Simple Algorithm
Deep Learning · Emergence · 26 min

Pretraining Objectives Compared

Causal, masked, span-corruption and prefix language modeling.

BERT hides 15% of its input and fills it back in. GPT predicts every token from the ones before it. T5 cuts out spans and writes them back; ELECTRA learns to spot forgeries. Each is a different conditional distribution to estimate, with a different share of tokens that teach the model and a different kind of model at the end. This lesson writes every objective as a conditional likelihood, works out what it converges to and how much of each sequence it learns from, and weighs the controlled comparisons behind today's division of labor: decoders for general-purpose language models, encoders for classification and search.

What you’ll learn

  • Write causal, prefix, masked, span-corruption, denoising and replaced-token-detection objectives as conditional likelihoods, and name the distribution each one converges to.
  • Prove that masked language modeling learns per-position conditionals whose product misses the joint distribution of the masked tokens by their total correlation, and explain how permutation language modeling and span corruption restore the dependencies.
  • Derive the Bayes-optimal ELECTRA discriminator, and compute how many positions per sequence carry a loss under each objective.
  • Summarize what the controlled comparisons of Raffel et al. (2020), Clark et al. (2020), Wang et al. (2022) and Tay et al. (2023) found, and what they leave open.
  • Explain why decoder-only models became the default for general-purpose language models while bidirectional encoders remain common for embeddings and classification.

Every objective is a conditional likelihood

Pretraining objectives differ less than their names suggest. Each one draws a corrupted view x~\tilde{\mathbf x} of a text x\mathbf x by a fixed random procedure cc, picks a set of target positions T\mathcal T, and maximizes the log-likelihood of the targets given what each target may see:

max⁡θ Ex∼pdata Ex~∼c(⋅∣x)[∑t∈Tlog⁡pθ(xt ∣ what position t may see)]\max_{\boldsymbol\theta}\ \E_{\mathbf x\sim p_{\text{data}}}\,\E_{\tilde{\mathbf x}\sim c(\cdot\mid\mathbf x)}\Big[\sum_{t\in\mathcal T}\log p_{\boldsymbol\theta}\big(x_t\ \big|\ \text{what position }t\text{ may see}\big)\Big]
The corruption, the targets and the visibility pattern define the objective; the architecture's job is to compute all the targets' predictions in one pass. Raffel et al. (2020) and Tay et al. (2023) organize their comparisons around this view.
ObjectiveWhat the model seesTargetsPositions with a loss
Causal LM (GPT; Radford et al., 2018, 2019)the prefix x<tx_{<t}every next tokenall T−1T-1
Prefix LM (Raffel et al., 2020; UniLM)a prefix, in both directions; the rest causallythe continuationthe continuation only
Masked LM (BERT; Devlin et al., 2019)the text after 15% of positions are selected: 80% of them become [MASK], 10% a random token, 10% stay unchangedthe selected tokens, each predicted separately15%
Span corruption (T5; Raffel et al., 2020)the text with spans (15% of tokens, mean length 3) each replaced by a sentinel unique within the examplethe dropped spans, written by a decoder15%, plus one sentinel per span
Denoising autoencoder (BART; Lewis et al., 2020)the text with spans (lengths drawn from a Poisson distribution with mean 3) each replaced by a single [MASK], and sentences shuffledthe whole original document, written by a decoder100%, mostly copies of visible tokens
Replaced-token detection (ELECTRA; Clark et al., 2020)the text after about 15% of tokens are replaced by samples from a small generatorfor every token: original or replaced?100%, one bit each
BART's large model masked 30% of the tokens and permuted all sentences; because one [MASK] may hide a span of any length, including zero, the model must also infer how many tokens are missing. XLNet's permutation objective, in the next step, belongs to the same family.

What does each objective converge to? Every one is a sum of log losses, and the expected log loss is minimized by the true conditional distribution of the target given what the model sees (the cross-entropy is the entropy plus a KL divergence). With unlimited data and capacity, each objective therefore learns one specific family of true conditionals, and that family determines what the trained model can do. A causal LM learns p(xt∣x<t)p(x_t\mid x_{<t}) for every tt, and by the chain rule their product is the joint distribution: the trained model is an exact sampler. A masked LM learns something weaker.

DerivationProof
  1. E[−log⁡qi(Xi∣x~)]=H(Xi∣x~)+DKL(p(⋅∣x~) ∥ qi)\E\big[-\log q_i(X_i\mid\tilde{\mathbf x})\big]=H(X_i\mid\tilde{\mathbf x})+\KL\big(p(\cdot\mid\tilde{\mathbf x})\,\big\|\,q_i\big)

    The loss is a sum of one term per masked position, and each term involves only its own qiq_i. Fix ii and x~\tilde{\mathbf x}; the expected term splits into an entropy and a KL divergence, so it is minimized exactly at the true conditional:

  2. ∑i∈MH(Xi∣x~)−H(XM∣x~)=E[log⁡p(XM∣x~)∏i∈Mp(Xi∣x~)]\sum_{i\in M}H(X_i\mid\tilde{\mathbf x})-H(X_M\mid\tilde{\mathbf x})=\E\Big[\log\frac{p(X_M\mid\tilde{\mathbf x})}{\prod_{i\in M}p(X_i\mid\tilde{\mathbf x})}\Big]

    At the optimum the loss is the sum of the per-position entropies. Subtract the joint entropy and write both as expectations under the joint p(xM∣x~)p(x_M\mid\tilde{\mathbf x}):

  3. =DKL(p(xM∣x~) ∥ ∏i∈Mp(xi∣x~)) ≥ 0=\KL\Big(p(x_M\mid\tilde{\mathbf x})\ \Big\|\ \prod_{i\in M}p(x_i\mid\tilde{\mathbf x})\Big)\ \ge\ 0

    The right-hand side is the KL divergence from the product of the conditionals to the joint, so it is nonnegative and zero exactly when the joint factorizes.

Check your understanding

A perfectly trained masked LM sees "She ordered [MASK] [MASK] for dinner." In its training data the two blanks are "fried rice" half the time and "ice cream" the other half. You fill both blanks at once, sampling each from the model's prediction for that blank. How often do you get an incoherent pair such as "fried cream"?

  1. Never
  2. 25% of the time
  3. 50% of the time
  4. Always
Show the answer

C. 50% of the time

Each blank's optimal prediction is a 50/50 marginal: fried or ice, rice or cream. Drawn independently, the four combinations each have probability 1/41/4, and two are incoherent. The model's loss on the pair is 2ln⁡2≈1.392\ln2\approx1.39 nats, while the joint has entropy ln⁡2≈0.69\ln2\approx0.69: the difference, ln⁡2\ln2, is the total correlation of the two blanks.

Restoring the dependencies: permutations and spans

Permutation language modeling. XLNet (Yang et al., 2019) keeps the chain rule but randomizes its order. Draw a permutation z\mathbf z of the positions and maximize

Ez∑t=1Tlog⁡pθ(xzt∣xz1,…,xzt−1).\E_{\mathbf z}\sum_{t=1}^{T}\log p_{\boldsymbol\theta}\big(x_{z_t}\mid x_{z_1},\dots,x_{z_{t-1}}\big).

Every order is an exact factorization of the joint distribution, so the dependencies a masked LM loses are kept; averaged over orders, each token is predicted from context on both sides; and no [MASK] ever enters the input, so the mismatch with fine-tuning disappears. The tokens stay at their original positions and the order lives in the attention masks. Since a prediction must depend on which position it is for without seeing that position's token, XLNet runs two attention streams, a content stream and a query stream that sees the target's position but not its token, and it predicts just the last tokens of each order to ease optimization. In the dinner example, the order "first blank, then second" costs −log⁡12−log⁡1=ln⁡2-\log\tfrac12-\log1=\ln2 nats, exactly the joint entropy. This any-order objective returns in Beyond Left-to-Right: Multi-Token & Diffusion LMs, where masked diffusion turns out to optimize it in disguise.

Span corruption. T5 restores the dependencies with architecture instead. The encoder reads the corrupted text, in which each dropped span is replaced by its own sentinel token, and the decoder writes the dropped spans one token at a time, each span after its sentinel, ending with a final sentinel. The decoder is autoregressive, so the tokens it writes condition on each other: span corruption models the joint distribution of the missing tokens given the visible ones. It is also cheap, because the decoder writes only what was removed:

DerivationSequence lengths under span corruption
  1. ncorrupt=rT=76.8,nspans=rTμ≈25.6n_{\text{corrupt}}=rT=76.8,\qquad n_{\text{spans}}=\frac{rT}{\mu}\approx25.6

    Corrupt a fraction rr of TT tokens in spans of mean length μ\mu. With T5's r=0.15r=0.15, μ=3\mu=3 and T=512T=512:

  2. Tin=T−rT+rTμ≈461,Tout=rT+rTμ+1≈103T_{\text{in}}=T-rT+\frac{rT}{\mu}\approx461,\qquad T_{\text{out}}=rT+\frac{rT}{\mu}+1\approx103

    The input keeps the visible tokens and gains one sentinel per span; the target holds the corrupted tokens, one sentinel per span and a final sentinel:

  3. ToutT≈0.20\frac{T_{\text{out}}}{T}\approx0.20

    A decoder that rewrote the whole text would process 512 positions; this one processes about 103. Raffel et al. found mean span lengths from 2 to 5 about equally good, and with i.i.d. token corruption, rates from 10% to 25% about equally good, with 50% worse.

Architecture (parameters, cost)Denoising objectiveLanguage-modeling objective
Encoder–decoder (2P2P, MM)83.2879.56
Prefix LM decoder (PP, MM)81.8279.68
Causal decoder (PP, MM)74.7073.78
GLUE scores after fine-tuning in Raffel et al.'s (2020) controlled comparison of base-size models pretrained on about 34 billion tokens. PP counts the parameters of one 12-layer stack and MM the FLOPs per sequence: the encoder–decoder has twice the parameters at the same cost, because each token passes through only one of its two stacks. In this fine-tuning setting the denoising objective beat language modeling for every architecture, and among objectives BERT-style denoising (82.96) beat prefix language modeling (80.69) and deshuffling (73.17).

How much of each sequence teaches the model

Objectives also differ in how many training signals one pass extracts from a sequence. A causal LM scores every position. BERT scores only the 15% it selected, although its encoder processes all of them. Devlin et al. (2019) reported that their masked model converged marginally slower than a left-to-right model, which predicts every token, and that its gains on downstream tasks far outweighed that cost. Signals per token are a crude currency, since a target predicted from both sides is easier and carries different information than a next token, but they set how much a fixed budget of text can teach.

python
import torch

def bert_mask(tokens, mask_id, vocab_size, p=0.15):
    """BERT's corruption: select ~15% of positions; of those, 80% -> [MASK], 10% -> random, 10% unchanged."""
    labels = tokens.clone()
    chosen = torch.rand(tokens.shape) < p
    labels[~chosen] = -100                                   # positions F.cross_entropy ignores
    r = torch.rand(tokens.shape)
    inputs = tokens.clone()
    inputs[chosen & (r < 0.8)] = mask_id
    swap = chosen & (r >= 0.8) & (r < 0.9)
    inputs[swap] = torch.randint(vocab_size, tokens.shape)[swap]
    return inputs, labels             # loss: F.cross_entropy(logits.flatten(0, 1), labels.flatten())

Every label outside the selected positions is −100-100, so the loss ignores about 85% of the sequence. The selected tokens that stay unchanged still carry labels, so any visible token might be a target and the encoder must represent every token well.

Predict before you look

A causal LM trained on 100 billion tokens receives about 100 billion next-token targets. How many tokens must a masked LM with 15% masking process to receive as many targets, in billions?

Show the answer

667 B

100/0.15≈667100/0.15\approx667 billion tokens, 6.76.7 times as many. The ratio counts targets, not information: a masked token predicted from both sides is a different, often easier, target than a next token, so the ratio does not measure efficiency by itself. ELECTRA's ablation below measures what learning at every position is worth.

Replaced-token detection. ELECTRA (Clark et al., 2020) makes every position a target by asking a cheaper question. A small generator, itself a masked LM, refills the selected positions with plausible samples; the main network, the discriminator, labels every token of the result as original or replaced, and a sample that happens to equal the original counts as original. The two are trained together, with the discriminator's loss weighted by λ=50\lambda=50, and only the discriminator is kept for fine-tuning. What does the discriminator learn?

DerivationProof, and what it means
  1. D∗(w∣c)=P(token=w, original∣c)P(token=w∣c)D^*(w\mid c)=\frac{P(\text{token}=w,\ \text{original}\mid c)}{P(\text{token}=w\mid c)}

    The binary cross-entropy is a log loss on the label, so its expected value is minimized by the posterior probability of the label given everything the discriminator sees, here the token ww and its context:

  2. P(w,orig.)=(1−m) p(w)+m p(w) q(w),P(w)=(1−m) p(w)+m q(w)P(w,\text{orig.})=(1-m)\,p(w)+m\,p(w)\,q(w),\qquad P(w)=(1-m)\,p(w)+m\,q(w)

    The token is ww and original if the position was left alone and the data put ww there, or if it was refilled, the data put ww there and the generator drew ww again. It is ww at all if it was left alone with x=wx=w, or refilled with a draw of ww:

  3. D∗=(0.968, 0.895, 0.628)D^*=(0.968,\ 0.895,\ 0.628)

    Dividing gives the proposition. With m=0.15m=0.15, data probabilities p=(0.6,0.3,0.1)p=(0.6,0.3,0.1) over three candidates and generator probabilities q=(0.3,0.3,0.4)q=(0.3,0.3,0.4), the optimal outputs are 0.9680.968, 0.8950.895 and 0.6280.628: a token the generator proposes more often than the data would looks suspicious.

  4. q=p ⟹ D∗(w∣c)=1−m+m p(w∣c)q=p\ \Longrightarrow\ D^*(w\mid c)=1-m+m\,p(w\mid c)

    The discriminator thus learns how the data distribution compares with the generator's at every position. If the generator is perfect, q=pq=p, the target collapses to 1−m+m p(w∣c)1-m+m\,p(w\mid c) and carries a weak signal; if it is poor and proposes tokens the data rarely use, D∗D^* is near 00 for those tokens and near 11 for the rest, and replacements are easy to spot. Clark et al. found generators a quarter to half the discriminator's size worked best.

ELECTRAAll-Tokens MLMReplace MLMELECTRA 15%BERT
85.084.382.482.482.2
GLUE scores from Clark et al.'s (2020) efficiency analysis. ELECTRA 15% computes the discriminator loss only at the selected positions; Replace MLM is BERT with generator samples instead of [MASK]; All-Tokens MLM predicts the identity of every token. Restricting the loss to 15% of the positions removed almost all of ELECTRA's advantage over BERT, while removing [MASK] from the inputs gained only 0.2 points: the advantage comes mostly from learning at every position. At larger scale, ELECTRA-Large matched RoBERTa and XLNet on GLUE with less than a quarter of their pretraining compute.

Which objective won, and why

Raffel et al. measured performance after fine-tuning each model on each task. Wang et al. (2022) asked a different question at a larger scale: which combination generalizes zero-shot, to tasks the model was never trained on? They pretrained six models of about 5 billion parameters (11 billion for the encoder–decoders) on 168 billion tokens: causal decoders, non-causal (prefix) decoders and encoder–decoders, each with an autoregressive or a masked language-modeling objective. They evaluated all of them on 30 tasks, with and without multitask prompted finetuning on 13 billion tokens. Three findings:

  • Directly after pretraining, the causal decoder trained autoregressively generalized best zero-shot.
  • After multitask finetuning, the models with non-causal attention over their input trained with masked language modeling performed best.
  • Pretrained models can be converted. A non-causal decoder pretrained with masked language modeling became a good generative causal decoder through continued autoregressive training, and a causal decoder could be adapted cheaply into a non-causal one that was competitive after multitask finetuning.

Mixtures of denoisers. Tay et al. (2023) argued that the architecture and the objective should be chosen separately, and trained one model on a mixture of seven denoisers. R-denoisers are T5-style span corruption at 15% with mean span lengths of 3 or 8. The S-denoiser is prefix language modeling with, on average, the last quarter of the text as target. X-denoisers corrupt aggressively: spans of mean length 64, or half of the tokens. A paradigm token at the start of the input tells the model which kind of denoising it faces, and the same token selects a mode for a downstream task. In their ablations this mixture beat both T5-style and GPT-style baselines on all nine tasks of their suite, and they scaled it to a 20-billion-parameter model.

Why decoders became the default. As of the mid-2020s, general-purpose language models with published designs are almost all causal decoders. The reasons usually given are structural:

  • One interface. A causal decoder reads and writes with the same next-token distribution, so any task phrased as text needs no new output head, and GPT-3's in-context learning made that interface the norm.
  • Every token teaches. Every position carries a loss, and the same model trains, scores and generates.
  • Cheap continuation. Appending tokens never changes earlier states under a causal mask, so a prompt's keys and values can be kept in a KV cache and reused across a conversation; a bidirectional encoder must recompute every state whenever its input changes.

None of this is a theorem. In the fine-tuning comparisons above, encoder–decoders and denoising objectives were stronger at equal compute, and mixtures improved on both sides. Where the product is a fixed representation of a text, as in retrieval embeddings, classification and tagging, bidirectional encoders remain the usual choice.

Key takeaways

  • Every pretraining objective is a conditional log-likelihood after a corruption: causal LM (prefix to next token), prefix LM, masked LM (visible tokens to each masked token separately), span corruption and denoising (visible tokens to the missing text, written autoregressively), and replaced-token detection (corrupted text to "original or not" at every position).
  • Log loss is minimized by the true conditionals, so a causal LM learns an exact sampler, while a masked LM learns per-position conditionals whose product misses the joint by the masked tokens' total correlation; permutation orders and autoregressive decoders restore the dependencies.
  • A causal LM and ELECTRA train on every position, a masked LM and span corruption on about 15%; ELECTRA's optimal discriminator compares the data with the generator, and its ablation credits most of its gain to the loss on all tokens.
  • Controlled comparisons disagree by setting: denoising encoder–decoders won after fine-tuning at base scale, causal decoders won zero-shot after pretraining alone, masked non-causal models won after multitask finetuning, and mixtures of denoisers improved on both.
  • Decoders became the default for general-purpose models because one causal model reads, writes and learns from every token and its states can be cached; bidirectional encoders remain the usual choice for embeddings and classification.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does T5's span corruption model the dependencies among the missing tokens when BERT's masked language modeling does not?

  1. Because it masks longer spans
  2. Because its decoder writes the dropped tokens autoregressively, each conditioned on the ones written before it
  3. Because each sentinel token encodes which words were removed
  4. Because it corrupts a larger fraction of the text
Show the answer

B. Because its decoder writes the dropped tokens autoregressively, each conditioned on the ones written before it

The decoder factorizes the targets by the chain rule, ∏kp(yk∣y<k,x~)\prod_kp(y_k\mid y_{<k},\tilde{\mathbf x}), so it can represent any joint distribution of the missing tokens. BERT predicts each masked token separately, which can represent only the product of the per-position conditionals.

Question 2

What does XLNet's permutation objective provide that masked language modeling does not?

  1. Each sampled order is an exact chain-rule factorization of the joint, so predicted tokens condition on each other, and no [MASK] token appears in the input
  2. Context on both sides for every prediction within a single order
  3. A cheaper forward pass than an encoder of the same size
  4. Robustness to shuffled word order in the input
Show the answer

A. Each sampled order is an exact chain-rule factorization of the joint, so predicted tokens condition on each other, and no [MASK] token appears in the input

Under a sampled order, the tt-th prediction conditions on all tokens earlier in that order, including other targets. Averaged over orders, every token is predicted from both sides, without the [MASK] symbol that never appears at fine-tuning time.

Question 3

In ELECTRA, a position is masked with probability mm and refilled by a sample from the generator qq; a sample equal to the original token counts as original. If the generator were perfect, q(⋅∣c)=p(⋅∣c)q(\cdot\mid c)=p(\cdot\mid c), what would the optimal discriminator output for a token ww in context cc?

  1. 1/21/2 for every token
  2. p(w∣c)p(w\mid c)
  3. Exactly 1−m1-m
  4. 1−m+m p(w∣c)1-m+m\,p(w\mid c)
Show the answer

D. 1−m+m p(w∣c)1-m+m\,p(w\mid c)

Put q=pq=p into D∗D^*: (1−m)p+mp2(1−m)p+mp=1−m+m p(w∣c)\frac{(1-m)p+mp^2}{(1-m)p+mp}=1-m+m\,p(w\mid c). The signal that separates tokens is only m p(w∣c)m\,p(w\mid c), small and noisy, which fits ELECTRA's finding that generators a quarter to half the size of the discriminator worked best.

Question 4

In Wang et al.'s (2022) comparison of models with about 5 billion parameters, which combination generalized best zero-shot directly after unsupervised pretraining, before any multitask finetuning?

  1. An encoder–decoder trained with masked language modeling
  2. A non-causal decoder trained with masked language modeling
  3. A causal decoder trained with autoregressive language modeling
  4. All combinations performed about equally
Show the answer

C. A causal decoder trained with autoregressive language modeling

Without finetuning, the causal decoder trained on next-token prediction was best. After multitask prompted finetuning, the non-causal models trained with masked language modeling came out ahead, and pretrained models could be adapted across both choices.

Further reading

  • J. Devlin, M.-W. Chang, K. Lee & K. Toutanova, "BERT: Pre-training of deep bidirectional transformers for language understanding," NAACL (2019).
  • C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li & P. J. Liu, "Exploring the limits of transfer learning with a unified text-to-text transformer," JMLR 21 (2020).
  • K. Clark, M.-T. Luong, Q. V. Le & C. D. Manning, "ELECTRA: Pre-training text encoders as discriminators rather than generators," ICLR (2020).
  • T. Wang, A. Roberts, D. Hesslow, T. Le Scao, H. W. Chung, I. Beltagy, J. Launay & C. Raffel, "What language model architecture and pretraining objective work best for zero-shot generalization?," ICML (2022).
  • Y. Tay et al., "UL2: Unifying language learning paradigms," ICLR (2023).