BERT Pre-training › Combined Pre-training Objective

Michael BrenndoerferUpdated July 19, 20258 min read
Language AI HandbookAll chapters
Part 24 of 67BERT and Variants
Chapter 170BERT Pre-training › Combined Pre-training Objective
Reading section 5 of 12 · Combined Pre-training Objective · 8 minSection 5 of 12 · 8 min

Book contents

Section 5 of 12 · 8 min read

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:

Ltotal=LMLM+LNSP\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{MLM}} + \mathcal{L}_{\text{NSP}}

where:

  • Ltotal\mathcal{L}_{\text{total}}: the total pre-training loss that BERT minimizes through gradient descent
  • LMLM\mathcal{L}_{\text{MLM}}: the masked language modeling loss, measuring how well the model predicts masked tokens
  • LNSP\mathcal{L}_{\text{NSP}}: 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:

LMLM=−∑i∈Mlog⁡Pθ(xi∣x~)\mathcal{L}_{\text{MLM}} = -\sum_{i \in \mathcal{M}} \log P_\theta(x_i | \tilde{x})

Let's unpack each component:

  • M\mathcal{M}: the set of masked position indices. For a 512-token sequence with 15% masking, this contains approximately 77 positions.
  • xix_i: the original token at position ii before we corrupted it. This is the "ground truth" the model must recover.
  • x~\tilde{x}: the corrupted input sequence where masked positions show [MASK], random tokens, or unchanged tokens (following the 80-10-10 rule).
  • Pθ(xi∣x~)P_\theta(x_i | \tilde{x}): the probability our model (with parameters θ\theta) assigns to the correct token xix_i, given the entire corrupted sequence as context.

The negative sign and logarithm work together to create our loss function. When Pθ(xi∣x~)P_\theta(x_i | \tilde{x}) is close to 1 (confident and correct), log⁡(1)=0\log(1) = 0, contributing zero loss. When Pθ(xi∣x~)P_\theta(x_i | \tilde{x}) is small (the model missed the answer), log⁡(small number)\log(\text{small number}) 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?

LNSP=−log⁡Pθ(yNSP∣h[CLS])\mathcal{L}_{\text{NSP}} = -\log P_\theta(y_{\text{NSP}} | h_{\text{[CLS]}})

The symbols in this expression are:

  • yNSPy_{\text{NSP}}: 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).
  • h[CLS]h_{\text{[CLS]}}: 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.
  • Pθ(yNSP∣h[CLS])P_\theta(y_{\text{NSP}} | h_{\text{[CLS]}}): the probability the model assigns to the correct label, computed by passing h[CLS]h_{\text{[CLS]}} 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 Ltotal\mathcal{L}_{\text{total}}, 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:

  1. Token embeddings learn to represent individual words in ways that support both masked token prediction (MLM) and sentence-pair understanding (NSP).

  2. Attention patterns develop to capture both local dependencies (which tokens help predict a masked word) and global coherence (what makes two sentences related).

  3. 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.

Out[24]:
Visualization
Stacked area chart showing MLM and NSP loss contributions over training steps.
Relative contribution of MLM and NSP losses during training. Early in training, MLM dominates because predicting from a 30K vocabulary is much harder than binary classification. As training progresses, both losses decrease but MLM remains the primary learning signal.

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.

In[25]:
Code
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_loss

The 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):

In[26]:
Code
# 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
)
Out[27]:
Console
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 ln⁡(V)=ln⁡(30522)≈10.33\ln(V) = \ln(30522) \approx 10.33, representing maximum uncertainty over the vocabulary. Similarly, random binary classification yields expected loss ln⁡(2)≈0.69\ln(2) \approx 0.69. 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.