4.2.6 · D3Tokenization & Language Modeling

Worked examples — Causal language modeling objective

1,986 words9 min readBack to topic

This page is the "throw everything at it" companion to the parent objective note. We already know the loss:

Here we use it on every kind of input a real training run meets. Before we start, two reminders in plain words so no symbol is a surprise:

The scenario matrix

Every causal-LM example falls into one of these cells. The 8 worked examples below cover all of them.

Cell Case class What's special Covered by
A Ordinary short sequence all context present Ex 1
B First token, no context (degenerate context) Ex 2
C Perfect prediction limiting value , loss Ex 3
D Worst prediction limiting value , loss Ex 3
E Uniform / untrained model baseline Ex 4
F Padding & masking tokens that must NOT count Ex 5
G Perplexity conversion turning loss into an interpretable number Ex 6
H Real-world word problem weather-report generator Ex 7
I Exam twist which shift is correct? off-by-one trap Ex 8
Figure — Causal language modeling objective

Example 1 — Cell A: an ordinary sequence

Forecast: guess before computing — is the total nearer , , or ? (The ML step is very surprising, so expect a chunky number.)

  1. Turn each probability into surprise. . Why this step? The objective is a sum of per-token surprises; each factor in the product becomes one additive term after .

  2. Add them. Why this step? Chain rule: , and of a product is the sum of s.

Verify: compute directly. , and . ✓ Matches the sum — the two roads agree, as Cross-Entropy Loss promises.


Example 2 — Cell B: the first token has context after all

Forecast: zero, or the same as before?

  1. Recognise the empty context is not empty. With <BOS>, we have . Why this step? The model still predicts a distribution over first words; The, I, capitalised tokens are common. That is real learnable information, so the loss is not waived.

  2. Apply the surprise formula. Why this step? Cell B is just Cell A with a one-token context; nothing about the loss changes.

Verify: it equals of Example 1 — consistent, since the probability is identical. Skipping this term would undercount the true negative log-likelihood. ✓


Example 3 — Cells C & D: the two extremes

Forecast: which is and which blows up?

  1. Perfect case (C). . Why this step? maps certainty to zero penalty — the floor of the loss.

  2. Near-impossible case (D). . Why this step? As , . This is the limiting behaviour that punishes over-confident wrong models catastrophically — the mathematical reason models learn to never assign exactly .

Verify: . ✓ And exactly. The gap between best and worst on a single token is unbounded above, bounded below by .


Example 4 — Cell E: the untrained-model baseline

Forecast: the parent note quoted "". Can you derive it?

  1. Write the uniform probability. . Why this step? A random-init softmax over near-equal logits spreads probability evenly — no token is favoured.

  2. Take the surprise. Why this step? Cell E is the calibration point: any trained model must beat this to have learned anything.

Verify: , matching the parent's . A trained GPT-2 scoring is genuinely far below chance. ✓ This baseline is exactly the Perplexity anchor (see Ex 6).


Example 5 — Cell F: padding must not be graded

Forecast: should the two big s drag the average up?

  1. Identify which positions are real. Positions are content; positions are padding with ignore_index. Why this step? Padding exists only to make tensors rectangular; grading it would teach the model to "predict" filler, corrupting the objective.

  2. Sum only the real terms. Why this step? The masked positions contribute , not their raw surprise.

  3. Average over the real count (3), not 5. Why this step? The mean must divide by the number of graded tokens.

Verify: the wrong way, dividing , is inflated by the padding — nearly double. Correct answer . ✓ This is why real code passes ignore_index=pad_token_id.


Example 6 — Cell G: loss → perplexity

Forecast: perplexity is "effective number of choices" — expect a couple dozen for .

  1. Define perplexity. . Why this step? Perplexity un-does the : it is the geometric-mean branching factor, "how many equally-likely tokens is the model effectively choosing among?" See Perplexity.

  2. Plug in the trained loss.

  3. Sanity-check the baseline. For Ex 4, , so Why this step? Uniform-over- must give perplexity exactly — the model is genuinely torn between all tokens.

Verify: ; and exactly. ✓ A trained model with PPL vs. baseline is a huge win.


Example 7 — Cell H: a real-world word problem

Forecast: with only 4 words, perfect uniform loss would be ; is this model better or worse than random?

  1. Per-token surprises. Why this step? Same machinery, small vocabulary.

  2. Total loss. . Why this step? Sum over the 2 graded positions.

  3. Average loss. . Why this step? Two tokens, so divide by 2.

  4. Perplexity. . Why this step? Effective branching factor; means the model beats a coin-flip-over-4 baseline. This connects directly to how Autoregressive Models chain conditionals during sampling.

Verify: ; ; sum ; half ; . Also . ✓ Two roads agree.


Example 8 — Cell I: the off-by-one exam twist

Forecast: how many valid (context → target) pairs can length-5 actually produce?

  1. State the causal rule. Position must be predicted from positions . Why this step? The whole objective forbids looking at when predicting — the no-shift code grades the model on copying its own input, which it can do trivially through the residual path. This is a fake near-zero loss.

  2. Do the shift. Use logits[:, :-1, :] against labels[:, 1:]. Why this step? Logit at position (which has only seen ) predicts label . Dropping the last logit and the first label lines them up.

  3. Count the pairs. Why this step? From tokens you get exactly prediction targets:

Verify: number of graded pairs . ✓ The no-shift version would spuriously "predict" from , giving loss near — the classic sign of the Teacher Forcing shift being missing. (Note this is training-time; generation instead suffers Exposure Bias, and it's why Masked Language Modeling and causal decoders handle masking differently.)


Recall Quick self-test

Loss of a token predicted with ::: Perplexity from average loss nats ::: Uniform baseline loss for a 1000-word vocab ::: Correct number of graded pairs for ::: Why don't padding tokens count? ::: they are filler; grading them corrupts the objective, so we mask with ignore_index