🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

BERT and Variants: Masked Language Modeling

Natural Language ProcessingBERT and Variants: Masked Language ModelingđŸŸĸ Free Lesson

BERT and Variants: Masked Language Modeling

What You'll Learn

  • 1Write the masked language modeling objective and its 80/10/10 masking policy
  • 2Count the parameters of a transformer encoder layer from its width
  • 3Explain why RoBERTa dropped NSP and why ALBERT factorizes embeddings
  • 4Fine-tune a pretrained encoder on a classification task without forgetting

BERT (Devlin, Chang, Lee, and Toutanova, 2019) made pre-training bidirectional by hiding tokens and asking the encoder to recover them, so one model could be fine-tuned into almost any sentence task. This lesson derives the masked language modeling loss, the 80/10/10 masking policy, the encoder parameter arithmetic behind the 110 million number, and the changes RoBERTa, ALBERT, DistilBERT, and ELECTRA made to the original recipe.

Masked Language Modeling

The encoder reads a sequence in which a random 15 percent of positions have been corrupted, and only the corrupted positions contribute to the loss:

where is the set of masked positions, is the corrupted input, and is a softmax over the vocabulary applied to each hidden state. A naive policy that always replaced with the literal mask token would never appear at fine-tuning time, so BERT keeps 10 percent of selected positions unchanged and 10 percent replaced by a random word:

The next sentence prediction objective was added as a binary head on the first position, and the two losses were trained jointly:

Parameter Arithmetic

One encoder layer is four attention projections and a two layer feed forward network with width , so at width the cost simplifies to:

At that is parameters per layer, and twelve layers give 84.9 million. The embedding table plus layer norm and pooler parameters lands the published total at 110 million.

ALBERT (Lan, Chen, Goodman, Gao, and Yu, 2020) attacks that count twice: it factorizes the vocabulary embedding so a small projection sits between the vocabulary and the hidden width, and it shares one layer across all positions:

with , plus a single layer reused times, which drops BERT-base from 110 million parameters to 12 million while keeping nearly all accuracy.

ModelParametersKey change to the recipe
BERT-base110 millionMLM 15 percent plus NSP
RoBERTa-base125 milliondrop NSP, dynamic masking, 160 GB of text
ALBERT-base12 millionfactorized embeddings, shared layers, SOP
DistilBERT66 millionsix layers distilled from twelve
ELECTRA-base110 millionreplaced token detection on every position

Fine-Tuning the Encoder

Pre-trained weights transfer through a task head that is trained from scratch while the encoder keeps learning at a much smaller rate. A sentence task reads the first position state into a dense classifier, a span task predicts start and end logits over every position, and a token task predicts one label per state, so one checkpoint serves classification, question answering, and sequence labeling without changing the trunk.

The learning rate matters more than the head: schedules of 2e-5 to 5e-5 with 10 percent warmup over three to five epochs beat higher rates, and freezing the lowest layers for the first epoch protects generic features when the labeled set is small. Distillation compresses the same stack by matching softened teacher distributions at temperature :

where are logits from each layer of the teacher and the student, so a six layer student inherits twelve layers of representation at 66 million parameters.

Worked Examples

Worked Code

python
import torch
import torch.nn as nn

def mask_tokens(inputs, tokenizer, mlm_probability=0.15):
    labels = inputs.clone()
    probability_matrix = torch.full(labels.shape, mlm_probability)
    masked_indices = torch.bernoulli(probability_matrix).bool()
    labels[~masked_indices] = -100

    replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
    inputs[replaced] = tokenizer.mask_token_id

    random_words = torch.randint(len(tokenizer), labels.shape, dtype=torch.long)
    random_selector = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices
    random_selector &= ~replaced
    inputs[random_selector] = random_words[random_selector]
    return inputs, labels

class MLMHead(nn.Module):
    def __init__(self, hidden, vocab):
        super().__init__()
        self.dense = nn.Linear(hidden, hidden)
        self.act = nn.GELU()
        self.norm = nn.LayerNorm(hidden)
        self.decoder = nn.Linear(hidden, vocab)

    def forward(self, hidden):
        return self.decoder(self.norm(self.act(self.dense(hidden))))
python
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
                          DataCollatorWithPadding, Trainer, TrainingArguments)

model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)

def tokenize(batch):
    return tokenizer(batch["text"], truncation=True, max_length=256)

args = TrainingArguments(
    output_dir="bert-sst2",
    evaluation_strategy="epoch",
    per_device_train_batch_size=16,
    learning_rate=2e-5,
    num_train_epochs=3,
    weight_decay=0.01,
)
trainer = Trainer(
    model=model,
    args=args,
    train_dataset=dataset.map(tokenize, batched=True),
    eval_dataset=eval_dataset.map(tokenize, batched=True),
    data_collator=DataCollatorWithPadding(tokenizer),
    compute_metrics=compute_metrics,
)
trainer.train()

Real-World Applications

  • Search and retrieval: fine-tuned encoders produce sentence embeddings that rank passages, and Google reported BERT style re-ranking behind web search from 2019.
  • Question answering: a two head span classifier fine-tunes the same checkpoint on SQuAD style data in a few epochs.
  • Efficient serving: DistilBERT keeps 97 percent of accuracy at 66 million parameters, which is what makes on-device classification practical.

💡ELECTRA spends its compute on every token

Instead of supervising 15 percent of positions, ELECTRA trains a small generator to mask and a discriminator to detect the replaced tokens, so 100 percent of positions produce gradient at the same pre-training compute budget.

Common Mistakes

Masking once and reusing the corrupted corpus

Fix: Resample masks every epoch, since a fixed pattern lets the model memorize positions.

Fine-tuning with a learning rate near 1e-3

Fix: Use 2e-5 to 5e-5 with warmup, or catastrophic forgetting wipes the pretrained features.

Feeding raw text to a BERT checkpoint

Fix: Apply the same WordPiece vocabulary, casing, and special tokens used in pre-training.

Best Practices

  • Use dynamic masking so each epoch sees a different corrupted view of the same sentence
  • Keep the classification head learning rate at the same scale as the encoder with a small warmup
  • Evaluate on the validation split after each epoch, since fine-tuning often peaks before the last one

Key Takeaways

  • Masked language modeling supervises only the masked positions, 15 percent of tokens by default
  • One encoder layer is 12 H squared parameters, which is 7.08 million at H = 768
  • ALBERT cuts BERT-base from 110 million to 12 million by factorizing embeddings and sharing layers
  • RoBERTa removed NSP and enlarged the corpus to 160 GB, which improved almost every downstream score

Frequently Asked Questions

Why does BERT use a bidirectional objective while GPT does not?

Causal masking gives GPT a clean factorization of the sequence probability but hides the right context. Masked language modeling deliberately hides tokens and shows both sides, which produces stronger sentence representations for classification at the cost of no direct generation ability.

What replaced next sentence prediction?

RoBERTa found NSP hurt performance and removed it entirely, training on longer concatenated sequences instead. ALBERT replaced it with sentence order prediction, which is harder, but both experiments show that single sentence pre-training is enough when the corpus is long enough.

How much data did BERT see?

The original run used BooksCorpus and English Wikipedia, about 16 GB of text, for one million steps. RoBERTa later trained on 160 GB across four corpora, and that corpus change alone matched many architectural improvements.

Interview Questions

Q1: Why the 80/10/10 split instead of always masking?

Mask tokens never appear during fine-tuning, so 10 percent of selected positions stay original and 10 percent take a random word, which keeps the model robust to input that is never corrupted.

Q2: How many parameters does one BERT-base layer have?

Twelve H squared with H = 768, so 12 times 589,824 equals 7,077,888 per layer, and twelve layers give 84.9 million before embeddings.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement