QuiddityML

By · 12 November 2026 · 9 min read

Masked language modeling explained: how BERT is trained

How to turn a sentence into masked inputs and labels, why the loss reads only the hidden positions, what the 80/10/10 recipe changes, and how to write the loss in PyTorch.

Masked language modeling (MLM) is a training task where a model sees a sentence with a few tokens hidden and learns to predict the hidden ones from the tokens on both sides. It is how BERT and many other encoder-only transformers learn about language before anyone fine-tunes them for a task such as sentiment or topic classification. No human labels are needed, because the hidden tokens come from the text itself.

Language models read text as tokens, which can be whole words or pieces of words. The examples here use short words as tokens to keep things simple.

Why an encoder needs its own training task

An encoder-only transformer reads its whole input at once. Inside it, self-attention lets every position mix in information from every other position, left and right. That is useful for understanding a sentence, but it rules out the usual language-model task of predicting the next token from the tokens before it. If every position can see the whole sentence, the next token is already visible and predicting it teaches nothing.

Masked language modeling fixes this by hiding the answer inside the input. Take a complete sentence, replace a few tokens with a special [MASK] token, and train the encoder to recover the originals. The hidden token has real text on both sides, so the model learns to use left and right context together.

The sentence the axolotl swims in tanks with positions 0 to 4. Position 2 is replaced by [MASK], with left context axolotl and right context in. The prediction at position 2 gives swims 0.72, floats 0.16, hides 0.08 and rests 0.04.

In the picture the model has to fill position 2 of "the axolotl ___ in tanks". It gives "swims" a probability of 0.72, and the words on both sides of the gap are what make "swims" the likely answer.

A worked example: inputs and labels

Take the sentence "the cute axolotl" and pick one position to hide, the token "cute". Encoder-only models usually add two special tokens. [CLS] goes at the start and gives the model a first position that can later summarize the whole input. [SEP] marks the end. The corrupted input is:

$$[\text{CLS}],\ \text{the},\ [\text{MASK}],\ \text{axolotl},\ [\text{SEP}]$$

The target at position 2 is the original token "cute", not the visible [MASK]. Every other position gets no target at all.

Original tokens [CLS] the cute axolotl [SEP] become the input [CLS] the [MASK] axolotl [SEP]. The target labels are ignore, ignore, cute, ignore, ignore.

A model works with token ids rather than text. Give a toy vocabulary of 10 entries some ids. The special tokens [CLS], [SEP] and [MASK] get 1, 2 and 3. The tokens "the", "cute" and "axolotl" get 4, 7 and 9. The input ids and the labels are then:

$$\text{input ids}=[1,4,3,9,2]$$

$$\text{labels}=[-100,-100,7,-100,-100]$$

The value $-100$ is a placeholder that means "no target here". PyTorch's cross-entropy skips any label equal to $-100$ by default, so only position 2 counts.

Input ids 1, 4, 3, 9, 2 for [CLS] the [MASK] axolotl [SEP], with the [MASK] id 3 in red. Labels are -100, -100, 7, -100, -100, and -100 means ignore this position in the loss.

What the encoder does with the masked input

The input ids go through an embedding table, which maps each id to a learned vector of length $d_{model}$. [MASK] gets its own learned vector like any other token. BERT-style models add two more vectors to each position. A position embedding says where the token sits, and a segment embedding says which of two input texts the token belongs to. For a single sentence every segment id is 0. The sum is the encoder input $X$, with shape $(1, 5, d_{model})$ for one sentence of 5 tokens.

Input token ids 1, 4, 3, 9, 2 feed three stacked rows: token embedding, position embedding and segment embedding, each of shape 1 x 5 x d_model, added together into X with shape 1 x 5 x d_model.

The encoder then runs full self-attention. The [MASK] position can attend to [CLS] and "the" on its left and to "axolotl" and [SEP] on its right. There is no causal mask, which is the triangular mask a GPT-style decoder uses to hide later tokens. The only mask an encoder usually needs is a padding mask, which hides the filler tokens added when shorter sentences share a batch with longer ones.

Position 2, the [MASK] token, attends to [CLS], the, [MASK], axolotl and [SEP]. The 5 by 5 attention matrix A is fully filled: full self-attention over the corrupted sentence, with a padding mask only when the batch holds padding.

The MLM head and the loss

After the last encoder layer each position has a hidden vector. Stacked together they form $H$, with shape $(B, T, d_{model})$, where $B$ is the batch size and $T$ is the number of tokens. With $B=1$, $T=5$ and a hidden size of 6, $H$ has shape $(1, 5, 6)$.

An MLM head is one linear layer that turns each hidden vector into one score per vocabulary entry. These scores are called logits. With a weight matrix $W_{vocab}$ and a bias $b$:

$$\text{logits}=HW_{vocab}+b$$

With a vocabulary of $V=10$ entries, the logits have shape $(1, 5, 10)$, one row of 10 scores per position.

H, the encoder output with batch 1, positions 5 and hidden size 6, goes through the vocabulary head logits = H W_vocab + b to give logits with batch 1, positions 5 and vocab size 10. Only position 2 is scored.

The head produces logits at every position, and the loss reads only the selected ones. Write $z_t$ for the logits at position $t$, $y_t$ for the label there, and $M$ for the set of positions whose label is not $-100$. The loss is the average negative log-probability of the original tokens at those positions:

$$\mathcal{L}_{MLM}= -\frac{1}{|M|}\sum_{t\in M}\log \text{softmax}(z_t)_{y_t}$$

The softmax turns the 10 scores at a position into probabilities, and the loss is low when the original token gets a high probability. In the example $M=\{2\}$, so the loss is $-\log p(\text{cute})$ at position 2.

Labels -100, -100, 7, -100, -100 over positions 0 to 4, with logit vectors z_0 to z_4 below them. Only z_2 feeds the cross-entropy, which uses position 2 only. M = {2}, the positions with labels other than -100, and ignore_index hides unselected positions from the loss.

In PyTorch the head and the loss fit in one function. It flattens the batch and position axes into rows so that cross_entropy sees one row of logits per token:

1import torch
2import torch.nn.functional as F
3 
4torch.manual_seed(0)
5B, T, d_model, V = 1, 5, 6, 10
6 
7input_ids = torch.tensor([[1, 4, 3, 9, 2]])            # [CLS] the [MASK] axolotl [SEP]
8labels = torch.tensor([[-100, -100, 7, -100, -100]])   # only position 2 is scored
9 
10hidden_states = torch.randn(B, T, d_model)  # stand-in for the encoder output H
11lm_head = torch.nn.Linear(d_model, V)
12 
13def mlm_loss(hidden_states, labels, lm_head):
14    logits = lm_head(hidden_states)                     # (B, T, V)
15    B, T, V = logits.shape
16    loss = F.cross_entropy(
17        logits.reshape(B * T, V),
18        labels.reshape(B * T),
19        ignore_index=-100)
20    return loss, logits
21 
22loss, logits = mlm_loss(hidden_states, labels, lm_head)
23by_hand = -torch.log_softmax(logits[0, 2], dim=-1)[7]
24print(logits.shape)                                     # torch.Size([1, 5, 10])
25print(round(loss.item(), 4), round(by_hand.item(), 4))  # 2.2981 2.2981

The loss and the hand-computed $-\log p(\text{cute})$ at position 2 match, which confirms that the four $-100$ positions were left out. If the loss comes out larger than expected, check that unselected labels really hold $-100$ and not a real token id.

The 80/10/10 corruption recipe

BERT-style training does not replace every selected token with [MASK]. First it selects about 15 percent of the token positions. Of those selected positions, 80 percent become [MASK], 10 percent become a random token from the vocabulary and 10 percent stay unchanged. The label at every selected position is the original token in all three cases.

BERT-style 80/10/10 corruption: the selected token cute becomes [MASK] 80 percent of the time, a random token such as axolotl 10 percent of the time and stays unchanged 10 percent of the time. The target label is cute in every case. Selected positions are about 15 percent of tokens.

The random and unchanged cases are there because the text a model sees after pretraining usually contains no [MASK] tokens. With the recipe, pretraining inputs are not made only of that artificial token at the scored positions, and an ordinary-looking token can also be one the model has to predict.

Here is the recipe as a function, run on 64 sequences of 512 token ids with a vocabulary of 30,000:

1import torch
2 
3def corrupt(input_ids, mask_id, vocab_size, special_ids, p=0.15):
4    labels = input_ids.clone()
5    candidates = ~torch.isin(input_ids, torch.tensor(special_ids))
6    selected = (torch.rand(input_ids.shape) < p) & candidates
7    labels[~selected] = -100                      # score selected positions only
8 
9    corrupted = input_ids.clone()
10    roll = torch.rand(input_ids.shape)
11    to_mask = selected & (roll < 0.8)
12    to_random = selected & (roll >= 0.8) & (roll < 0.9)
13    corrupted[to_mask] = mask_id
14    corrupted[to_random] = torch.randint(4, vocab_size, input_ids.shape)[to_random]
15    return corrupted, labels                      # the other 10% stay unchanged
16 
17torch.manual_seed(0)
18ids = torch.randint(4, 30000, (64, 512))          # 64 sequences of 512 token ids
19ids[:, 0], ids[:, -1] = 1, 2                      # [CLS] and [SEP]
20corrupted, labels = corrupt(ids, mask_id=3, vocab_size=30000, special_ids=[1, 2])
21 
22selected = labels != -100
23print(f"selected: {selected.float().mean():.3f}")                          # selected: 0.149
24print(f"masked:   {(corrupted[selected] == 3).float().mean():.3f}")        # masked:   0.806
25print(f"kept:     {(corrupted[selected] == ids[selected]).float().mean():.3f}")  # kept:     0.092

About 15 percent of positions were selected, about 80 percent of those became [MASK] and about 10 percent kept their original id. The special tokens [CLS] and [SEP] are never selected, since predicting them teaches nothing about the text.

How [CLS] gets used after pretraining

During pretraining [CLS] is one more position that attends to the whole input. After the encoder, its hidden vector is the first row of $H$:

$$h_{cls}=H[:,0,:]$$

with shape $(B, d_{model})$. To classify a whole input, a small classification head reads that vector and gives one logit per class:

$$\text{logits}=h_{cls}W_{class}+b$$

The result has shape $(B, C)$, where $C$ is the number of classes. Fine-tuning then trains this head together with the encoder on labeled examples.

[CLS] for sequence classification: the input positions [CLS] the cute axolotl [SEP] go through the encoder stack with full self-attention. The first row of H, h_cls, feeds a classification head logits = h_cls W_class + b with shape B x C. The same base encoder serves sentiment, topic, entailment or toxicity by swapping the head.

In code, with 3 classes:

1import torch
2 
3B, T, d_model, C = 1, 5, 6, 3
4H = torch.randn(B, T, d_model)       # encoder output
5h_cls = H[:, 0, :]                   # the [CLS] position
6classifier = torch.nn.Linear(d_model, C)
7print(h_cls.shape, classifier(h_cls).shape)   # torch.Size([1, 6]) torch.Size([1, 3])

BERT also used next-sentence prediction

The original BERT pretraining had a second task called next-sentence prediction (NSP). The model received two text segments, marked with segment ids 0 and 1, and used the [CLS] vector to predict whether the second segment really followed the first in the source text.

BERT pretraining used two objectives. Objective 1, masked language modeling: [CLS] the axolotl [MASK] [SEP] with the predicted token at position 3 being swims. Objective 2, next-sentence prediction: [CLS] axolotls breathe [SEP] with segment id 0 and they swim [SEP] with segment id 1, where the [CLS] position predicts is next, yes or no. Later encoder models such as RoBERTa train without next-sentence prediction.

Later BERT-style models such as RoBERTa dropped NSP and trained with masked language modeling alone, using more data and different masking choices. NSP is worth knowing when you read BERT code or configs, while masked language modeling is the part that carried forward.

Common mistakes

Encoder vs decoder vs encoder-decoder transformers places masked language modeling next to next-token training for GPT-style decoders and span corruption for T5. Causal masking explained shows the triangular mask that decoders use and encoders leave out. Self-attention explained works through the attention step that lets the [MASK] position read both sides, and cross-entropy explained covers the loss behind the formula above.

QuiddityML teaches masked language modeling as its own concept in the Intro to NLP track, built on the same "the cute axolotl" example. The exercises include filling in the blanks of the MLM loss function, spotting a wrong ignore_index in it and typing the loss from scratch.