Causal Language Modeling › The CLM Objective
Language AI HandbookAll chapters Causal Language Modeling › The CLM ObjectiveOne section · Sections in this chapter3 / 13 ↓
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
Now that we understand how to decompose sequence probability, we need a way to train a model to produce good probability estimates. This requires two things: a loss function that measures prediction quality, and a mechanism to improve the model based on that measurement. The CLM objective is the standard answer to both. It is derived from maximum likelihood estimation, a classical statistical principle, applied to the autoregressive factorization we just derived. Understanding the derivation step by step reveals why the final formula looks the way it does and why the choices made along the way are the right ones.
From Maximum Likelihood to Minimum Loss
Our goal is to find model parameters that make the training data as probable as possible. Given a training sequence , we want to maximize:
Maximizing a product of many small probabilities is numerically unstable. As sequences grow longer, the product shrinks toward zero, causing underflow. The standard solution is to work with logarithms. Since is monotonically increasing, maximizing a probability is equivalent to maximizing its log:
The product becomes a sum, which is numerically stable and computationally convenient. Now, optimization algorithms typically minimize rather than maximize, so we flip the sign to get our loss function:
where:
- : the loss function we minimize during training
- : the model parameters (weights and biases of the neural network)
- : the length of the training sequence
- : the probability the model assigns to the correct token given the context
- : the log-probability, which is negative since probabilities lie in
The Connection to Cross-Entropy
This loss function has a beautiful interpretation: it's the cross-entropy between the model's predicted distribution and the true distribution (which puts all probability mass on the actual next token).
To see why, recall that cross-entropy measures how well a predicted distribution matches a true distribution :
At each position , the "true distribution" is a one-hot vector: probability 1 for the actual token , and 0 for everything else. The model predicts a distribution over all vocabulary tokens. The cross-entropy simplifies to:
Only the true token's probability matters. This is why cross-entropy loss is also called "negative log-likelihood" in language modeling contexts.
Understanding the Loss Signal
The loss function creates an intuitive learning signal. When the model assigns high probability to the correct token, the loss contribution is small. When the model is surprised, the loss contribution is large.

Consider these scenarios:
- Confident and correct (): . Small loss, weak gradient. The model is doing well here.
- Uncertain (): . Moderate loss. Room for improvement.
- Confident and wrong (): . Large loss, strong gradient. The model needs to update significantly.
This asymmetry is powerful: the model receives the strongest teaching signal precisely where it's making the biggest mistakes.
Efficient Learning from Every Token
A remarkable property of CLM loss is that it decomposes across positions. A single sequence of length provides independent gradient signals, one for each prediction. This is dramatically more efficient than classification tasks where a single input yields a single label.
Consider training on a document with 1,000 tokens. Each forward pass produces 1,000 predictions and 1,000 loss terms. The model learns from every token simultaneously, extracting maximum information from the training data. This efficiency is one reason language models can learn so much from their training corpora.
Implementation
Let's implement this loss function to see how it works in practice:
import torch.nn.functional as F
def compute_clm_loss(logits, targets, ignore_index=-100):
"""
Compute causal language modeling loss.
Args:
logits: Model outputs of shape (batch, seq_len, vocab_size)
targets: Target token IDs of shape (batch, seq_len)
ignore_index: Token ID to ignore in loss computation (e.g., padding)
Returns:
Scalar loss value (mean over all valid positions)
"""
# Reshape for cross-entropy: (batch * seq_len, vocab_size)
batch_size, seq_len, vocab_size = logits.shape
logits_flat = logits.view(-1, vocab_size)
targets_flat = targets.view(-1)
# Cross-entropy computes -log(softmax(logits)[target])
loss = F.cross_entropy(
logits_flat, targets_flat, ignore_index=ignore_index, reduction="mean"
)
return lossExample CLM loss: 4.7462 Perplexity: 115.15 Random baseline (vocab=100): loss=4.6052, ppl=100
With random logits, the loss is close to where is the vocabulary size, because the model assigns roughly uniform probability to all tokens. As training progresses, the model learns to concentrate probability mass on likely continuations, reducing the loss.

