BERT Pre-training › Combined Pre-training Objective
Language AI HandbookAll chapters BERT Pre-training › Combined Pre-training ObjectiveOne section · Sections in this chapter5 / 12 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
So far we've examined BERT's two objectives separately: MLM teaches the model to understand words in context, while NSP teaches it to recognize document-level coherence. But how do these objectives work together during training? The answer lies in how we combine their signals into a single optimization target.
Why Combine Two Objectives?
Consider what each objective teaches in isolation. MLM forces the model to build rich token representations by predicting masked words from surrounding context. A model that excels at MLM understands syntax and semantics, along with factual knowledge encoded in word patterns. However, MLM operates at the sentence level. It doesn't explicitly teach the model whether two sentences belong together or flow logically from one to the other.
NSP addresses this gap. By asking "does sentence B follow sentence A?", the model must develop representations that capture discourse relationships, topic coherence, and logical flow. The [CLS] token becomes a summary of the entire sentence pair, encoding whether they form a coherent unit.
Training on both objectives simultaneously allows the model to develop representations that are rich at multiple levels: tokens capture local meaning, while the [CLS] token captures global coherence. The question becomes: how do we combine these two learning signals?
The Combined Loss Formula
BERT uses the simplest possible combination: add the losses together. Each batch of training data produces two loss values, and the total loss is their sum:
where:
- : the total pre-training loss that BERT minimizes through gradient descent
- : the masked language modeling loss, measuring how well the model predicts masked tokens
- : the next sentence prediction loss, measuring how well the model classifies sentence pairs
This equal weighting (1.0 for each) means both objectives contribute equally to the gradient updates. The model cannot cheat by ignoring one task to optimize the other. It must find parameters that satisfy both constraints simultaneously.
Understanding the MLM Loss Component
The MLM loss measures how surprised the model is by the correct answers at masked positions. If the model confidently predicts the right token, the loss is low. If it assigns low probability to the correct token, the loss is high.
Mathematically, we sum the negative log-probabilities across all masked positions:
Let's unpack each component:
- : the set of masked position indices. For a 512-token sequence with 15% masking, this contains approximately 77 positions.
- : the original token at position before we corrupted it. This is the "ground truth" the model must recover.
- : the corrupted input sequence where masked positions show
[MASK], random tokens, or unchanged tokens (following the 80-10-10 rule). - : the probability our model (with parameters ) assigns to the correct token , given the entire corrupted sequence as context.
The negative sign and logarithm work together to create our loss function. When is close to 1 (confident and correct), , contributing zero loss. When is small (the model missed the answer), becomes a large negative value, and the negative sign makes it a large positive loss. This asymmetry creates strong gradients that push the model to assign high probability to correct tokens.
Understanding the NSP Loss Component
The NSP loss has a simpler structure because it's a binary classification problem. The model looks at the [CLS] token's representation and must decide: IsNext or NotNext?
The symbols in this expression are:
- : the true binary label. We encode IsNext as 1 and NotNext as 0. This comes from how we constructed the training data (50% consecutive pairs, 50% random pairs).
- : the hidden representation of the
[CLS]token after passing through all transformer layers. This 768-dimensional vector (for BERT-base) summarizes the entire sentence pair. - : the probability the model assigns to the correct label, computed by passing through the NSP classification head.
The structure mirrors the MLM loss: negative log-probability of the correct answer. When the model confidently predicts the right class, loss is near zero. When it's wrong or uncertain, loss increases.
How the Losses Interact
Both losses share the same transformer backbone. When we compute the gradient of , it flows back through both the MLM head and the NSP head, then merges in the transformer layers. This means every transformer layer receives gradient signal from both objectives.
The interplay teaches complementary skills:
-
Token embeddings learn to represent individual words in ways that support both masked token prediction (MLM) and sentence-pair understanding (NSP).
-
Attention patterns develop to capture both local dependencies (which tokens help predict a masked word) and global coherence (what makes two sentences related).
-
The
[CLS]token becomes especially important for NSP, learning to aggregate sentence-level meaning, while other positions focus more on token-level prediction.
This multi-task learning is why BERT's representations transfer so well to diverse downstream tasks. The model has learned to encode information at multiple levels of abstraction.

Implementing the Combined Loss
Let's translate these formulas into code. PyTorch's cross_entropy function computes exactly the negative log-probability we described, making the implementation straightforward. The key insight is handling the MLM labels: we use -100 for positions that weren't masked, and PyTorch's ignore_index parameter automatically excludes these from the loss calculation.
def compute_pretraining_loss(
mlm_logits, # (batch, seq_len, vocab_size)
mlm_labels, # (batch, seq_len) with -100 for non-masked
nsp_logits, # (batch, 2)
nsp_labels, # (batch,) with 0 or 1
vocab_size,
):
"""
Compute combined BERT pre-training loss.
"""
# MLM loss (ignores -100 labels automatically)
mlm_loss = F.cross_entropy(
mlm_logits.view(-1, vocab_size), mlm_labels.view(-1), ignore_index=-100
)
# NSP loss
nsp_loss = F.cross_entropy(nsp_logits, nsp_labels)
# Combined loss
total_loss = mlm_loss + nsp_loss
return total_loss, mlm_loss, nsp_lossThe mlm_logits.view(-1, vocab_size) reshapes the predictions from a 3D tensor (batch, sequence, vocabulary) into a 2D tensor (batch × sequence, vocabulary). This flattening allows us to treat each position independently, which matches our formula where we sum over individual masked positions.
Now let's see what the losses look like at initialization, before any training has occurred. We'll create random logits (simulating an untrained model) and random labels (simulating our training data):
# Simulate pre-training forward pass with random (untrained) model
batch_size, seq_len, vocab_size = 4, 128, 30522
# Random logits simulate an untrained model's predictions
mlm_logits = torch.randn(batch_size, seq_len, vocab_size)
mlm_labels = torch.full((batch_size, seq_len), -100)
# Mask about 15% of positions (as BERT does)
for i in range(batch_size):
mask_positions = torch.randperm(seq_len)[: int(seq_len * 0.15)]
mlm_labels[i, mask_positions] = torch.randint(
0, vocab_size, (len(mask_positions),)
)
nsp_logits = torch.randn(batch_size, 2)
nsp_labels = torch.randint(0, 2, (batch_size,))
total, mlm, nsp = compute_pretraining_loss(
mlm_logits, mlm_labels, nsp_logits, nsp_labels, vocab_size
)Pre-training losses (random initialization): MLM Loss: 10.8903 NSP Loss: 1.1417 Total Loss: 12.0319 Expected random MLM loss: ln(30522) = 10.3262 Expected random NSP loss: ln(2) = 0.6931
The results confirm our understanding of the loss functions. An untrained model assigns roughly uniform probability across all tokens, so the expected MLM loss is , representing maximum uncertainty over the vocabulary. Similarly, random binary classification yields expected loss . The actual values fluctuate slightly due to random sampling, but they hover around these theoretical baselines.
As training progresses, both losses decrease. The MLM loss drops as the model learns which tokens fit in which contexts. The NSP loss drops as the model learns to distinguish coherent sentence pairs from random ones. The total loss, being their sum, tracks the model's overall progress toward understanding language.