Cross-entropy for a token prediction
A penalty computed from the target and predicted distributions
This page appears at more than one point in the learning path : Cross-entropy for a token prediction.
-
08 · Score observed tokens Core stage Stage 8/9 Stage 8 of 9 · page 2 of 2
Evaluate the probability assigned to a known target, build a sequence likelihood, and connect negative log-likelihood to cross-entropy without selecting a token or changing parameters.
-
09 · Learn and update parameters Optional Stage 9/9
Connect observed targets to the aggregated loss, gradients, and parameter updates, then to the repeated training loop and validation loss; understand teacher forcing conceptually without making shifted-example preparation a stage of the Theory path.
Lesson objective. Compute H(q,p) at a single position and recover −log p(y) when the target is concentrated on y.
Lesson skeleton
- Next-token conditional distribution + Observed target token → Cross-entropy + Per-token NLL · Compute a one-position penalty and identify the one-hot case
Stage connections explained on this page
Score observed tokens ↔︎ Learn and update parameters
Score observed tokens ↔︎ Learn and update parameters
Connect the score assigned to an observed target with the learning objective that aggregates these penalties to update parameters, without making scoring a prerequisite.
For one context, the model predicts a distribution \(p\) and we have a target \(q\). What penalty should we assign to that prediction at a single position? When \(q\) specifies the observed token, the answer is its negative log-likelihood. Batch loss then uses those local penalties.
- One target: for a one-hot target \(y\), \(\ell=-\log p_\theta(y\mid x_{<t})\); assigning low probability to the observed token is costly.
- A target distribution: more generally, \(H(q,p)=-\sum_i q_i\log p_i\). Cross-entropy is not predictive entropy \(H(p)\).
Quick check. How do you recover one token’s NLL from H(q,p)?
Observed target Predicted distribution One-position penalty
To connect this formula to training, also inspect how input-target examples are built and how loss masking is applied. Do not confuse it with the entropy of the predicted distribution: entropy describes the spread of probabilities before the next token is observed, while cross-entropy loss scores the probability assigned to the observed target (or a target distribution).
In the running example, the target token is the next token actually present in the reference continuation. Cross-entropy penalizes the model when it assigns that token a low probability; it does not directly compare whole sentences as indivisible objects.
Objective for one token
Here, \(t\) indexes the target token: the logits are aligned with \(x_t\) and represent \(p_\theta(x_t\mid x_{<t})\). Some implementations instead index logits by the input position; then the row at input position \(t\) predicts \(x_{t+1}\). These conventions are equivalent only when the logits and labels are shifted consistently. For a one-hot target, the loss is:
\[ \ell_t=-\log p_\theta(x_t\mid x_{<t}). \]
If \(y\) is the target-token index and \(p=\operatorname{softmax}(z)\), this can be written as:
\[ \ell(z,y)=-z_y+\log\sum_{j=1}^{V}e^{z_j}. \]
The cost increases when the model assigns low probability to the observed token. A wrong but highly confident prediction is therefore strongly penalized.
For the Romans example, let \(p=(0.6,0.2,0.1,0.1)\) for “They”, “Aqueducts”, “Nothing”, and “Well”, and let the one-hot target be \(q=(1,0,0,0)\) because “They” is the observed next token. Then:
\[ H(q,p)=-\sum_i q_i\log p_i=-\log(0.6)\approx0.511\text{ nats}. \]
Only the target probability appears explicitly in this one-hot expression. The other probabilities still matter indirectly because softmax normalizes all logits and therefore affects the target probability and its gradient. This is the loss at one target position, not yet a sequence or batch reduction.
When the selected token differs from the target
Keep the same prefix and probabilities. Greedy decoding selects “They” (\(0.6\)). Now imagine a different observed continuation that starts with “Aqueducts” (\(0.2\)).
- Before observing the target, predictive entropy is still \(1.089\) nats. The first-turn distribution is the same.
- To score “Aqueducts”, the loss at this position is \(-\ln(0.2)\approx 1.609\) nats. It is computed from the observed target.
- To train the model, this loss can contribute to the batch objective. Backpropagation computes gradients and the optimizer applies the update.
After the first token, generation continues with “They” in its prefix. Scoring continues with “Aqueducts” in its prefix. Compare the two prefixes in a two-token trace.
Visual intuition: the loss measures the surprise of the observed token
Both cases concern the same target token: only the probability assigned to it changes. When \(p(y)=0.9\), the loss is about \(0.105\) nats; when \(p(y)=0.1\), it is about \(2.303\) nats. The second loss is nearly 22 times larger. The function \(-\log p(y)\) makes confident errors costly, but it does not tell us whether the observed token is true or useful in a broader sense.
This figure illustrates the loss for one token with a one-hot target. It does not show the full vocabulary distribution, the averaging over valid positions, or the entire training objective.
Connection to the gradient
The derivative of one-hot cross-entropy with respect to the logits is \(p_i-\mathbb{1}[i=y]\). Its interpretation and role in backpropagation are developed in the Gradients lesson.
Multiple positions: causal shift and masks
In an autoregressive model, the representation at position \(t\) is used to predict the next token. Depending on the code convention, logits and labels must therefore be shifted consistently: the model must not receive the target token as unmasked context when predicting that same token.
For a batch, logits often have shape \((B,T,V)\) and labels shape \((B,T)\). Before interpreting the loss, check:
- Target shift: each logit is compared with the token it is supposed to predict, not accidentally with the input token.
- Padding and masks: ignored positions must contribute neither to the sum nor to the denominator of the mean.
- Reduction: a sum, mean over valid tokens, and mean over sequences do not have the same scale.
- Weighting: class weights, label smoothing, or auxiliary losses change the objective from the unweighted one-hot case.
- Comparison: state the tokenizer, included positions, and averaging convention before comparing two values.
Perplexity
For one-hot targets, mean cross-entropy computed over the same valid positions with the same reduction convention coincides with mean NLL. The definition and interpretation of perplexity, and the conditions required to compare scores, are consolidated in the Likelihood lesson.
Misconceptions
“Cross-entropy is between 0 and 1.” False: it can grow without bound when the model assigns probability close to zero to the target.
“A falling training loss proves that the model is improving.” No: validation, leakage, baselines, and generalization still need to be examined.
“Lower perplexity proves higher general capability.” No: it measures average prediction quality on a particular corpus, not direct success on every task. It does not necessarily capture gains from post-training or reasoning, and its irreducible information floor is unknown. Cross-lab comparisons are difficult when evaluation corpora and training mixtures differ. See OpenAI — Perplexity and Intelligence and Raschka — Pre-training is (still) not plateauing.
Soft targets and KL divergence
The one-hot case is sufficient to compute the penalty for an observed token. For a target that distributes its mass across several tokens, the identity \(H(q,p)=H(q)+D_{\mathrm{KL}}(q\Vert p)\), its assumptions and its boundary cases are developed in the Deepen resource The mathematics of language modeling. This derivation is not required to compute the NLL of one observed token.
Implementations — NumPy, PyTorch, and numerical stability
The NumPy reference implementation and its unit tests cover a deliberately small case: logits with shape \((B,C)\), one integer target per row, and the unweighted mean over rows. The loss uses natural logarithms, so its value is in nats. The gradient function returns the derivative of that same mean loss with respect to the logits; it is not a gradient with respect to a model’s parameters.
This reference does not implement sequence-level input/target shifting, token masks or ignore_index, soft targets, class weights, or perplexity. For token-level language modeling, callers must align logits and targets and select valid target positions before using this row-wise function. The implementation should not be mistaken for a complete LLM training loss.
The tests check a known value, central finite-difference agreement, stability for large logits, invariance to adding a constant per row, gradient row sums, non-mutation of inputs, and invalid-input handling. These checks support this reference implementation’s stated scope; they do not validate masking or sequence alignment, which are not implemented here.
The following self-contained example uses a common language-model output shape, (B,T,V), then flattens the first two dimensions because CrossEntropyLoss expects classes in the second dimension. Targets are assumed to be already aligned with the logits: this code does not construct the autoregressive input/target shift.
import torch
import torch.nn.functional as F
# B=1 batch, T=3 positions, V=3 vocabulary tokens.
logits = torch.tensor(
[[[2.0, 0.0, -1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 2.0]]],
dtype=torch.float64,
)
targets = torch.tensor([[0, 2, -100]], dtype=torch.long)
# Validate the sequence-level contract before inspecting dimensions.
assert logits.ndim == 3
batch_size, seq_len, vocab_size = logits.shape
assert targets.shape == (batch_size, seq_len)
assert targets.dtype == torch.long
valid = targets.ne(-100)
in_range = targets.ge(0) & targets.lt(vocab_size)
assert torch.all(in_range | targets.eq(-100))
assert valid.any()
flat_logits = logits.reshape(-1, vocab_size)
flat_targets = targets.reshape(-1)
per_token_loss = torch.nn.CrossEntropyLoss(
ignore_index=-100, reduction="none"
)(flat_logits, flat_targets).reshape(batch_size, seq_len)
mean_loss = torch.nn.CrossEntropyLoss(
ignore_index=-100, reduction="mean"
)(flat_logits, flat_targets)
manual_loss = -F.log_softmax(logits[valid], dim=-1).gather(
1, targets[valid].unsqueeze(1)
).mean()
# The framework reduction agrees with the mean over valid target positions.
torch.testing.assert_close(per_token_loss[valid].mean(), mean_loss)
torch.testing.assert_close(mean_loss, manual_loss)
# Passing probabilities as if they were logits changes the objective.
softmax_first_loss = torch.nn.CrossEntropyLoss(ignore_index=-100)(
logits.softmax(dim=-1).reshape(-1, vocab_size), flat_targets
)
assert not torch.isclose(mean_loss, softmax_first_loss)
print("per-token:", per_token_loss.tolist())
print("mean:", mean_loss.item()) # 0.860645...
print("softmax-first:", softmax_first_loss.item()) # 0.946560...The final position is ignored by ignore_index; it contributes neither to the sum nor to the mean denominator. reduction="none" exposes local losses, while reduction="mean" averages valid targets (with no class weights in this example). Applying softmax first is incorrect for the intended API use: it turns probabilities into a new set of input scores and changes the loss. This example demonstrates the API and reduction; it does not replace causal masking, target alignment, or a training loop.
PyTorch also accepts probability-distribution targets (for example with label smoothing), but ignore_index applies only to class-index targets. This example deliberately uses integer indices.
A common shape bug: normalizing over time instead of vocabulary
For logits shaped (B,T,V), each time position needs a probability distribution over the vocabulary. Therefore softmax must use dim=-1 (the vocabulary axis). Normalizing over dim=1 instead makes probabilities sum to one across time for each vocabulary entry; it does not produce a categorical distribution over tokens at each position.
import torch
logits = torch.tensor(
[[[2.0, 0.0, -1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 2.0]]],
dtype=torch.float64,
)
batch_size, seq_len, vocab_size = logits.shape
correct_probs = logits.softmax(dim=-1)
wrong_axis_probs = logits.softmax(dim=1)
# The vocabulary probabilities sum to one at every batch/time position.
torch.testing.assert_close(
correct_probs.sum(dim=-1),
torch.ones((batch_size, seq_len), dtype=logits.dtype),
)
# With the wrong axis, the sums over vocabulary are not one per position.
wrong_sums = wrong_axis_probs.sum(dim=-1)
assert not torch.allclose(
wrong_sums,
torch.ones_like(wrong_sums),
)This is why the example first flattens (B,T,V) to (B×T,V): the class/vocabulary dimension is then unambiguously dimension 1 for CrossEntropyLoss.
A numerical edge case: stable log-softmax
A direct softmax can underflow a very small target probability to zero. Taking its logarithm then produces infinity, even though the mathematically correct cross-entropy is finite. The fused, numerically stable cross-entropy computes the equivalent log-softmax expression without first materializing that zero probability.
import torch
import torch.nn.functional as F
extreme_logits = torch.tensor(
[[1000.0, 0.0, -1000.0]], dtype=torch.float64
)
extreme_target = torch.tensor([2], dtype=torch.long)
stable_loss = F.cross_entropy(extreme_logits, extreme_target)
naive_probability = extreme_logits.softmax(dim=-1)[0, 2]
naive_loss = -torch.log(naive_probability)
torch.testing.assert_close(
stable_loss, torch.tensor(2000.0, dtype=torch.float64)
)
assert torch.isfinite(stable_loss)
assert naive_probability == 0.0
assert torch.isinf(naive_loss)The infinite result is a floating-point failure of the naïve computation, not an infinite mathematical loss: for these logits, the exact loss is 2000 nats. In practice, pass logits directly to CrossEntropyLoss or use log_softmax followed by the target gather; do not compute log(softmax(logits)) yourself.
- “PyTorch CrossEntropyLoss expects probabilities.” For ordinary categorical classification, the API expects unnormalized logits and combines a log-softmax-like operation with NLL. Check shapes, ignore_index, targets, and reduction.
To revisit the connection with information theory, see the entropy synthesis, the review sheet, and the predictive compression experiment.
Practice
The questions and exercises for this lesson are collected on its dedicated practice page.
Supplementary resources Experiment, explore further, and practise the ideas from this lesson.
Further practice
The mathematical foundations collection includes worked exercises on logits, loss and masking; further topics remain planned.
References
- PyTorch — CrossEntropyLoss — API behaviour, not the general mathematical definition.
- PyTorch — LogSoftmax — log-softmax operation used to compute log-probabilities in a numerically stable way.
- C. E. Shannon (1948), A Mathematical Theory of Communication.
- Cover & Thomas, Elements of Information Theory.
- 3Blue1Brown — But what is cross-entropy? — visual intuition complementary to the derivation above.