4.2.6 · D4Tokenization & Language Modeling

Exercises — Causal language modeling objective

2,360 words11 min readBack to topic

This page is a self-test ladder. Each problem states cleanly what to do; the answer hides inside a collapsible Solution callout so you can try first, then check. Work from the top — every level builds on the last. Parent: Causal language modeling objective.

Before we start, one reminder about the tool we lean on everywhere: the natural logarithm (also written here — we always mean base , the number ). Why the log at all? Because probability of a long sentence is a product of many small numbers, and multiplying small numbers underflows to zero on a computer. The log turns that product into a sum (), which is stable and easy to differentiate. Every loss below is a sum of .


Level 1 — Recognition

Exercise 1.1

Which of these expressions is the causal factorization of ? (a) (b) (c)

Recall Solution

Answer: (b). Why not (a)? That assumes the three words are independent — but "love" after "I" is not the same as "love" after "quantum", so they are not independent. Why not (c)? It is a valid chain-rule ordering mathematically, but it conditions on the future (predicting from ). "Causal" means left-to-right: position may only look at positions . Only (b) respects that direction.

Exercise 1.2

A model gives for every token in a sentence (perfect prediction). What is for that sentence?

Recall Solution

Each term is . Summing zeros gives . Intuition: zero loss = the model was certain and correct at every step. Loss can never go below because probabilities are , and of anything is .


Level 2 — Application

Exercise 2.1

Sequence "she runs fast" with model probabilities , , . Compute (use , round to 2 decimals).

Recall Solution

Total . Notice position 1 does contribute — see Mistake 2 in the parent note.

Exercise 2.2

A vocabulary has tokens. A freshly initialised model has learned nothing, so it outputs a uniform distribution. What is the per-token loss ?

Recall Solution

Uniform means every token gets probability . . Why this matters: is the "know-nothing" baseline. If your trained model's per-token loss is not clearly below , it has learned nothing useful. (For GPT-2's , that baseline is .)

Exercise 2.3

Given logits over a 3-token vocab, and the true next token is index 0 (the token with logit ). Compute the loss using the softmax-cross-entropy form .

Recall Solution

Why this tool (softmax)? Logits are raw scores in ; softmax turns them into positive numbers that sum to 1, i.e. a probability distribution. The formula above is just of the softmax probability of the true class, algebraically simplified. . . . Check: softmax prob of class 0 , and . ✓


Level 3 — Analysis

Exercise 3.1

Perplexity is defined as . For Exercise 2.1 (, total loss ), compute the perplexity and interpret it.

Recall Solution

Average per-token loss . . Interpretation: perplexity is the "effective branching factor" — as if, at each step, the model were choosing uniformly among equally likely tokens. Lower is better. Why exponentiate the average loss? Because loss is in log-units (nats); undoes the log and puts us back in "number of choices" units, which humans read more easily.

Exercise 3.2

Two models are evaluated on the same test sentence. Model A has average loss ; Model B has . By what factor is Model A less "perplexed"?

Recall Solution

, . Ratio . Insight: a loss difference of nats is a perplexity ratio of . A 1-nat improvement always multiplies perplexity down by , regardless of the starting point. This is why loss differences of "just 0.3" are quietly significant.

Exercise 3.3

During training we compute all positions in parallel, so it looks like the model sees the whole sentence. Explain, using the attention mask, why the loss is still causal. What value replaces the masked attention scores, and why that specific value?

Recall Solution

In self-attention, position computes a score against every other position, then softmaxes those scores into weights. To forbid looking ahead, we set the scores for positions to before the softmax. Why ? Because softmax exponentiates: . So a future position receives weight exactly and contributes nothing to position 's representation. See figure below. Key phrase: computationally parallel ≠ informationally non-causal. All positions are processed at once for speed, but each one is blind to its future because those weights are zeroed. See Transformer Decoder and Teacher Forcing.


Level 4 — Synthesis

Exercise 4.1

In the GPT-2 training code we do shift_logits = logits[:, :-1, :] and shift_labels = input_ids[:, 1:]. For the token sequence [<BOS>, "I", "love", "ML"] (4 tokens), list every (input-position, predicted-label) pair used in the loss.

Recall Solution

Indexing from 0: positions hold <BOS>(0), I(1), love(2), ML(3). shift_logits uses positions 0,1,2 (drop the last, since there is no token after ML to predict). shift_labels uses positions 1,2,3 (drop the first, <BOS>, which we never predict). Pairs (context ⇒ target):

  • <BOS>I
  • <BOS>, Ilove
  • <BOS>, I, loveML That is 3 loss terms from 4 tokens. General rule: a length- sequence yields predictions when the first token is a given <BOS>.

Exercise 4.2

Prepending <BOS> fixes "the first real token has no context" (parent Mistake 2). Suppose without <BOS> the model assigns , but with <BOS> it can condition and gets . How much does the first-token loss improve (in nats)?

Recall Solution

Without: . With: . Improvement nats. Why it works: <BOS> is a learnable anchor. Predicting "which token starts a sentence" from a consistent start symbol lets the model learn a real conditional distribution instead of a vaguer unconditional one — connects to how Autoregressive Models handle the boundary.

Exercise 4.3

You compare a causal LM against Masked Language Modeling (MLM). For the sentence "the cat sat", how many next-token prediction terms does a causal LM produce, versus how many masked-token predictions an MLM produces if it masks exactly 1 of the 3 tokens (15% rounds to 1)? State why causal LM is the natural choice for generation.

Recall Solution

Causal LM: predicts each token from its left context ⇒ up to terms (or with <BOS>). Every position supervised. MLM: masks ~15% of tokens, here 1 token, and predicts only that ⇒ term per pass. MLM also lets predictions see both sides (bidirectional), so it is not left-to-right. Why causal for generation: generation produces text left-to-right, one token at a time. The training objective is exactly the conditional you sample from at generation. MLM's bidirectional peeking cannot be run left-to-right, so it does not directly give a generation procedure. See GPT Family and Sampling Strategies.


Level 5 — Mastery

Exercise 5.1

Exposure Bias. At generation time the model conditions on its own sampled tokens, which may contain errors it never saw during Teacher Forcing training. Suppose at each of steps there is a chance of an error, and one error makes the whole continuation "wrong". What is the probability the 5-token continuation is fully correct? Contrast with training, where the true context is always given.

Recall Solution

Each step correct with prob ; steps' errors compound multiplicatively. , i.e. about . Contrast: during teacher forcing the model always receives the ground-truth previous tokens, so a mistake at step 2 never corrupts step 3's context. At generation there is no ground truth to fall back on — errors feed forward and compound. That gap between training and inference conditioning is exactly exposure bias.

Exercise 5.2

Derive that minimizing averaged over infinite data is equivalent to matching the true data distribution, i.e. the loss is minimized when . (Sketch via cross-entropy vs entropy.)

Recall Solution

Expected per-token loss is the cross-entropy . A standard identity: , where is the fixed data entropy and is the Kullback–Leibler divergence, equal to iff the two distributions match. Since does not depend on , minimizing the loss means minimizing , whose minimum () is attained exactly when . See Cross-Entropy Loss. Takeaway: the best possible loss is not zero — it is the data's own entropy , the irreducible uncertainty of language. A model at that floor is perfect; it cannot do better because language itself is not fully predictable.

Exercise 5.3 (numeric floor)

A toy language: after "the", the true next token is "cat" with prob and "dog" with prob ; nothing else. Compute the minimum achievable per-token loss at this position (the entropy).

Recall Solution

A perfect model outputs exactly . Its expected loss equals the entropy: nats. Interpretation: even a flawless model pays nats here because the true next word is genuinely uncertain. No amount of training pushes this position's loss below . That is the entropy floor from Exercise 5.2 made concrete.

Recall Self-test wrap-up

One-nat loss improvement multiplies perplexity by which factor? ::: Minimum achievable average loss equals what quantity? ::: the entropy of the true data distribution A length- sequence with a prepended <BOS> gives how many loss terms? ::: (predict each real token from its left context) What replaces future attention scores before softmax, and why? ::: , because zeroes their weight, enforcing causality