4.2.7 · D4Tokenization & Language Modeling

Exercises — Masked language modeling (BERT)

2,391 words11 min readBack to topic

This page is your self-test for Masked language modeling (BERT). Work each problem before opening its solution. Problems climb five levels: L1 RecognitionL2 ApplicationL3 AnalysisL4 SynthesisL5 Mastery. Every symbol used here was built in the parent note; if you meet one you forgot, this page re-anchors it in plain words the first time it appears.

Quick symbol refresher (so line one is readable):

Recall What do the symbols mean? (open if rusty)
  • ::: the sequence of tokens (word pieces) fed to the model, position to .
  • ::: the set of masked positions — the indices we hid and asked the model to guess.
  • ::: the corrupted input — the sequence with the chosen positions replaced by [MASK] / random / unchanged.
  • ::: the probability the model assigns to the true token at position , given everything it can see.
  • ::: the training loss — smaller means better guesses.
  • here is the natural log (base ), the default in ML. is big when is small (bad guess) and when (perfect guess).

Level 1 — Recognition

L1.1

BERT selects 15% of tokens for masking. Of those selected, what fraction becomes the literal [MASK] token, what fraction becomes a random token, and what fraction stays unchanged?

Recall Solution

Of the selected tokens: ==80% → [MASK], 10% → random token, 10% → unchanged==. These are fractions of the 15% selected, not of the whole sequence. So of the whole sequence: become [MASK], random, unchanged.

L1.2

Classify each model by its attention direction: GPT, BERT, and the encoder of T5. Which one(s) are bidirectional?

Recall Solution
  • GPT ::: causal (left-to-right only) — cannot see future tokens.
  • BERT ::: bidirectional — every position attends to all others.
  • T5 encoder ::: bidirectional. Only GPT is unidirectional. GPT must stay causal because it generates one token at a time; seeing the future would be cheating.

L1.3

Write down the total BERT pre-training loss as a sum of its two objectives, and name each.

Recall Solution

= Masked Language Modeling loss (predict hidden tokens). = Next Sentence Prediction loss (does sentence B follow A?).


Level 2 — Application

L2.1

A sequence has tokens. Using BERT's protocol, how many tokens (rounded to the nearest whole token) are selected for masking, and of those how many become the literal [MASK] token?

Recall Solution

Selected: tokens. Literal [MASK]: tokens. Random: . Unchanged: . (In practice the split is stochastic per token, so these are expectations.)

L2.2

The model predicts the true token with probability at one masked position, and at another. Compute the MLM loss (sum over just these two positions). Use natural log.

Recall Solution

, and . What this means: the position where the model was only confident contributes more loss () than the one () — bad guesses are penalised harder, which is the whole point of . See the loss curve below.

Figure — Masked language modeling (BERT)

L2.3

Input text "The dog barked loudly" becomes, after tokenization, [CLS] the dog barked loudly [SEP] (7 positions, indexed ). We mask position (dog). Write the loss contribution from this one position in terms of the model's probability for the true token, and state which hidden state produces it.

Recall Solution

The contextual hidden state at position is (the Transformer's output vector there). We project it to vocabulary scores and softmax: Loss contribution: . Only masked positions contribute — positions add nothing to the loss even though the model produces hidden states for them.


Level 3 — Analysis

L3.1

BERT could have masked of selected tokens with [MASK]. Explain, using the fine-tuning stage, why the 80/10/10 split is used instead. Then explain why the two non-[MASK] cases (random and unchanged) push the model in different useful directions.

Recall Solution

Why not 100% [MASK]: the [MASK] token never appears during fine-tuning (downstream tasks feed clean text). If the model only ever learned to fill [MASK] slots, it would face a train–test mismatch and its representations of ordinary tokens would be under-trained. Random 10%: forces the model to not blindly trust the token it sees — even a present-looking token might be wrong, so the model must cross-check against context. This builds error-correcting representations. Unchanged 10%: forces the model to produce a good representation of the correct token as well, so that a token being "kept" is meaningful rather than a signal of "this one is safe to ignore." Because the model can't tell which of the three cases it's in, it must build a strong contextual representation for every selected position.

L3.2

Two students disagree. Student A says "GPT can't be bidirectional because it's an old architecture." Student B says "GPT can't be bidirectional because of its objective." Who is right and why?

Recall Solution

Student B. The barrier is the autoregressive generation objective, not the age of the design. GPT predicts the next token; if it could attend to future tokens, position would literally see token — the very thing it must predict — so training would be trivial and generation impossible. BERT can be bidirectional precisely because it is not generating: it corrupts input and reconstructs it, so "seeing both sides" of a masked slot is fair — the answer at that slot was hidden, not leaked.

L3.3

Suppose a model outputs a uniform distribution over a vocabulary of size at a masked position (it has learned nothing). What is the loss at that position? Interpret the number as an "information content."

Recall Solution

Uniform means for every token, including the true one. This is the loss of a model that guesses randomly — the maximum-ignorance baseline (in natural log units, "nats"). Any trained model should sit well below . It equals the entropy of a uniform choice among options: the number of nats needed to pin down one token with no help from context.


Level 4 — Synthesis

L4.1

You are given a mini-batch with two sentences. Sentence 1 has masked positions with true-token probabilities . Sentence 2 has masked positions with probabilities . Compute the total MLM loss for the batch (sum over all masked positions across both sentences).

Recall Solution

Sentence 1: . (Note , so this is .) Sentence 2: . Total: .

L4.2

Design the input token stream for BERT for the NSP pair below, then write BOTH loss terms symbolically and state which hidden state drives NSP.

  • Sentence A: "I went to the store"
  • Sentence B: "I bought some milk" (this genuinely follows A)
Recall Solution

Input stream (segment A tokens then segment B tokens, separated and terminated by [SEP]):

[CLS] I went to the store [SEP] I bought some milk [SEP]

Segment embeddings: A for [CLS] I went to the store [SEP], B for I bought some milk [SEP].

  • MLM term (over whatever tokens are masked in ): .
  • NSP term: the final hidden state of [CLS], call it , feeds a binary classifier. True label here is IsNext (): Total: .

L4.3

For the NSP classifier at one [CLS] position, the model gives probability to the correct label. Its MLM part over masked tokens gives probabilities . Compute for this example.

Recall Solution

. .


Level 5 — Mastery

L5.1

Two candidate models predict the true token at one masked position. Model X gives ; Model Y gives . Both look "very confident." Compute each loss and the ratio of improvement. Explain why the jump from is worth chasing even though it's "only 9 percentage points."

Recall Solution

. . Ratio . Why it matters: is steep near , so tiny gains in already-high probability slash the loss by an order of magnitude. The loss curve (below) is nearly vertical as and flattens toward as — this is why late-stage training keeps improving loss even when accuracy looks saturated.

Figure — Masked language modeling (BERT)

L5.2

Consider a degenerate case: a training example where BERT happens to select tokens for masking (possible on a very short sequence, e.g. , since rounds/samples to ). What is , and what does gradient descent do with this example's MLM term?

Recall Solution

With (empty set), the sum has no terms: A zero loss has zero gradient from the MLM head, so this example contributes no MLM update. (The NSP term, if present, can still contribute.) This is the correct, safe behaviour — an empty sum is , not undefined. Practically, implementations guard against empty or ensure at least one token is masked.

L5.3

A subtle limiting question. Show that for a masked position, the MLM loss is bounded below by and unbounded above, and identify the probabilities producing each extreme. Why does this asymmetry make the loss a good teacher?

Recall Solution

is a probability, so (it can be but never exactly in floating point / after softmax).

  • As : . Lower bound , achieved at perfect confidence in the truth.
  • As : . No upper bound — the more confidently wrong the model is, the more brutal the penalty. Why it teaches well: the loss can never reward a mistake (it's ) and it punishes confident errors without limit, so the model is strongly discouraged from putting near-all probability on a wrong token. The gentle floor near means correct-and-confident predictions stop generating pressure — training energy flows to the still-wrong positions.