What is Masked Language Modeling?
Hide words in a sentence and let a bidirectional model guess them back. Click any token to mask it, then watch the model score candidates using context from both sides.
Hide words in a sentence and let a bidirectional model guess them back. Click any token to mask it, then watch the model score candidates using context from both sides.
A causal model reads left to right and predicts what comes next. So it can never look ahead. MLM has no such restriction: the blank sits in the middle. And the model is free to use each token on both sides at once.
Mask soft in "the cat sat on the ___ mat" and the left context narrows it to a modifier while the right context (mat) rules out most adjectives. Neither side alone is enough. That is why MLM gives such strong grasp forms. And why it cannot be used to generate text. BERT masks 15% of tokens in each training case. But not all of them turn [MASK]: 80% are replaced with the mask token, 10% are replaced with a random word, and 10% are left unchanged. The random replacement prevents the model from learning that [MASK] is always present. And the unchanged tokens force it to build good forms even for visible words. The training objective is cross-entropy on only the masked spots. The model predicts over the full vocabulary at each masked slot. And the loss ignores the unmasked spots fully. After pretraining, the MLM head is discarded and the encoder is fine-tuned for downstream tasks (classification, NER, question answering) by attaching a task-set head. MLM cannot generate text because it has no notion of giving tokens left to right. It fills blanks, it does not continue sequences. GPT-style causal language modelling is the pretraining objective for generation. This page masks tokens in a sample sentence, shows the model's top predictions at each spot, and covers the 80/10/10 split and why it matters.
Hide words in a sentence and let a bidirectional model guess them back.
Masked Language Modeling (MLM) is the pretraining objective behind BERT and its descendants. The recipe is deceptively simple: take ordinary text, hide a fraction of the tokens, and train the model to reconstruct exactly what was hidden. No human labels required — the text supplies its own answer key.
A causal model reads left to right and predicts what comes next. So it can never look ahead. MLM has no such restriction: the blank sits in the middle. And the model is free to use each token on both sides at once.
Mask soft in "the cat sat on the ___ mat" and the left context narrows it to a modifier while the right context (mat) rules out most adjectives. Neither side alone is enough. That is why MLM gives such strong grasp forms. And why it cannot be used to generate text. BERT masks 15% of tokens in each training case. But not all of them turn [MASK]: 80% are replaced with the mask token, 10% are replaced with a random word, and 10% are left unchanged. The random replacement prevents the model from learning that [MASK] is always present. And the unchanged tokens force it to build good forms even for visible words. The training objective is cross-entropy on only the masked spots. The model predicts over the full vocabulary at each masked slot. And the loss ignores the unmasked spots fully. After pretraining, the MLM head is discarded and the encoder is fine-tuned for downstream tasks (classification, NER, question answering) by attaching a task-set head. MLM cannot generate text because it has no notion of giving tokens left to right. It fills blanks, it does not continue sequences. GPT-style causal language modelling is the pretraining objective for generation. This page masks tokens in a sample sentence, shows the model's top predictions at each spot, and covers the 80/10/10 split and why it matters.
BERT masks about 15% of tokens, but does not always insert a literal [MASK]. Of the chosen spots:
The reason is a train/test mismatch: [MASK] never appears during fine-tuning or inference. If each masked slot were a literal mask token, the model would learn features that only activate on a symbol it will never see again.
Mask too little and each sentence teaches the model almost nothing. Training is slow because most spots carry no loss. Mask too much and you destroy the very context needed to make a prediction. Around 15% is the long-standing sweet spot, though later work has shown much higher rates can work with large enough models. Drag the rate slider and watch the sentence degrade. At 50% the left context often cannot pin the answer down.
Masked language modelling hides some tokens and trains the model to recover them from both sides of the gap.
"The cat sat on the [MASK]" → predict "mat"
The gap from causal modelling is the way of data flow. Here the model sees all of it except the masked spots, so a token can be predicted from the words after it and before. That bidirectional context is what makes the coming forms strong for grasp tasks. And it is just why the model cannot generate, since there is no notion of "next".
BERT's set recipe masks 15% of tokens, and the composition is deliberate:
| Treatment | Share of masked tokens |
|---|---|
Replaced with [MASK] | 80% |
| Replaced with a random token | 10% |
| Left unchanged | 10% |
The last two look odd and solve a real problem. [MASK] never appears at fine-tuning or inference time, so a model trained only on it would be mismatched with how it is used. Including corrupted and unchanged tokens forces the model to build a good form of each spot, not just the masked ones.
Too little masking and each pass teaches almost nothing. Too much and there is not enough context left to make prediction doable.
15% became the convention, and later work suggests the optimum is task- and scale-dependent. Some studies find 40% works better for larger models.
There is a real speed result either way:
| Masked LM | Causal LM | |
|---|---|---|
| Predictions per forward pass | 15% of tokens | 100% of tokens |
| Sees | Both directions | Past only |
| Can generate | No | Yes |
A causal model extracts a training sign from each spot in one pass; a masked model from roughly one in seven. That is a large gap in training speed. And it is one of a few reasons the field shifted towards causal modelling for large-scale pretraining.
ELECTRA addressed it right with a different objective — a small generator replaces tokens. And the main model classifies each spot as first or replaced. This gives a sign at all spots.
The output of masked pretraining is a model whose hidden states are excellent context forms. That is the product; the mask-filling task was only the means.
Those forms are what get used:
[CLS] spot or pooled states.For all of these, an encoder fine-tuned on a few thousand labelled cases is often as exact as prompting a much larger model, and orders of size cheaper to run. A DistilBERT classifier answers in milliseconds on a CPU.
Predictions come from a small context-scoring model built live in your browser from the demo corpus shown in the vocabulary count. It ranks candidate words by how often they co-occur with the surviving context. It is a genuine math, not a canned list. But it is far simpler than a transformer. Treat the shape of the results as the lesson, not the exact percentages.
MLM turns any raw text into supervised training data by deleting parts of it. Because the blank is surrounded rather than trailing, the model learns deep bidirectional grasp. Ideal for classification, retrieval and question answering, and unsuitable for generation. That generative job belongs to causal models, which predict strictly forward.
| Model | What changed |
|---|---|
| RoBERTa | More data, longer training, dynamic masking, no next-sentence prediction |
| ALBERT | Parameter sharing across layers, factorised embeddings |
| DeBERTa | Disentangled attention for content and position |
| ELECTRA | Replaced-token detection instead of masking |
| DistilBERT | Distilled from BERT: 40% smaller, 60% faster, ~97% of the quality |
RoBERTa is the instructive one. Same design, same objective, and much better results. From training longer on more data with larger batches, masking dynamically (a different mask each epoch rather than one fixed at preprocessing), and dropping BERT's next-sentence-prediction objective. This turned out to be unhelpful.
That is a useful general lesson: BERT's first recipe was not best. And a large part of the later improvement came from training procedure rather than design.
Next-sentence prediction asked whether two segments were adjacent in the first text. It was intended to teach discourse links and mostly taught topic matching. This the masked objective now provided.
The split looked permanent for a few years — encoders for grasp, decoders for generation. What changed is scale: a large decoder, prompted rightly, does classification and extraction well enough that the bidirectional edge stopped being decisive for most uses.
So current practice is roughly:
| Need | Reach for |
|---|---|
| Embeddings for search or clustering | A masked-pretrained encoder, contrastively fine-tuned |
| Cheap high-volume classification | A fine-tuned small encoder |
| Token-level labelling | An encoder |
| Generation of any kind | A decoder |
| Zero-shot or few-shot on an unknown task | A decoder |
| Lowest possible inference cost | An encoder |
The rows favouring encoders share a shape: a fixed task with labelled data and a cost or latency constraint. That describes a great many production systems, which is why BERT-family models remain very widely deployed despite receiving far less attention.
from transformers import AutoTokenizer, AutoModelForMaskedLM
import torch
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForMaskedLM.from_pretrained("bert-base-uncased")
text = "The capital of France is [MASK]."
ids = tok(text, return_tensors="pt")
logits = model(**ids).logits
pos = (ids.input_ids[0] == tok.mask_token_id).nonzero(as_tuple=True)[0]
top = logits[0, pos].topk(5).indices[0]
print(tok.convert_ids_to_tokens(top)) # ['paris', 'lyon', 'marseille', ...]Three things worth knowing when fine-tuning one:
Continued pretraining helps on specialised domains. Running the masked objective on your own unlabelled corpus before supervised fine-tuning often gives a measurable gain, and needs no labels.
The [CLS] form is not a good sentence embedding out of the box. It was not trained for likeness. Use a model fine-tuned contrastively, or masked mean pooling.
512 tokens is the usual limit. Longer documents need chunking, or a long-context variant such as Longformer.
Masked language modelling has two numbers in it that look arbitrary. A 15 percent masking rate and an 80/10/10 split of what to do with each masked token. Both are answers to set problems, and both are visible in the arithmetic.
Building on the same setup, the next block shows the left cases.
The below block covers the left steps.
The next block goes on with the left demonstrations.
Why can BERT not generate text? It has no notion of "next". Its objective assumes nearby context exists. Iterative mask-filling works poorly.
Is masked language modelling obsolete? Not for embeddings and cheap classification, where encoders remain the real choice. For general-purpose models, causal pretraining rules.
Why the 80/10/10 split? Because [MASK] does not exist at fine-tuning time; the random and unchanged cases prevent the model relying on the token's presence.
Should I continue pretraining on my domain? If you have a large unlabelled domain corpus, often yes. It is cheap and often helps.
What is [CLS] for? A spot whose final form is used as a sequence summary for classification.
Can I use a decoder for embeddings? Yes, by pooling hidden states, and purpose-trained embedding models often do better. This is because they are trained with a likeness objective.
[MASK] never appears at fine-tuning time.Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.
Without scrolling back — what is the one-line takeaway from this module?
What does this module say about “Why It Must Be Bidirectional”?
What does this module say about “The Curious 80 / 10 / 10 Split”?
Hide 15 percent of tokens and train the model to reconstruct them using both sides of the sentence — BERT's pretraining objective.