Cross-Entropy Loss › Defining Cross-Entropy

Michael BrenndoerferFebruary 21, 20267 min read
Language AI HandbookAll chapters
Part 53 of 67Evaluation Fundamentals
Chapter 406Cross-Entropy Loss › Defining Cross-Entropy
Reading section 3 of 15 · Defining Cross-Entropy · 7 minSection 3 of 15 · 7 min

Book contents

Section 3 of 15 · 7 min read

Cross-Entropy Loss › Defining Cross-EntropyOne section · Sections in this chapter3 / 15 ↓
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

Cross-entropy combines the entropy of the true distribution with the KL divergence between true and predicted distributions into a single quantity that we can compute from data. For distributions PP (true) and QQ (model prediction), cross-entropy is:

H(P,Q)=−∑xP(x)log⁡Q(x)H(P, Q) = -\sum_{x} P(x) \log Q(x)

where:

  • H(P,Q)H(P, Q): the cross-entropy between the true distribution PP and the predicted distribution QQ
  • P(x)P(x): the probability of outcome xx under the true distribution (empirical distribution from data)
  • Q(x)Q(x): the probability of outcome xx assigned by the model
  • xx: an outcome from the set of possible events

When PP represents the empirical distribution from training data, P(x)P(x) is 1 for the actual observed token and 0 for all others. This simplifies cross-entropy dramatically because the sum collapses to a single term involving only the true token:

H(P,Q)=−∑xP(x)log⁡Q(x)=−log⁡Q(xtrue)\begin{aligned} H(P, Q) &= -\sum_{x} P(x) \log Q(x) \\ &= -\log Q(x_{\text{true}}) \end{aligned}

where:

  • xtruex_{\text{true}}: the observed token (the single outcome where P(x)=1P(x) = 1)
  • Q(xtrue)Q(x_{\text{true}}): the probability assigned by the model to the true token

This is the negative log-likelihood of the true token under the model's predicted distribution. It penalizes the model proportionally to how surprised it was by the actual observation: if the model assigns high probability to the correct token, the loss is small; if the model assigns low probability, the loss is large, approaching infinity as the predicted probability approaches zero.

The simplification from the full sum to a single term has an important practical consequence. During training, we do not need to compare probability distributions element by element across the entire vocabulary. We only need to look up how much probability the model assigned to the one token that appeared next. This makes gradient computation efficient: backpropagation only needs to update the output neuron corresponding to the true token, though intermediate layers receive gradients from all vocabulary items through the softmax normalization.

Out[4]:
Visualization
Line chart showing cross-entropy loss in nats and bits rising steeply as predicted probability approaches zero and falling toward zero as probability approaches one.
Cross-entropy loss as a function of predicted probability for the true class. The loss decreases rapidly as model confidence increases, approaching zero for perfect prediction, and rises steeply to infinity as the predicted probability approaches zero. The steep left tail creates strong gradient signals that push the model to avoid confidently wrong predictions.
Cross-Entropy Decomposition

Cross-entropy decomposes into entropy plus KL divergence:

H(P,Q)=H(P)+DKL(P∥Q)H(P, Q) = H(P) + D_{KL}(P \| Q)

where:

  • H(P,Q)H(P, Q): the cross-entropy between the true distribution PP and the predicted distribution QQ
  • H(P)H(P): the entropy of the true distribution (constant with respect to model parameters)
  • DKL(P∥Q)D_{KL}(P \| Q): the KL divergence from the model distribution to the true distribution

Since H(P)H(P) is constant with respect to model parameters, minimizing cross-entropy is equivalent to minimizing KL divergence. This decomposition reveals that cross-entropy captures both the inherent uncertainty in the data (the entropy term) and the additional penalty for using a suboptimal model (the KL divergence term). During optimization, the entropy term acts as a constant offset, so gradient descent on cross-entropy effectively minimizes the KL divergence between our model and reality. The lowest achievable cross-entropy on any dataset equals the true entropy of the language, which represents the irreducible uncertainty stemming from inherent ambiguity in text.

Cross-Entropy as Maximum Likelihood Estimation

The connection between cross-entropy and maximum likelihood estimation (MLE) explains the statistical basis for using cross-entropy to train probabilistic language models. Given a dataset of NN observed tokens {x1,x2,…,xN}\{x_1, x_2, \ldots, x_N\}, MLE seeks the model parameters θ\theta that maximize the probability of the observed data:

θ^=arg⁡max⁡θ∏i=1NP(xi∣contexti;θ)\hat{\theta} = \arg\max_{\theta} \prod_{i=1}^{N} P(x_i | \text{context}_i; \theta)

where:

  • θ^\hat{\theta}: the maximum likelihood estimate of the model parameters
  • P(xi∣contexti;θ)P(x_i | \text{context}_i; \theta): the model's probability of the ii-th observed token given its context
  • ∏\prod: the product over all tokens in the dataset

Because products of many small probabilities rapidly underflow to zero numerically, we take the logarithm of both sides. This converts the product into a sum, which is numerically stable:

θ^=arg⁡max⁡θ∑i=1Nlog⁡P(xi∣contexti;θ)=arg⁡min⁡θ−1N∑i=1Nlog⁡P(xi∣contexti;θ)\begin{aligned} \hat{\theta} &= \arg\max_{\theta} \sum_{i=1}^{N} \log P(x_i | \text{context}_i; \theta) \\ &= \arg\min_{\theta} -\frac{1}{N} \sum_{i=1}^{N} \log P(x_i | \text{context}_i; \theta) \end{aligned}

where:

  • ∑i=1Nlog⁡P(xi∣contexti;θ)\sum_{i=1}^{N} \log P(x_i | \text{context}_i; \theta): the log-likelihood of the observed tokens
  • −1N∑i=1Nlog⁡P(xi∣contexti;θ)-\frac{1}{N} \sum_{i=1}^{N} \log P(x_i | \text{context}_i; \theta): the negative log-likelihood, normalized by dataset size

The final expression is exactly the cross-entropy loss averaged over the training set. Minimizing cross-entropy is mathematically identical to performing maximum likelihood estimation. This means we have a strong statistical justification for using cross-entropy: it is the objective that, as NN grows large, causes our model to converge to the true underlying data distribution (or the closest approximation within our model family). Any other loss function would not have this convergence guarantee in the same form.

The Language Modeling Objective

In autoregressive language modeling, we predict the next token xtx_t given previous tokens x<tx_{<t}. This sequential factorization allows us to model complex joint distributions over sequences by breaking them down into manageable conditional probabilities. The probability of a sequence factorizes as:

P(x1,x2,…,xT)=∏t=1TP(xt∣x<t)P(x_1, x_2, \ldots, x_T) = \prod_{t=1}^{T} P(x_t | x_{<t})

where:

  • P(x1,x2,…,xT)P(x_1, x_2, \ldots, x_T): the joint probability of the entire sequence
  • P(xt∣x<t)P(x_t | x_{<t}): the conditional probability of token xtx_t given all preceding tokens x<tx_{<t}

This factorization is exact: the chain rule of probability guarantees it without any independence assumptions. The cross-entropy loss for a sequence of length TT is:

L=−1T∑t=1Tlog⁡P(xt∣x<t;θ)\mathcal{L} = -\frac{1}{T} \sum_{t=1}^{T} \log P(x_t | x_{<t}; \theta)

where:

  • L\mathcal{L}: the average cross-entropy loss over the sequence
  • TT: the length of the target sequence (number of tokens)
  • xtx_t: the token at position tt in the sequence
  • x<tx_{<t}: all tokens preceding position tt (the context)
  • θ\theta: the model parameters
  • P(xt∣x<t;θ)P(x_t | x_{<t}; \theta): the model's predicted probability of token xtx_t given previous tokens

This formulation reveals why cross-entropy is called the log-loss: we sum the negative log probabilities of each token. Lower probability assigned to the correct token results in higher loss, with the loss approaching infinity as the predicted probability approaches zero. This creates strong gradients when the model is confidently wrong, pushing the parameters aggressively to correct major errors.

The averaging by TT (sequence length) ensures that longer sequences do not automatically incur higher loss simply because they contain more tokens. This normalization allows us to compare loss values across sequences of different lengths and to aggregate loss across batches during training. Without this normalization, a long document would always appear to be modeled worse than a short sentence, even if the model's per-token accuracy was identical.

A necessary practical point: in transformer training, the model processes an entire sequence in a single forward pass, computing predicted probability distributions at every position simultaneously. For a sequence of length TT, this produces TT losses in parallel. The positions at the beginning of the sequence receive less context than positions near the end, so the model must predict early tokens with limited information. This variability in difficulty across positions is averaged away by the uniform weighting in the loss, which treats all positions equally. Some researchers have proposed weighting later positions more heavily, since they benefit from richer context and thus provide cleaner learning signal, but this remains an active area of investigation.