Masked language modeling (BERT)
Overview
Masked Language Modeling (MLM) is a pre-training objective where we randomly mask some tokens in the input sequence and train the model to predict the original masked tokens based on their bidirectional context. This is the core innovation behind BERT (Bidirectional Encoder Representations from Transformers).
WHY does this matter? Traditional language models (like GPT) are unidirectional — they only see words to the left. But understanding language requires seeing BOTH directions. "The bank was steep" vs "The bank was closed" — you need words on BOTH sides to know if we mean riverbank or financial institution.

Unlike next-word prediction (which is causal/autoregressive), MLM is a denoising autoencoder approach — we corrupt the input and learn to reconstruct it.
The Masking Strategy
WHY 15%? Balance between:
- Too low → not enough training signal
- Too high → too much context removed, harder to predict
WHY not 100% [MASK]? The [MASK] token never appears during fine-tuning (downstream tasks), so we'd have a train-test mismatch. By using random tokens 10% and unchanged 10%, the model learns to be robust.
The MLM loss is:
where represents the corrupted sequence (with masks).
DERIVATION from first principles:
-
Start with likelihood: We want to maximize the probability of the original tokens given the corrupted input.
WHY product? Assuming conditional independence of predictions given the context (each masked token predicted independently).
-
Take log for numerical stability:
WHY log? Products of probabilities → underflow. Sums are stable.
-
Negate for minimization: WHY negative? Gradient descent minimizes loss. Maximizing log-likelihood = minimizing negative log-likelihood.
-
Implementation: The probability comes from:
where:
- = contextualized embedding from Transformer at position
- = output embedding for vocabulary token
- This is a softmax over the entire vocabulary
Architecture Details
WHY encoder-only? We're not generating sequences autoregressively. We need bidirectional context for understanding, not left-to-right generation.
Input Representation
The input to BERT combines three embedings (added element-wise):
WHY three types?
- Token embedding: The word/subword itself
- Position embedding: Which position in sequence (learned, not sinusoidal like original Transformer)
- Segment embedding: Which sentence (A or B) — needed for Next Sentence Prediction (NSP), the second pre-training task
After WordPiece tokenization: [CLS] the cat sat on the mat [SEP]
Masking (15% → here we mask "cat"):
[CLS] the [MASK] sat on the mat [SEP]
Token embeddings: Look up in vocab Position embeddings: [0, 1, 2, 3, 4, 5, 6, 7] Segment embeddings: [A, A, A] (all sentence A)
The model outputs hidden states
At position2 (where [MASK] is), we compute:
where projects back to vocabulary size.
Training Process
Input sentence: "The quick brown fox jumps"
Step 1 - Tokenize:
[CLS] the quick brown fox jumps [SEP]
Step 2 - Random selection (15%): Suppose we select tokens at positions {3, 5} (brown, jumps)
Step 3 - Apply masking protocol:
- Position 3: 80% chance →
[MASK] - Position 5: 10% chance → random token, say
"happy"
Result:
[CLS] the quick [MASK] fox happy [SEP]
Step 4 - Forward pass: Transformer encoder produces and
Step 5 - Predict originals:
- At position 3: Compute over vocab. True label: "brown"
- At position 5: Compute over vocab. True label: "jumps"
Step 6 - Compute loss:
Step 7 - Backprop and update weights
WHY this works: The model CANNOT cheat by memorizing position-token mappings because:
- Only 15% masked (not every position)
- Random corruption (10% random, 10% unchanged)
- Bidirectional attention forces using ALL context
Differences from Other Language Models
| Aspect | GPT (Causal LM) | BERT (Masked LM) | T5 (Seq2Seq) |
|---|---|---|---|
| Architecture | Decoder-only | Encoder-only | Encoder-Decoder |
| Attention | Causal (left-to-right) | Bidirectional | Enc: bidirectional, Dec: causal |
| Objective | Predict next token | Predict masked tokens | Span corruption |
| Use case | Generation | Understanding/Classification | Both |
| Context | Unidirectional | Full bidirectional | Bidirectional encoding |
WHY can't GPT use bidirectional attention? Because it's designed for autoregressive generation. If it could "see the future", it would cheat during generation.
WHY can BERT use bidirectional? Because we're not generating — we're encoding for understanding. During fine-tuning (classification, QA), we don't generate, we just need rich representations.
Next Sentence Prediction (NSP)
BERT uses a second pre-training objective alongside MLM:
The loss is:
where the [CLS] token's final hidden state is passed through a binary classifier.
WHY NSP? To help BERT learn sentence-level relationships for tasks like Question Answering and Natural Language Inference.
TOTAL BERT LOSS:
Input to BERT:
[CLS] I went to the store [SEP] I bought some milk [SEP]
NotNext pair:
- Sentence A: "I went to the store."
- Sentence B: "The moon orbits Earth."
- Label: 0
Input:
[CLS] I went to the store [SEP] The moon orbits Earth [SEP]
The model learns to use as a sentence-pair representation.
Fine-tuning BERT
After pre-training with MLM+NSP on massive text corpora, BERT is fine-tuned on downstream tasks:
For classification tasks:
For token-level tasks (NER, POS tagging):
For Question Answering (span extraction): Learn start/end pointers:
WHY this works: The pre-trained bidirectional representations already encode rich contextual information. We just add a thin task-specific layer on top.
Key insight: Same pre-trained model → many different tasks. The "knowledge" is in the encoder weights.
Common Mistakes
Why it feels right: We trained with [MASK], so we should test with [MASK].
The fix: Never use [MASK] during fine-tuning. Downstream tasks have real text, no masks. This is why BERT masks only 80% with [MASK] and uses random/unchanged for the other 20% — to reduce train-test mismatch.
Steel-man: The concern about distribution shift is valid! But the10% random + 10% unchanged in pre-training creates robustness. The model learns: "sometimes there's a [MASK], sometimes not — I need to use context regardless."
Why it feels right: BERT predicts tokens, so it should generate text.
The fix: BERT is an encoder, not a generator. It predicts tokens in parallel given bidirectional context. It has no notion of left-to-right autoregressive generation. For generation, use GPT-style models.
Steel-man: You could technically generate by iteratively masking and predicting, but it's inefficient and incoherent because BERT wasn't trained for sequential generation. Use the right tool for the job.
Why it feels right: If we mask everything, we train on everything.
The fix: The 10% random + 10% unchanged is crucial. If we only saw [MASK], the model would learn a shortcut: "if I see [MASK], predict based on context; if I see real token, ignore it." During fine-tuning (no [MASK]), this fails catastrophically.