4.2.6Tokenization & Language Modeling

Causal language modeling objective

2,493 words11 min readdifficulty · medium2 backlinks

What Problem Does It Solve?

Language has structure: the word "love" is more likely after "I" than after "quantum". Causal LM learns this conditional probability distribution over sequences:

P(sentence)=P(w1)P(w2w1)P(w3w1,w2)P(wnw1wn1)P(\text{sentence}) = P(w_1) \cdot P(w_2 | w_1) \cdot P(w_3 | w_1, w_2) \cdots P(w_n | w_1 \ldots w_{n-1})

Why factorize this way? By the chain rule of probability, any joint distribution can be written as a product of conditionals. The causal constraint means each P(wtw<t)P(w_t | w_{<t}) is a forward-looking prediction, matching how we naturally produce language.

Figure — Causal language modeling objective

Derivation from First Principles

Step 1: Start with Maximum Likelihood

We want a model that assigns high probability to real text. For a dataset D\mathcal{D} of sequences, maximize:

xDPθ(x)\prod_{\mathbf{x} \in \mathcal{D}} P_\theta(\mathbf{x})

Why product? Assuming independence between training examples.

Step 2: Apply Chain Rule to Each Sequence

For one sequence x=(x1,,xT)\mathbf{x} = (x_1, \ldots, x_T):

Pθ(x)=Pθ(x1,x2,,xT)=t=1TPθ(xtx<t)P_\theta(\mathbf{x}) = P_\theta(x_1, x_2, \ldots, x_T) = \prod_{t=1}^{T} P_\theta(x_t \mid x_{<t})

Why this factorization? The chain rule of probability: P(A,B)=P(A)P(BA)P(A, B) = P(A) P(B|A), extended to TT variables. The causal ordering (x1x_1 first, then x2x_2 given x1x_1, etc.) is arbitrary but matches text's left-to-right flow.

Step 3: Take Negative Log for Optimization

Maximizing product = minimizing negative log-likelihood:

LCLM=logPθ(x)=t=1TlogPθ(xtx<t)\mathcal{L}_{\text{CLM}} = -\log P_\theta(\mathbf{x}) = -\sum_{t=1}^{T} \log P_\theta(x_t \mid x_{<t})

Why negative log?

  1. Numerical stability: Products of small probabilities underflow; sums of logs don't.
  2. Additivity: Loss over a batch is just the sum of per-example losses.
  3. Convexity: Log-loss is convex for exponential families (like softmax output).

Step 4: Average Over Dataset

LCLM(D)=1DxDt=1TlogPθ(xtx<t)\mathcal{L}_{\text{CLM}}(\mathcal{D}) = -\frac{1}{|\mathcal{D}|} \sum_{\mathbf{x} \in \mathcal{D}} \sum_{t=1}^{T} \log P_\theta(x_t \mid x_{<t})

This is the cross-entropy loss between the true next-token distribution (one-hot) and the model's predicted distribution.

Worked Examples

Example 1: Tiny Sequence

Sequence: "I love ML"
Tokens: x1=I,x2=love,x3=MLx_1 = \text{I}, x_2 = \text{love}, x_3 = \text{ML}

Step-by-step loss:

  1. Position 1: L1=logPθ(x1=I)\mathcal{L}_1 = -\log P_\theta(x_1 = \text{I} \mid \varnothing) Why no context? x1x_1 is the first token; model predicts from a start-of-sequence token or learns unconditional distribution.

  2. Position 2: L2=logPθ(x2=lovex1=I)\mathcal{L}_2 = -\log P_\theta(x_2 = \text{love} \mid x_1 = \text{I}) Why only x1x_1? Causal constraint: model sees "I", predicts "love".

  3. Position 3: L3=logPθ(x3=MLx1=I,x2=love)\mathcal{L}_3 = -\log P_\theta(x_3 = \text{ML} \mid x_1 = \text{I}, x_2 = \text{love}) Why both x1,x2x_1, x_2? All previous context available.

Total loss: LCLM=L1+L2+L3\mathcal{L}_{\text{CLM}} = \mathcal{L}_1 + \mathcal{L}_2 + \mathcal{L}_3

Concrete numbers: Suppose model outputs:

  • Pθ(I)=0.1P_\theta(\text{I} \mid \varnothing) = 0.1L1=log(0.1)2.30\mathcal{L}_1 = -\log(0.1) \approx 2.30
  • Pθ(loveI)=0.4P_\theta(\text{love} \mid \text{I}) = 0.4L2=log(0.4)0.92\mathcal{L}_2 = -\log(0.4) \approx 0.92
  • Pθ(MLI love)=0.05P_\theta(\text{ML} \mid \text{I love}) = 0.05L3=log(0.05)3.00\mathcal{L}_3 = -\log(0.05) \approx 3.00

Total: 2.30+0.92+3.00=6.222.30 + 0.92 + 3.00 = 6.22

Why this number? Lower loss = model assigns higher probability to the true sequence. Perfect prediction (P=1P=1) gives loss 00.

Example 2: Generation vs. Training

Training:

  • Input: "The cat sat on the"
  • Targets: "cat sat on the mat" (shifted by 1)
  • Loss: logP(catThe)logP(satThe cat)-\log P(\text{cat}|\text{The}) - \log P(\text{sat}|\text{The cat}) - \ldots

Generation (autoregressive sampling):

  • Start: "The"
  • Sample x2Pθ(The)x_2 \sim P_\theta(\cdot | \text{The}) → get "cat"
  • Sample x3Pθ(The cat)x_3 \sim P_\theta(\cdot | \text{The cat}) → get "sat"
  • Continue until end-of-sequence token

Why same objective works for both? Training learns Pθ(xtx<t)P_\theta(x_t | x_{<t}) at every position. Generation repeatedly applies this learned conditional to extend the sequence.

Why Causal vs. Other Objectives?

Objective Prediction Mask Use Case
Causal LM Next token Future positions Generation (GPT, GPT-2, GPT-3)
Masked LM Masked tokens Random positions Understanding (BERT)
Prefix LM Next token Future in suffix Hybrid (encoder-decoder)

Why causal for generation? At inference, you only have past tokens. Training objective must match test-time reality (no future available).

Why masked LM can't generate? BERT sees bidirectional context, but generation is left-to-right. Mismatch between training and inference.

Recall Explain to a 12-Year-Old

Imagine you're writing a story, one word at a time. You can look back at what you've already written, but you can't peek ahead at what comes next (because you haven't written it yet!).

Causal language modeling is teaching a robot to play this same game. The robot reads "Once upon a", then guesses the next word might be "time". If the real next word is "time", the robot gets a good score. If it guessed "banana", it gets a bad score and learns to do better.

The robot practices on millions of stories, learning patterns like:

  • "Once upon a ___" → usually "time"
  • "I feel ___" → often "happy", "sad", "excited"
  • "The dog ___" → probably a verb like "ran", "barked"

The trick is the robot never cheats by looking ahead. It only sees what it's already written, just like you. That's why it's called "causal"—like cause and effect, the past causes the future, not the other way around!

After enough practice, the robot becomes so good at guessing next words that it can write entire stories on its own, one word at a time.

Connections

  • Autoregressive Models — Causal LM is the autoregressive paradigm applied to text
  • Cross-Entropy Loss — The mathematical form of the CLM objective
  • Transformer Decoder — Architecture implementing causal self-attention
  • Teacher Forcing — Training technique where true tokens (not predictions) provide context
  • Perplexity — Evaluation metric: exp(LCLM)\exp(\mathcal{L}_{\text{CLM}}), lower is better
  • Masked Language Modeling — Contrasting objective for bidirectional understanding (BERT)
  • Exposure Bias — Training-inference mismatch in autoregressive models
  • Sampling Strategies — How to generate from Pθ(xtx<t)P_\theta(x_t | x_{<t}) (greedy, beam search, nucleus)
  • GPT Family — Models trained with causal LM objective

#flashcards/ai-ml

What is the causal language modeling objective? :: Minimize negative log-likelihood t=1TlogPθ(xtx<t)-\sum_{t=1}^{T} \log P_\theta(x_t \mid x_{<t}), predicting each token from only previous tokens (no future access).

Why is it called "causal"? :: Because prediction at position tt can only depend on positions before tt (cause → effect), preserving time's forward direction.

How does CLM factorize sequence probability?
By the chain rule: P(x)=t=1TP(xtx<t)P(\mathbf{x}) = \prod_{t=1}^{T} P(x_t \mid x_{<t}), decomposing joint probability into conditional next-token predictions.
What enforces causality in transformers?
Attention masking: positions >t> t get scores of -\infty before softmax, zeroing their contribution to position tt's representation.
What is the loss for a single position tt?
Lt=logPθ(xtx<t)\mathcal{L}_t = -\log P_\theta(x_t \mid x_{<t}), the negative log-probability assigned to the true token xtx_t given past context.
Why use negative log-likelihood instead of probability product?
Numerical stability (logs avoid underflow), additivity (easy to sum), and convexity (better optimization properties).
What is the relationship between CLM and cross-entropy?
CLM is cross-entropy between the true next-token distribution (one-hot at correct token) and model's predicted softmax distribution.
How is causal LM used for generation?
Autoregressively sample xtPθ(x<t)x_t \sim P_\theta(\cdot \mid x_{<t}), then condition on sampled xtx_t to predict xt+1x_{t+1}, repeating until end-of-sequence.
What is perplexity in context of CLM?
PPL=exp(LCLM)\text{PPL} = \exp(\mathcal{L}_{\text{CLM}}), the exponentiated average negative log-likelihood; lower perplexity = better predictions.
Why does CLM train on shifted targets?
Input at position t1t-1 predicts target at position tt (input: "The cat sat", targets: "cat sat on"), implementing P(xtx<t)P(x_t \mid x_{<t}).
What is exposure bias in causal LM?
Training uses true tokens as context (teacher forcing), but generation uses model's own predictions; errors compound since model never practiced recovering from mistakes.
Why can't BERT generate text like GPT?
BERT uses masked LM with bidirectional context, but generation is left-to-right (only past available); training-inference mismatch prevents autoregressive sampling.

Concept Map

trains to

constrained by

enforced by

justifies

defines

maximizes

becomes

via negative log

objective is

enables

Causal Language Modeling

Predict next token

Never look ahead

Chain rule of probability

Product of conditionals

Maximum likelihood

Negative log-likelihood loss

Attention masks

Text generation

Numerical stability

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho yaar, causal language modeling ka core idea bahut simple hai - model ko sirf yeh sikhana hai ki ek sentence mein "next word" kya aayega, wo bhi sirf pichle words ko dekh ke, future ko bilkul dekhe bina. Jaise aap ek sentence left-to-right padh rahe ho aur har agle word ko guess kar rahe ho - "I..." ke baad "love" aane ki probability zyada hai, "quantum" ki kam. Yeh "causal" isliye kehte hain kyunki position tt ki prediction sirf uske pehle wale tokens (x<tx_{<t}) pe depend kar sakti hai, matlab cause pehle aata hai aur effect baad mein, time ki direction preserve hoti hai.

Ab maths ki taraf dekho toh yeh chain rule of probability se aata hai. Kisi bhi poore sentence ki probability ko hum chote-chote conditional probabilities ke product mein tod sakte hain - pehle P(w1)P(w_1), phir P(w2w1)P(w_2|w_1), aur aise aage. Model ko train karne ke liye hum negative log-likelihood minimize karte hain, jo actually cross-entropy loss ban jaata hai. Log lene ke teen faayde hain: chote probabilities multiply karne se numbers underflow ho jaate hain (log se yeh problem nahi hoti), loss additive ban jaata hai (batch ka total loss bas sum ho jaata hai), aur optimization convex ho jaati hai. Practically, transformer har position pe logits deta hai, softmax se woh probabilities banti hain, aur attention mein "causal masking" lagti hai taaki model cheating karke future tokens na dekh sake.

Yeh matter isliye karta hai kyunki yahi objective aaj ke saare bade text-generation models - jaise GPT family - ke peeche ka fundamental hai. Jab model yeh forward-looking prediction achhe se seekh leta hai, toh wo naya coherent text generate kar sakta hai, ek-ek token karke. Toh agar aap language models ko deeply samajhna chahte ho, yeh objective aapka foundation hai - baaki sab isi ke upar build hota hai.

Go deeper — visual, from zero

Test yourself — Tokenization & Language Modeling

Connections