Pretraining Objectives: Causal, Masked and Span Corruption
Pretraining turns raw, unlabelled text into a supervised task by hiding part of the text and asking the model to recover it. What is hidden and how the model may look at the rest is the pretraining objective, and it shapes the model more than any other choice: it decides whether the model can generate, how much signal each sequence gives, and what the model is good at after fine-tuning. Self-Supervised Pretraining introduced the idea with masked words in NumPy; this lesson implements the objectives of the real model families exactly: the causal LM of GPT, BERT's masked LM with its 80/10/10 rule, T5's span corruption with sentinel tokens, and ELECTRA's replaced-token detection, and computes each loss on toy logits.
Four ways to hide text
| Objective | Model | What is hidden | What is predicted | Positions with a loss |
|---|---|---|---|---|
| Causal LM | GPT, Llama | the future | every next token | all () |
| Masked LM | BERT, RoBERTa | 15% of tokens | the original tokens at those positions | about 15% |
| Span corruption | T5 | spans, about 15% of tokens, mean length 3 | the spans, written out by a decoder after sentinels | about 15% + sentinels |
| Replaced-token detection | ELECTRA | nothing; some tokens are swapped | for every token: original or replaced? | all (binary) |
All of them are maximum likelihood with a cross-entropy loss (MLE and Cross-Entropy). For the causal LM, the loss of a sequence is
and for masked LM, with the set of chosen positions and the corrupted input,
The difference is in the conditioning: the causal model sees only the past, the masked model sees both sides of the gap (bidirectional context) but only learns from the hidden positions.
Masked LM and the 80/10/10 rule
BERT chooses 15% of the token positions as prediction targets. If all of them were replaced by [MASK], the model would learn representations that are only useful at [MASK] positions, a token that never appears during fine-tuning. So of the chosen positions, 80% become [MASK], 10% a random token and 10% stay unchanged. The model must predict the original token at all of them, so it cannot trust any input token blindly and has to build a good representation of every position. Special tokens ([CLS], [SEP], padding) are never chosen, and the labels of unchosen positions are set to , the index PyTorch's cross-entropy ignores.
import numpy as np
MASK_ID, IGNORE = 0, -100
special = {1, 2} # e.g. [CLS] = 1, [SEP] = 2: never masked
V = 1000
def mask_tokens(ids, rng, p=0.15):
"""BERT's rule. Choose 15% of the (non-special) positions as prediction targets; of those,
80% become [MASK], 10% a random token, 10% stay unchanged. Labels are -100 elsewhere."""
ids = ids.copy()
can = ~np.isin(ids, list(special))
target = (rng.random(ids.shape) < p) & can
labels = np.where(target, ids, IGNORE)
r = rng.random(ids.shape)
to_mask = target & (r < 0.8)
to_random = target & (r >= 0.8) & (r < 0.9)
ids[to_mask] = MASK_ID
ids[to_random] = rng.integers(3, V, size=int(to_random.sum()))
return ids, labels
rng = np.random.default_rng(0)
words = "[CLS] the night ferry crossed the bay while the town slept under a thin moon [SEP]".split()
vocab = {w: i + 3 for i, w in enumerate(dict.fromkeys(w for w in words if w[0] != "["))}
vocab.update({"[CLS]": 1, "[SEP]": 2})
inv = {i: w for w, i in vocab.items()}
inv[MASK_ID] = "[MASK]"
ids = np.array([vocab[w] for w in words])
x, y = mask_tokens(ids, np.random.default_rng(3))
print("input :", " ".join(inv.get(int(i), f"<{int(i)}>") for i in x))
print("labels:", [inv[int(t)] if t != IGNORE else "." for t in y])
# Statistics over a large batch of random sequences.
batch = rng.integers(3, V, size=(2000, 128))
batch[:, 0], batch[:, -1] = 1, 2
x, y = mask_tokens(batch, rng)
t = y != IGNORE
print(f"targets: {t.mean():.4f} of all positions ({t[:, 1:-1].mean():.4f} of non-special ones)")
print(f"of the targets: [MASK] {(x[t] == MASK_ID).mean():.3f}, "
f"random {((x[t] != MASK_ID) & (x[t] != y[t])).mean():.3f}, unchanged {(x[t] == y[t]).mean():.3f}")
print("special tokens ever chosen:", bool(t[:, [0, -1]].any()))input : [CLS] the night ferry [MASK] the bay while the [MASK] slept under a thin moon [SEP]
labels: ['.', '.', '.', '.', 'crossed', '.', '.', '.', '.', 'town', '.', '.', '.', '.', '.', '.']
targets: 0.1478 of all positions (0.1502 of non-special ones)
of the targets: [MASK] 0.801, random 0.100, unchanged 0.099
special tokens ever chosen: False
On the sentence, "crossed" and "town" were chosen and both became [MASK] (with only 14 candidate positions, the 10% cases are rare in one sentence). Over 2000 sequences of 128 tokens the proportions come out as designed: 15.02% of the ordinary positions are targets, of which 80.1% [MASK], 10.0% random, 9.9% unchanged, and special tokens are never chosen. RoBERTa (2019) kept this rule but drew a new mask every time a sequence was seen (dynamic masking) instead of fixing it once during preprocessing, as the original BERT code did.
Span corruption with sentinels
T5 (Raffel et al., 2020) is an encoder-decoder model, so it can afford a cheaper target: replace each corrupted span of consecutive tokens with a single sentinel token (<extra_id_0>, <extra_id_1>, ...) in the input, and let the decoder output only the spans, each introduced by its sentinel, followed by a final sentinel. With a corruption rate of 15% and a mean span length of 3, the input shrinks and the target is short, which makes pretraining cheaper than predicting every token. The implementation follows T5's recipe: split the corrupted tokens into a fixed number of spans of random lengths, and the kept tokens into the same number of stretches, and interleave them.
import numpy as np
def random_segments(total, n, rng):
"""Split `total` items into n non-empty segments of random lengths."""
cuts = np.sort(rng.choice(np.arange(1, total), size=n - 1, replace=False))
return np.diff(np.concatenate([[0], cuts, [total]]))
def span_corrupt(tokens, rng, density=0.15, mean_span=3.0):
n = len(tokens)
n_noise = max(1, round(n * density))
n_spans = max(1, round(n_noise / mean_span))
noise_len = random_segments(n_noise, n_spans, rng) # lengths of the corrupted spans
keep_len = random_segments(n - n_noise, n_spans, rng) # lengths of the kept stretches
inp, tgt, i = [], [], 0
for s, (k, m) in enumerate(zip(keep_len, noise_len)): # keep k tokens, then corrupt m
inp += tokens[i:i + k]; i += k
sentinel = f"<extra_id_{s}>"
inp.append(sentinel) # one sentinel replaces the whole span
tgt += [sentinel] + tokens[i:i + m]; i += m
tgt.append(f"<extra_id_{n_spans}>") # final sentinel ends the target
return inp, tgt, n_noise, n_spans
text = ("the harbour master rang the bell twice , and the fishing boats came home one by one "
"before the storm reached the coast , while the gulls circled low over the grey water").split()
rng = np.random.default_rng(1)
inp, tgt, n_noise, n_spans = span_corrupt(text, rng)
print(f"{len(text)} tokens, {n_noise} corrupted in {n_spans} spans")
print("input :", " ".join(inp))
print("target:", " ".join(tgt))
print(f"input {len(inp)} tokens, target {len(tgt)} tokens (vs {len(text)} to predict for a causal LM)")33 tokens, 5 corrupted in 2 spans
input : the harbour master rang the bell twice , and the fishing boats came home <extra_id_0> one before the storm reached the coast , while the gulls circled low over <extra_id_1>
target: <extra_id_0> one by <extra_id_1> the grey water <extra_id_2>
input 30 tokens, target 8 tokens (vs 33 to predict for a causal LM)
33 tokens, 15% of which is 5 corrupted tokens, in spans: "one by" (from "came home one by one before") and "the grey water" at the end. The encoder reads 30 tokens with two sentinels; the decoder has to produce only 8 tokens, <extra_id_0> one by <extra_id_1> the grey water <extra_id_2>, against 33 for a causal LM over the same text. The sentinel tells the decoder which gap each span belongs to. BART (2019) uses a related denoising objective: it replaces spans with a single [MASK] (text infilling), shuffles sentences, and reconstructs the whole original text with its decoder.
ELECTRA: detect the replaced tokens
ELECTRA (Clark et al., 2020) asks a different question. A small masked-LM generator fills the masked positions with plausible samples; the main model, the discriminator, then labels every token of the result as original or replaced:
Every position now gives a training signal, not just 15%, so ELECTRA reaches a given quality with much less compute than BERT; the paper reports ELECTRA-Small, trained on one GPU for 4 days, outperforming GPT on the GLUE benchmark. Only the discriminator is kept for fine-tuning. If the generator samples the original token, the label is "original": the task is about the content, not about whether the position was masked.
The losses on toy logits
The example computes all four losses for one sequence of 10 tokens from a 12-token vocabulary, with random logits standing in for a model. The point is which positions enter each loss and against what target.
import numpy as np
rng = np.random.default_rng(0)
V, T = 12, 10
x = rng.integers(0, V, size=T) # one sequence of token ids
def ce(logits, targets): # mean cross-entropy, logits (n, V)
z = logits - logits.max(-1, keepdims=True)
logp = z - np.log(np.exp(z).sum(-1, keepdims=True))
return float(-logp[np.arange(len(targets)), targets].mean())
def bce(logit, label): # mean binary cross-entropy from logits
p = 1 / (1 + np.exp(-logit))
return float(-(label * np.log(p) + (1 - label) * np.log(1 - p)).mean())
logits = rng.normal(0, 1, size=(T, V)) # stand-in for a model's output, one row per position
# 1. Causal LM: row t predicts token t + 1, every position but the last is a target.
print(f"causal LM : {T - 1:2d} targets, loss {ce(logits[:-1], x[1:]):.3f}")
# 2. Masked LM: only the masked positions are scored (here positions 2 and 7).
masked = np.array([2, 7])
print(f"masked LM : {len(masked):2d} targets, loss {ce(logits[masked], x[masked]):.3f}")
# 3. Span corruption: the decoder predicts sentinel + span tokens + final sentinel.
span_target = np.array([V - 1, x[4], x[5], x[6], V - 2]) # two sentinel ids at the end of the vocab
dec_logits = rng.normal(0, 1, size=(len(span_target), V))
print(f"span corr.: {len(span_target):2d} targets, loss {ce(dec_logits, span_target):.3f}")
# 4. ELECTRA: a small generator fills the masked positions with samples; the discriminator
# labels EVERY position as original (0) or replaced (1).
gen_probs = np.exp(logits[masked]) / np.exp(logits[masked]).sum(-1, keepdims=True)
corrupted = x.copy()
corrupted[masked] = [rng.choice(V, p=p) for p in gen_probs]
replaced = (corrupted != x).astype(float) # a sampled token equal to the original counts as original
disc_logits = rng.normal(0, 1, size=T)
print(f"ELECTRA : {T:2d} targets, loss {bce(disc_logits, replaced):.3f}, replaced positions {np.flatnonzero(replaced).tolist()}")
print(f"chance levels: ln V = {np.log(V):.3f} per token, ln 2 = {np.log(2):.3f} per binary label")causal LM : 9 targets, loss 2.880
masked LM : 2 targets, loss 1.864
span corr.: 5 targets, loss 2.298
ELECTRA : 10 targets, loss 0.878, replaced positions [2, 7]
chance levels: ln V = 2.485 per token, ln 2 = 0.693 per binary label
The counts are the story: the causal LM gets 9 targets from 10 tokens, masked LM 2, span corruption 5 (3 span tokens plus 2 sentinels), ELECTRA 10 binary labels. Random logits give losses near the chance levels, per token and per binary decision (the values scatter around them because only a few positions are averaged). Here the generator sampled replacements different from the originals at both masked positions, so positions 2 and 7 are labelled "replaced".
Next-sentence prediction, and why it was dropped
BERT had a second objective: given two segments A and B, predict whether B really followed A in the corpus (50%) or was a random segment from another document (50%), from the [CLS] vector through the pooler. The idea was to teach relations between sentences for tasks like question answering. RoBERTa's ablations found that removing NSP and training on full-length contiguous text matched or improved downstream results: the random negative usually comes from a different document, so the task can be solved by detecting a topic change, which says little about coherence. ALBERT replaced it with sentence-order prediction (the same two consecutive segments, swapped or not), a harder task that does need coherence. Most later encoders use masked LM alone.
The library version
Hugging Face's DataCollatorForLanguageModeling implements both main objectives as a batch-building step, so the masking is redrawn for every batch (dynamic masking):
import torch
from transformers import AutoTokenizer, DataCollatorForLanguageModeling
from transformers.utils import logging
logging.set_verbosity_error()
torch.manual_seed(0)
tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
collator = DataCollatorForLanguageModeling(tok, mlm=True, mlm_probability=0.15, seed=0)
texts = [f"ferry number {i} leaves the old harbour at dawn and returns to the island before the evening storm"
for i in range(400)]
enc = [tok(t) for t in texts]
batch = collator(enc)
x, y = batch["input_ids"], batch["labels"]
print("keys:", sorted(batch.keys()), " shapes:", tuple(x.shape), tuple(y.shape))
print("example input :", tok.decode(x[0]))
t = y != -100
orig = y[t]
print(f"targets {t.float().mean().item():.3f} of positions; of them [MASK] {(x[t] == tok.mask_token_id).float().mean().item():.3f}, "
f"random {((x[t] != tok.mask_token_id) & (x[t] != orig)).float().mean().item():.3f}, "
f"unchanged {(x[t] == orig).float().mean().item():.3f}")
print("[CLS]/[SEP] ever targets:", bool(t[:, 0].any() or (y == tok.sep_token_id).any()))
clm = DataCollatorForLanguageModeling(tok, mlm=False) # causal LM: labels = input_ids, padding -> -100
b2 = clm([tok("a short one"), tok("a slightly longer sentence here")])
print("mlm=False labels:", b2["labels"][0].tolist())keys: ['attention_mask', 'input_ids', 'labels', 'token_type_ids'] shapes: (400, 21) (400, 21)
example input : [CLS] ferry [MASK] [MASK] leaves the old harbour at dawn and returns [MASK] the island before the evening storm [SEP] [PAD]
targets 0.127 of positions; of them [MASK] 0.795, random 0.099, unchanged 0.106
[CLS]/[SEP] ever targets: False
mlm=False labels: [101, 1037, 2460, 2028, 102, -100, -100]
With mlm=True it returns input_ids with the 80/10/10 corruption and labels with everywhere except at the targets. In this batch 12.7% of all positions are targets, a little under 15% because [CLS], [SEP] and padding are never chosen, and the split of the targets is 79.5% [MASK], 9.9% random, 10.6% unchanged: the same rule as the NumPy version, with sampling noise. With mlm=False the labels are a copy of the inputs with padding set to ; the model shifts them for the causal LM loss (inside a decoder-only LM).
Pitfalls
- Masking special tokens or padding. Predicting
[PAD]is free accuracy that teaches nothing and inflates the reported MLM accuracy. Exclude special positions before choosing targets. - Computing the MLM loss over all positions. The labels of unchosen positions must be ; otherwise the model learns to copy its input at 85% of the positions.
- Static masks. Masking once during preprocessing shows the model the same gaps every epoch; redraw per batch.
- Comparing losses across objectives. A causal LM loss over all tokens and an MLM loss over 15% of hidden tokens are not comparable numbers, and neither is ELECTRA's binary loss.
- Forgetting the final sentinel or reusing sentinel ids for different spans in T5-style data: the decoder can then no longer tell where a span ends.
- Thinking the objective only matters for pretraining. A model pretrained with MLM cannot generate fluently without further training, and a causal LM gives weaker token-level features for tagging at the same size; choose the family for the downstream task (encoder, decoder, encoder-decoder).
Practice
- With BERT's rule, what fraction of all non-special input tokens is shown to the model as
[MASK], as a random token, and as an unchanged target?
Answer
as [MASK], random, unchanged targets. The remaining 85% are unchanged non-targets.
- A 512-token sequence is pretrained with T5's span corruption (15%, mean span 3). About how many tokens are corrupted, how many spans and sentinels are there, and how long are the encoder input and decoder target?
Answer
corrupted tokens in spans. Input: tokens. Target: tokens (each span's tokens with its sentinel, plus the final sentinel).
- Change
po2.pytodensity=0.5, mean_span=1and run it. How does the task change, and which objective does it start to resemble?
Answer
Half the tokens are corrupted, each span is one token, so almost every other token is a sentinel and the target is long. Each span is a single hidden token predicted from the rest, which is close to a masked LM with a high masking rate, but written out by the decoder.
- Why does ELECTRA label a position "original" when the generator happens to sample the original token there?
Answer
The discriminator sees only the corrupted text. If the token equals the original, there is nothing in the text to detect, and labelling it "replaced" would ask the model to guess where masking happened, an impossible and useless task.
Test yourself
In BERT's masked LM, a chosen target position is shown to the model as…
- always [MASK]
- [MASK] 80% of the time, a random token 10%, the original token 10%
- a random token 50%, [MASK] 50%
- deleted
What does the T5 decoder output for span corruption?
- The whole original text
- Each corrupted span after its sentinel, then a final sentinel
- One label per token: original or replaced
- Only the sentinels
Why is ELECTRA more compute-efficient than BERT's masked LM?
- It uses a smaller vocabulary
- Its discriminator gets a training signal at every position, not only at the 15% masked ones
- It needs no generator
- It uses no attention
Why did RoBERTa drop next-sentence prediction?
- It was too slow
- Removing it matched or improved downstream results; the task was largely solvable by spotting a topic change
- It needs labelled data
- BERT never used it
In a masked-LM batch, the labels of positions that were not chosen are set to…
- 0
- the [MASK] id
- , the index the cross-entropy ignores
- the original token id