17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
A language model’s training loop prints a number, the negative log-likelihood, from its very first run. The byte bigram in Byte bigram: counts, logits, safetensors v0 in AI Engineering already reports it, but nothing yet says what that number is measured against or how low it can go. Once you train the same bigram by gradient descent in Training loop and the autograd bigram, with the cross-entropy loss of Losses with a fused backward, the loss needs a meaning: what is the floor, and how far above it are you?
Concepts from other sections (12)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Acceptance rate: accepted draft tokens over proposed draft tokens; per token, . Read more: 21.6 Speculative decoding: n-gram, prompt-lookup, and model drafts in AI Engineering
- Gibbs’ inequality: , with equality if and only if ; coding data from with a code built for always costs extra bits, so cross-entropy is never below entropy. Read more: Chapter 17: Information Theory
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- GRPO: a PPO-style RL method that replaces the critic with the group-normalized reward of several samples of the same prompt. Read more: 19.7 The training step and validation in AI Engineering
- Log-likelihood: , the log probability of the observed counts under a distribution . Read more: 13.3 MLE, Laplace, absolute discounting
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- reverse KL: , weighted by the student; mode-seeking. Read more: 18.4 Distillation with forward and reverse KL in AI Engineering
- Standard error: , the estimated standard deviation of the sample mean. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Mutual information: , the nats that knowing one variable saves about the other. Read more: 17.3 Mutual information, PMI, and PPMI
Information theory answers that, and the same few quantities keep returning later in the system. The sampler in Sampling and logit processors logs the entropy of every step so a collapsing temperature shows up in the traces. Speculative decoding reads its acceptance rate off the distance between two distributions. Post-training in Group relative policy optimization with verifiable rewards penalizes the policy for drifting from a reference model with a sampled KL. And Matrix differentials, the trace trick, and closed-form VJPs needs a forward cross-entropy to check its gradient against. Each of these needs the same definitions, with the same conventions at zero, in nats, and stable on the log-probabilities models actually produce.
This section builds entropy, cross-entropy, KL divergence, Jensen-Shannon divergence and Schulman’s k3 estimator from the single idea of surprise, works every one by hand on a three-outcome example, and then walks through the reference implementation, entropy.py (contract: entropy.pyi), function by function. It builds on Stable numerics: logsumexp, softmax, and compensated sums, whose log_softmax it calls. As you read the code, try to predict each line before you see it.
Learning objectives
- Define entropy, cross-entropy, KL and JS, and compute each by hand for a small distribution.
- Prove Gibbs’ inequality and explain why the cross-entropy loss has a floor at the data’s entropy.
- Compute KL and entropy from log-probabilities and logits without producing NaN or losing precision.
- Explain why the k3 estimator is unbiased and nonnegative, and why it is computed with
expm1.- Apply the conventions and exactly, without an epsilon.
Notation
Section titled “Notation”The quantities in this section share a small vocabulary of symbols, collected here for reference.
| Symbol | Meaning | Type / shape |
|---|---|---|
| number of outcomes (vocabulary size for a language model) | int | |
| probability distributions over the outcomes: , | float64[n] | |
| the natural logarithm; results are in nats (divide by for bits) | ||
| entropy of | scalar | |
| cross-entropy of relative to | scalar | |
| Kullback-Leibler divergence from to | scalar, | |
| the mixture of and | float64[n] | |
| Jensen-Shannon divergence | scalar in | |
| a policy and a reference model (as in GRPO post-training) | distributions | |
| an outcome sampled from | index | |
| log ratio at a sample | scalar | |
| the k3 estimator of | scalar, | |
| logits, with a distribution | float64[n] |
Surprise and entropy
Section titled “Surprise and entropy”Start with a single outcome. An outcome of probability carries surprise . A certain outcome () carries none, a rare one carries a lot, and the surprise of two independent outcomes adds, because . With the unit is the bit, and is the length of the best code word for outcome .
Entropy is the average surprise:
A term with is defined as 0, because as : an outcome that never happens costs nothing. since every surprise is , and , with equality exactly for the uniform distribution. Nothing is more unpredictable than equal chances.
Cross-entropy: a model measured against data
Section titled “Cross-entropy: a model measured against data”Now suppose the data come from but you predict with a model . Your average surprise is
This is the language-model loss. With the one-hot distribution of the observed next token , it is , and averaging over positions gives the negative log-likelihood the bigram already prints. A term with and is : the model said impossible, and it happened.
KL divergence: the excess, never negative
Section titled “KL divergence: the excess, never negative”Cross-entropy mixes two things: the inherent unpredictability of the data and the model’s mistakes. Subtracting the entropy isolates the second:
KL is never negative, a fact known as Gibbs’ inequality. The proof uses for , with equality only at . Over the outcomes with ,
Equality needs everywhere. So minimizing the cross-entropy over minimizes KL, and the loss floor is , the entropy of the data itself. Training a language model is pushing toward 0; the training loss is the data’s own entropy, which no model can beat, plus the model’s excess.
KL also has a direction. weighs the log ratio by , so it punishes for being small where is large (it is “mass covering”), and it is infinite if misses any outcome of . punishes the opposite and prefers a that sits on one mode of . The two are different numbers: for against uniform, one direction gives 0.36806 and the other 0.51083. The post-training chapter of AI Engineering picks one direction on purpose, as Distillation with forward and reverse KL shows.
KL from log-probabilities
Section titled “KL from log-probabilities”Models do not hand you probabilities; they output log-probabilities, , which stay finite even where the probability underflows. So write KL in terms of them:
a difference of moderate numbers. Never form , which is or when the logits are large. Two edge cases need care. means and contributes 0, even against , where the difference would be NaN. A finite against is , even when underflows to 0, where would be NaN.
Jensen-Shannon: symmetric and bounded
Section titled “Jensen-Shannon: symmetric and bounded”KL’s asymmetry and its infinities are sometimes exactly what you want and sometimes a nuisance. When you want a symmetric, always-finite comparison, compare both distributions with their average :
is positive wherever or is, so JS is always finite. And since , every , so , a bound reached by distributions with disjoint supports.
Estimating KL from samples: k3
Section titled “Estimating KL from samples: k3”When is a whole vocabulary and you only have the log-probabilities of the tokens you sampled, you cannot sum over every outcome. Instead you estimate by averaging over samples. The plain estimator is unbiased but negative for many samples, which is awkward for a per-token penalty. Schulman’s k3 adds a term with mean zero:
so has the same mean, . (The sum runs over ‘s support, which is everything for softmax outputs.) And every sample is , because the exponential lies above its tangent at 0: .
There is a numerical trap in the formula. Near , is tiny while . Computing subtracts numbers near 1 and keeps only the rounding error of , about , against a true value of at . np.expm1(r) computes directly to full relative precision, so keeps the answer. This is exactly the regime at the start of post-training, when the policy has barely moved.
Entropy from logits
Section titled “Entropy from logits”The same reasoning applies to entropy. With from Stable numerics, , with masked entries () contributing 0. Computing and then meets as soon as one probability underflows.
Working it by hand
Section titled “Working it by hand”With the definitions in place, it helps to see every one of them produce a number. Take , , . Every log is a multiple of except one.
The entropy is nats, which is 1.5 bits.
The cross-entropy is .
The KL divergence, computed directly, is . As a check, , the same number.
For Jensen-Shannon, the mixture is , and the terms of are:
| 0 | ||
So . By the symmetry of this example is the same, and , well under .
For k3, let and . The log ratios are :
| 1 | 1/2 | ||
| 2 | 1/4 | 0 | 0 |
| 3 | 1/4 |
The mean under is . That is exactly , as promised, and every row is nonnegative.
Finally, entropy from logits: gives and softmax , so the entropy is again .
These numbers are the first test case any implementation should pass.
Designing the interface
Section titled “Designing the interface”The implementation lives in one module, with natural logs throughout so every result is in nats:
# python/tinyllm/info/entropy.py (natural logs: nats)def entropy(p: ArrayLike, axis: int = -1) -> NDArraydef cross_entropy(p: ArrayLike, q: ArrayLike, axis: int = -1) -> NDArraydef kl(p: ArrayLike, q: ArrayLike, axis: int = -1) -> NDArraydef kl_from_logprobs(logp: ArrayLike, logq: ArrayLike, axis: int = -1) -> NDArraydef js(p: ArrayLike, q: ArrayLike) -> NDArray # last axisdef kl_k3(logp_ref: ArrayLike, logp: ArrayLike) -> NDArray # elementwise, no reductiondef entropy_from_logits(z: ArrayLike, axis: int = -1) -> NDArrayEach function reduces over axis and drops it, like np.sum. Probabilities are not renormalized, and a negative one is a ValueError. Note the argument order of kl_k3: the reference model comes first, as in . The zero conventions are computed with np.where on the individual terms; adding a small epsilon inside the logs would bias every answer and turn a true into a large finite number.
Building it step by step
Section titled “Building it step by step”The reasoning behind the implementation is short, and each step follows from the one before.
- Every quantity is a sum of per-outcome terms. , , KL and JS all have the form , reduced over one axis. So each function builds an array of terms with the input’s shape and calls
np.sum(..., axis=axis)once; batching ([B, V]to[B]) then comes for free. - The zero conventions are properties of single terms. and are statements about one , so they are applied to the term array with
np.wherebefore the sum. They are not approximations, so there is no epsilon: shifts every finite answer and turns a true into a large finite number. - NumPy will produce the wrong values first, and the
wherereplaces them.0 * np.log(0)is0 * -inf = nan, andnp.log(0)warns. The solution lets NumPy compute the raw term undernp.errstate(...), silencing the warning it knows about, and then overwrites exactly the positions the convention covers.np.whereevaluates both branches, which is why the raw computation must be allowed to producenanquietly. - KL needs both conventions, in a fixed priority. wins (the term is 0 even if ); otherwise gives . Writing it as
a * (log a - log b)rather thana * log(a / b)keeps the two logs separate, the same form the log-probability version uses. - From log-probabilities, the same priority is tested on the logs.
logp = -infis , so the term is 0; otherwiselogq = -infis . Testingnp.isneginf(lq)instead of the product matters: atlp = -800,np.exp(lp)underflows to 0 and0 * infwould benan, but the true term is because . - JS reuses KL. is positive wherever or is, so
kl(a, m)never hits the branch, and the result is finite and at most with no special code. - k3 is one line once is right. , reference first, and is written
np.expm1(r) - rso the survives when is tiny. - Entropy from logits goes through
log_softmax. The stable-numerics section already makes finite for huge logits, so the term is with masked entries () set to 0, the same convention as step 2 expressed on logs.
Now the code. Two private helpers carry the validation and the rule:
def _probs(p: ArrayLike, name: str) -> NDArray: """p as a float64 array, ValueError on a negative entry.""" a = np.asarray(p, dtype=np.float64) # A negative "probability" is almost always a logit passed by mistake. # Fail loudly instead of returning log(negative) = nan. if (a < 0).any(): raise ValueError(f"{name} has a negative probability (min {a.min()!r})") return a
def _xlogy(x: NDArray, y: NDArray) -> NDArray: """x * log(y) elementwise with 0 * log(anything) = 0.""" with np.errstate(divide="ignore", invalid="ignore"): t = x * np.log(y) # may be 0 * -inf = nan where x == 0 return np.where(x == 0, 0.0, t) # the convention overrides those entries_xlogy handles but deliberately not with : there x * log(0) is already , which is the right term for cross-entropy ( after the minus sign). Note too that no function renormalizes its input: a row that sums to 0.9 gives the formula’s value for that row, not for a corrected one.
With the helpers, entropy and cross-entropy are one line each:
def entropy(p: ArrayLike, axis: int = -1) -> NDArray: a = _probs(p, "p") return -np.sum(_xlogy(a, a), axis=axis) # H(p) = -sum p log p
def cross_entropy(p: ArrayLike, q: ArrayLike, axis: int = -1) -> NDArray: a, b = _probs(p, "p"), _probs(q, "q") return -np.sum(_xlogy(a, b), axis=axis) # H(p, q) = -sum p log qKL cannot use _xlogy, because it needs the second convention as well:
def kl(p: ArrayLike, q: ArrayLike, axis: int = -1) -> NDArray: a, b = _probs(p, "p"), _probs(q, "q") with np.errstate(divide="ignore", invalid="ignore"): t = a * (np.log(a) - np.log(b)) # p = 0 costs nothing; p > 0 where q = 0 is log(p / 0) = +inf. # The outer where is checked first, so p = q = 0 gives 0, not inf. t = np.where(a == 0, 0.0, np.where(b == 0, np.inf, t)) return np.sum(t, axis=axis)The log-probability version has the same structure with the tests moved onto the logs:
def kl_from_logprobs(logp: ArrayLike, logq: ArrayLike, axis: int = -1) -> NDArray: lp = np.asarray(logp, dtype=np.float64) lq = np.asarray(logq, dtype=np.float64) with np.errstate(invalid="ignore", over="ignore"): # A difference of moderate numbers: never exp(lp) / exp(lq). t = np.exp(lp) * (lp - lq) # logp = -inf is p = 0: no cost. logq = -inf under p > 0 is +inf, even when # exp(logp) underflows to 0 (0 * inf would be nan). t = np.where(np.isneginf(lp), 0.0, np.where(np.isneginf(lq), np.inf, t)) return np.sum(t, axis=axis)There is no _probs check here: log-probabilities are naturally negative, and validating them would reject every valid input.
The last three functions are short because the hard decisions have already been made:
def js(p: ArrayLike, q: ArrayLike) -> NDArray: a, b = _probs(p, "p"), _probs(q, "q") m = 0.5 * (a + b) # positive wherever a or b is: KL(., m) is finite return 0.5 * kl(a, m) + 0.5 * kl(b, m)
def kl_k3(logp_ref: ArrayLike, logp: ArrayLike) -> NDArray: # Reference first: r = log pi_ref - log pi, so E_pi[e^r] = 1. r = np.asarray(logp_ref, dtype=np.float64) - np.asarray(logp, dtype=np.float64) # exp(r) - 1 - r loses everything to rounding when |r| is small: exp(r) # is 1 + r + r^2/2 and the 1 swallows the r^2/2. expm1 keeps it. return np.expm1(r) - r # elementwise: one value per sample, no mean
def entropy_from_logits(z: ArrayLike, axis: int = -1) -> NDArray: lp = log_softmax(np.asarray(z, dtype=np.float64), axis=axis) # M09.2, finite at 1e4 with np.errstate(invalid="ignore"): t = np.exp(lp) * lp # 0 * -inf = nan on masked entries... return -np.sum(np.where(np.isneginf(lp), 0.0, t), axis=axis) # ...which are 0js reduces over the last axis only (it calls kl with the default), which is what the contract says. kl_k3 returns per-sample values because its caller in GRPO post-training adds them per token and averages over its own batch and mask; reducing here would throw away that structure.
The full solution is entropy.py.
Why this design
Section titled “Why this design”Every function is one vectorized pass over the input: time per row and temporary memory for the term array. The np.where calls cost a few extra passes, negligible next to the log and exp.
The choice of np.where over an epsilon is the central one. An epsilon is shorter, but it is wrong by construction: it changes finite answers, hides a true (a model that assigned probability 0 to something that happened), and its “right size” depends on the dtype. The where gives exact conventions and the same results as SciPy. Boolean-mask indexing (t[a == 0] = 0) would also work, but where keeps every function a pure expression that also works on 0-d inputs, and it composes cleanly for KL’s two nested conventions.
Computing KL from log-probabilities, rather than as kl(exp(logp), exp(logq)), matters because exponentiating first loses everything below about to zero and then needs the infinite-KL branch where the true answer is finite. Staying in logs keeps precision where models actually live. SciPy’s scipy.special.xlogy and rel_entr would do the same jobs, and _xlogy mirrors them; writing them out keeps the conventions visible and the module dependent only on NumPy and log_softmax.
One tradeoff is accepted deliberately: there is no renormalization. A slightly unnormalized input gives a slightly off answer rather than being silently fixed. That surfaces bugs upstream, such as a softmax over the wrong axis, instead of hiding them.
What can go wrong
Section titled “What can go wrong”A correct implementation has to survive a specific set of checks. It must reproduce every hand-worked number above, in nats, and agree with SciPy’s entropy, KL and JS on dense, sparse, peaked and column-wise inputs. It must satisfy Gibbs’ inequality ( on 200 random pairs, exactly 0 at ), which guarantees a KL penalty never rewards drift, and the decomposition , which is how you read a loss as floor plus excess. KL must not be symmetric: against uniform gives 0.36806 one way and 0.51083 the other, because forward and reverse KL are different objectives.
At the boundaries, , , and no NaN may appear, which is what sparse distributions and masked tokens need. A negative entry must be a ValueError everywhere, so a logit passed as a probability fails loudly. Entropy must be 0 for a one-hot distribution, for uniform, and in between otherwise; that is how you read the sampler’s entropy log. Shapes must batch: [B, V] reduces to [B], and axis=0 reduces columns. JS must be symmetric, lie in , and equal for disjoint supports.
The log-space functions carry their own checks. kl_from_logprobs must equal kl on the same distributions, entries included; it must give a finite, correct KL from logits near (late training, low temperature); and against must be 0 while a finite value (even ) against is , with no NaN from or . The k3 estimator must be nonnegative on 1000 samples, 0 at and at ; it must have relative error below at , the regime at the start of post-training; and its mean must be KL, exactly by enumeration and within 4 standard errors over 20000 samples. Entropy from logits must equal , stay finite at , and count masks as 0.
Most failures come from a short list of mistakes, summarized here with how the solution avoids each:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
p * np.log(p) with , or an epsilon inside the logs | NaN entropy for sparse rows; a finite KL where it is infinite | computes the raw term, then overrides the convention positions with np.where (_xlogy and kl) |
| forming from exponentiated log-probabilities | 0/0 and inf/inf once logits are large | kl_from_logprobs uses the difference lp - lq, weighted by exp(lp) |
| computing when you meant | the right number only on symmetric examples | weights by the first argument everywhere: a * (log a - log b) |
np.exp(r) - r - 1 | rounding noise instead of for small | np.expm1(r) - r in kl_k3 |
-sum(p * log(p)) with | NaN entropy as soon as one probability underflows | entropy_from_logits works on log_softmax(z) and masks entries |
np.log2 instead of the natural log | every number off by a factor of | uses np.log throughout: every result is in nats |
| the k3 ratio upside down, | still nonnegative, but its mean is not KL | takes logp_ref first and computes logp_ref - logp |
| letting or through | NaN where the answer is 0 or | tests np.isneginf on lp first, then on lq |
Warning: A flipped k3 ratio is the most dangerous of these, because nothing looks wrong. Every value stays nonnegative; only the mean is off.
Where this leads
Section titled “Where this leads”This section leans backward on Stable numerics for log_softmax and the max shift behind every stable log-probability. Looking forward, Matrix differentials, the trace trick, and closed-form VJPs checks its cross-entropy VJP as the gradient of this cross_entropy. In AI Engineering, the training loss of Losses with a fused backward is , fused and stable; Sampling and logit processors logs entropy_from_logits per sampling step; Speculative decoding accepts with probability , a comparison JS and KL frame the same way; and GRPO with verifiable rewards applies the KL penalty to the reference model per token with kl_k3. Direct preference optimization and IPO and Distillation with forward and reverse KL write their objectives in terms of KL to a reference. Within this chapter, Perplexity, bits per byte, NLL accumulator turns the per-token cross-entropy into perplexity , and Mutual information, PMI, and PPMI defines mutual information as the KL from the joint to the product of marginals.
The production equivalents of these functions are worth reading once you know what to look for. scipy.stats.entropy (in scipy/stats/_entropy.py) adds a base argument and normalizes its inputs. torch.nn.functional.kl_div (in torch/nn/functional.py) takes as input and as target (note the order), with log_target and batch reductions. TRL’s GRPO trainer (trl/trainer/grpo_trainer.py) applies the per-token penalty against the reference model. scipy.spatial.distance.jensenshannon (in scipy/spatial/distance.py) returns the JS distance, the square root, with a base.
Further reading
Section titled “Further reading”- Cover and Thomas, Elements of Information Theory (2nd ed.), chapter 2.
- MacKay, Information Theory, Inference, and Learning Algorithms, chapters 2 and 4.
- Schulman, “Approximating KL Divergence” (2020 blog post).
Key terms
Section titled “Key terms”- Surprise: , the information carried by an outcome of probability .
- Entropy: , the average surprise of a distribution.
- Cross-entropy: , the average surprise when data from are predicted with .
- KL divergence: , the excess cost of predicting with ; nonnegative and asymmetric.
- Jensen-Shannon divergence: the average KL of and to their mixture; symmetric and bounded by .
- k3 estimator: with , an unbiased, nonnegative per-sample estimate of .
- Nat: the unit of information with natural logs; one bit is nats.
Summary
Section titled “Summary”- Entropy is the average surprise of a distribution, between 0 (certain) and (uniform).
- Cross-entropy splits as : the training loss is the data’s own entropy, which no model can beat, plus the model’s excess.
- with equality only at (Gibbs), and it is not symmetric; Jensen-Shannon is symmetric and bounded by .
- From model outputs, compute KL with log-probabilities, never with ; the k3 estimator estimates KL from samples without bias and is never negative.
- Apply the zero conventions exactly with
np.where; an epsilon biases every answer and hides true infinities.
Review questions
Section titled “Review questions”- Why does
kltesta == 0beforeb == 0, and what would the other order return for ?Answer
An outcome that never happens under $p$ costs nothing, whatever $q$ says, so $p_i = 0$ must win. With the order reversed, $p_i = q_i = 0$ would give $+\infty$, and any sparse distribution compared with itself would have infinite KL instead of 0. - In
kl_from_logprobs, why testnp.isneginf(lq)rather than relying onnp.exp(lp) * (lp - lq)being ?Answer
When `lp` is finite but very negative (say $-800$), `np.exp(lp)` underflows to exactly 0, and `0 * inf` is `nan`. Mathematically $p > 0$, so the term is $+\infty$; only a test on the logs themselves can see that. - Why is
kl_k3’s argument order (reference first) essential, given that for either sign of ?Answer
The estimator is unbiased only because $\mathbb{E}_{x \sim \pi}[e^{r}] = 1$, which needs $r = \log(\pi_{\mathrm{ref}}/\pi)$ with samples from $\pi$. With the ratio flipped, every value is still nonnegative, so nothing looks wrong, but the mean is no longer $\mathrm{KL}(\pi \,\Vert\, \pi_{\mathrm{ref}})$. - Why is
entropy_from_logitsnot justentropy(softmax(z))?Answer
The naive `-sum(p * log(p))` on `softmax(z)` gives `nan` as soon as one probability underflows to 0. Going through `log_softmax` gets $\ell_i = z_i - \mathrm{LSE}(z)$ directly, finite for every unmasked entry even at logits near $10^4$, instead of taking the log of an already-rounded probability; the only infinite entries are true masks, which the `where` sets to 0. - Why does
jsnever need the branch?Answer
KL is infinite only where the second argument is 0 and the first is not. The mixture $m_i = (p_i + q_i)/2$ is 0 only where both $p_i$ and $q_i$ are 0, and there the first argument is 0 too, so the term is 0. - What is the floor of the cross-entropy training loss, and why can no model go below it?
Answer
The floor is $H(p)$, the entropy of the data. Since $H(p, q) = H(p) + \mathrm{KL}(p \,\Vert\, q)$ and Gibbs' inequality gives $\mathrm{KL} \ge 0$ with equality only at $q = p$, the loss can reach $H(p)$ only when the model matches the data distribution exactly.