NeuroGenesys.
Information TheoryAcademy • Foundations • Lesson 2 of 3

Cross-entropy and KL divergence: the language-model loss

6 min read • By Will Schulz • NeuroGenesys AI Academy

What does it cost to describe data with the wrong probability model, and why is that cost the loss nearly every language model is trained on? Cross-entropy measures that cost, and KL divergence isolates the part that comes from the model being wrong.

Coding with the wrong distribution

Entropy told us that an outcome of probability p(x)p(x) deserves a codeword of about −log⁡p(x)-\log p(x) bits. Now suppose the data really come from pp, but we design our code from a model qq. Each outcome xx then costs −log⁡q(x)-\log q(x), and the average cost is the cross-entropy:

H(p,q)=−∑xp(x)log⁡q(x)=Ex∼p[−log⁡q(x)].H(p, q) = -\sum_x p(x)\log q(x) = \mathbb{E}_{x\sim p}\big[-\log q(x)\big].

Split it into two parts:

H(p,q)=−∑xp(x)log⁡p(x)⏟H(p)  +  ∑xp(x)log⁡p(x)q(x)⏟DKL(p ∥ q).H(p,q) = \underbrace{-\sum_x p(x)\log p(x)}_{H(p)} \;+\; \underbrace{\sum_x p(x)\log\frac{p(x)}{q(x)}}_{D_{\mathrm{KL}}(p\,\|\,q)} .

The first term is the unavoidable cost of the source's own uncertainty. The second is the Kullback–Leibler divergence, introduced by Solomon Kullback and Richard Leibler in 1951 as a measure of the information available for telling two distributions apart.[1] In coding terms, it is the expected number of extra bits you pay per symbol for using qq in place of pp.[2]

Gibbs' inequality

DKL(p ∥ q)≥0D_{\mathrm{KL}}(p\,\|\,q)\ge 0, with equality if and only if q=pq=p. One line of proof uses Jensen's inequality on the concave logarithm:

−DKL(p∥q)=∑xp(x)log⁡q(x)p(x)≤log⁡∑xp(x)q(x)p(x)=log⁡∑xq(x)≤log⁡1=0.-D_{\mathrm{KL}}(p\|q) = \sum_x p(x)\log\frac{q(x)}{p(x)} \le \log\sum_x p(x)\frac{q(x)}{p(x)} = \log\sum_x q(x) \le \log 1 = 0 .

So H(p,q)≥H(p)H(p,q)\ge H(p). No model can beat the true distribution at coding its own data, and the gap is exactly the KL divergence.[2]

Worked example: KL is not symmetric

Let p=(12,14,14)p = (\tfrac12, \tfrac14, \tfrac14) and let qq be uniform, (13,13,13)(\tfrac13,\tfrac13,\tfrac13). In bits:

  • H(p)=12(1)+14(2)+14(2)=1.5H(p) = \tfrac12(1)+\tfrac14(2)+\tfrac14(2) = 1.5.
  • H(p,q)=log⁡23≈1.585H(p,q) = \log_2 3 \approx 1.585, because every outcome costs log⁡23\log_2 3 under the uniform code.
  • DKL(p∥q)=1.585−1.5≈0.085D_{\mathrm{KL}}(p\|q) = 1.585 - 1.5 \approx 0.085 bits.

Now reverse the roles:

DKL(q∥p)=13[log⁡21/31/2+2log⁡21/31/4]=13[−0.585+2(0.415)]≈0.082 bits.D_{\mathrm{KL}}(q\|p) = \tfrac13\Big[\log_2\tfrac{1/3}{1/2} + 2\log_2\tfrac{1/3}{1/4}\Big] = \tfrac13\big[-0.585 + 2(0.415)\big] \approx 0.082 \text{ bits}.

The two directions give different numbers. KL divergence is not a distance metric: it is asymmetric and does not satisfy the triangle inequality. Which direction you minimise changes what you get, as discussed below.

Check your understanding

A model assigns probability q(x)=0q(x)=0 to an outcome that actually occurs with p(x)=0.01p(x)=0.01. What is DKL(p∥q)D_{\mathrm{KL}}(p\|q), and what does this imply for language-model training?

Show answer +

It is infinite: the term p(x)log⁡p(x)0p(x)\log\frac{p(x)}{0} diverges. Under the forward direction, a model that rules out anything that can happen pays an unbounded penalty. That is why softmax outputs, which are never exactly zero, are a natural fit for cross-entropy training, and why language models spread at least a little probability over everything plausible.

Why this is the language-model loss

A language model defines conditional distributions qθ(xt∣x<t)q_\theta(x_t\mid x_{<t}) over a vocabulary. Training on a corpus minimises the average negative log-probability of each actual next token:

L(θ)=−1N∑t=1Nlog⁡qθ(xt∣x<t).\mathcal{L}(\theta) = -\frac{1}{N}\sum_{t=1}^{N}\log q_\theta(x_t\mid x_{<t}).

This is cross-entropy with a "one-hot" target: the empirical distribution puts all its mass on the token that actually appeared. Averaged over the data distribution pp, it is

E [L]=H(p,qθ)=H(p)+DKL(p ∥ qθ).\mathbb{E}\,[\mathcal{L}] = H(p, q_\theta) = H(p) + D_{\mathrm{KL}}(p\,\|\,q_\theta).

Since H(p)H(p) does not depend on θ\theta, minimising cross-entropy is the same as minimising the forward KL divergence from the data to the model. It is also the same as maximising likelihood, because −log⁡qθ-\log q_\theta summed over the data is the negative log-likelihood. The probabilistic view of this is in Maximum likelihood. Three standard ways of describing training, as maximum likelihood, KL minimisation and code-length minimisation, all describe the same objective.

Units and perplexity

Training code usually computes the loss in nats. Dividing by ln⁡2\ln 2 gives bits per token. Perplexity is the exponentiated loss, exp⁡(Lnats)\exp(\mathcal{L}_{\text{nats}}). Suppose a model's validation loss is 2.0 nats per token. That is 2.0/0.693≈2.892.0/0.693 \approx 2.89 bits per token, and its perplexity is e2.0≈7.39e^{2.0}\approx 7.39. On average the model is as uncertain as if it were choosing uniformly among about 7.4 tokens. Because the irreducible H(p)H(p) is unknown, a loss value alone does not tell you how close a model is to the floor. Loss comparisons are meaningful only on the same data with the same tokenizer.

The gradient is "prediction minus target"

With logits zz and q=softmax(z)q = \mathrm{softmax}(z), the cross-entropy against a target distribution yy (one-hot or soft) has a very simple gradient:

∂∂zi(−∑jyjlog⁡qj)=qi−yi.\frac{\partial}{\partial z_i}\Big(-\sum_j y_j\log q_j\Big) = q_i - y_i .

Each logit is pushed up by the probability the model failed to give the right answer and pushed down by the probability it gave the wrong ones. The gradient is bounded and well scaled, which is part of why softmax with cross-entropy is the default output layer for classifiers and language models. The full backward pass is covered in Backpropagation.

Check your understanding

A three-token vocabulary gives softmax probabilities q=(0.7,0.2,0.1)q=(0.7, 0.2, 0.1), and the correct token is the second one. What is the loss in nats, and what is the gradient with respect to the logits?

Show answer +

Loss =−ln⁡0.2≈1.61= -\ln 0.2 \approx 1.61 nats. Gradient =q−y=(0.7, 0.2−1, 0.1)=(0.7, −0.8, 0.1)= q - y = (0.7,\,0.2-1,\,0.1) = (0.7,\,-0.8,\,0.1). A gradient-descent step raises the correct logit and lowers the other two in proportion to their probabilities.

Forward versus reverse KL

The direction of the divergence decides the behaviour of the fitted model:

ObjectivePenalises heavilyTypical behaviour of qqWhere it appears
Forward, DKL(p∥q)D_{\mathrm{KL}}(p\|q)qq small where pp is largeMass-covering: spreads out to cover every mode of ppMaximum-likelihood pretraining; distillation
Reverse, DKL(q∥p)D_{\mathrm{KL}}(q\|p)qq large where pp is smallMode-seeking: concentrates on one high-probability regionVariational inference; KL penalties on a policy

Two places in modern training make the distinction concrete:

  • Distillation. A small "student" is trained to match a large "teacher" by minimising cross-entropy against the teacher's full output distribution ("soft targets"), not only the one-hot label.[3] Since the teacher's entropy is fixed, this is forward-KL minimisation toward the teacher. The soft targets carry information about which wrong answers are nearly right.
  • Fine-tuning with a KL leash. In reinforcement learning from human feedback, the policy is rewarded by a learned reward model but penalised by a per-token KL term against the supervised starting model. The penalty discourages it from drifting into outputs the reward model scores well but the original model considers very unlikely.[4] Here the expectation is taken under the policy's own samples, which makes it the reverse direction.

Key takeaways

  • Cross-entropy H(p,q)H(p,q) is the average code length when data from pp are coded with model qq. It equals H(p)+DKL(p∥q)H(p) + D_{\mathrm{KL}}(p\|q).
  • KL divergence is non-negative and zero only when q=pq=p. It is asymmetric, and the direction you choose determines whether the fitted model is mass-covering or mode-seeking.
  • The language-model loss is per-token cross-entropy. Minimising it is the same as maximum likelihood and the same as minimising forward KL from data to model.
  • The softmax cross-entropy gradient is q−yq - y: prediction minus target.
  • Perplexity is elosse^{\text{loss}}. Loss numbers can be compared only on the same data and tokenizer, because the entropy floor H(p)H(p) is unknown.

Sources

  1. S. Kullback and R. A. Leibler (1951). "On Information and Sufficiency." The Annals of Mathematical Statistics 22(1), 79–86. https://doi.org/10.1214/aoms/1177729694 ↩

  2. T. M. Cover and J. A. Thomas (2006). Elements of Information Theory, 2nd ed. Wiley-Interscience. https://doi.org/10.1002/047174882X ↩ ↩2

  3. G. Hinton, O. Vinyals and J. Dean (2015). "Distilling the Knowledge in a Neural Network." arXiv:1503.02531. https://arxiv.org/abs/1503.02531 ↩

  4. L. Ouyang, J. Wu, X. Jiang et al. (2022). "Training language models to follow instructions with human feedback." arXiv:2203.02155. https://arxiv.org/abs/2203.02155 ↩

Leadership

A word from the founder — on why the brain is the blueprint, and why the next decade of intelligence will be built here.

"The brain is the universe's only proof that general intelligence is possible. We treat it as the blueprint."

From cortical interfaces to photonic silicon, every program at NeuroGenesys exists to answer one question: how does intelligence arise — and how do we build it safely.

Will Schulz

Will Schulz

Founder, NeuroGenesys • AW3 Technology