Chapter 0 · Section 0.5 · 65 min

Information theory, entropy, and cross-entropy

I am thinking of a number from 1 to 8, and you may ask yes-or-no questions. Halving the range each time ("is it 4 or less?"), you need exactly 3 questions, and 3=log⁡283 = \log_2 8. Now suppose you know I pick 1 half the time. Asking "is it 1?" first wins immediately half the time, and on average you need fewer questions. The more predictable the source, the fewer questions it takes.

That observation, made precise by Claude Shannon in 1948, is information theory. It is exactly the right language for machine learning. The cross-entropy loss that trains every classifier and every language model is an average number of questions. The KL divergence that keeps an RLHF policy close to its starting point is the extra questions you pay for using the wrong distribution. Perplexity, the headline number of language modeling, is the effective number of choices the model is torn between. This section builds all of them from one idea, surprise.

Surprise and entropy

How surprised should you be when an event of probability pp happens? Three properties pin down the answer. A certain event (p=1p = 1) should carry no surprise. Rarer events should be more surprising. And the surprises of two independent events should add, so that seeing two unrelated things together is exactly as surprising as seeing each in turn. The only functions with these properties are multiples of −log⁡p-\log p, so we define the surprise (or information content) of an outcome xx as

s(x)=−log⁡p(x)=log⁡1p(x).s(x) = -\log p(x) = \log\frac{1}{p(x)} .

With log⁡2\log_2 the unit is the bit, and with the natural log it is the nat (1 nat=1/ln⁡2≈1.4431 \text{ nat} = 1/\ln 2 \approx 1.443 bits). Machine learning code uses nats, since np.log is natural, while papers about compression and tokenizers often report bits.

The entropy of a distribution is its average surprise,

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

with the convention 0log⁡0=00 \log 0 = 0 (impossible outcomes contribute nothing). In plain words, entropy measures how unpredictable a source is, the average number of yes-or-no questions (in bits) needed to pin down one draw.

A few values to anchor intuition. A fair coin has H=1H = 1 bit. A coin that lands heads 90% of the time has H=−0.9log⁡20.9−0.1log⁡20.1=0.469H = -0.9\log_2 0.9 - 0.1\log_2 0.1 = 0.469 bits, less than half as unpredictable. A fair six-sided die has log⁡26=2.585\log_2 6 = 2.585 bits. And in general a uniform distribution over KK outcomes has H=log⁡KH = \log K, which is the largest entropy any distribution on KK outcomes can have (we prove it below). For continuous variables with a given mean and variance, the maximum-entropy distribution is the Gaussian, one reason it is the default assumption in §0.4.

Entropy is the best possible average code length

Shannon's source coding theorem makes the "questions" picture exact. Any lossless code for draws from pp needs at least H(p)H(p) bits per draw on average, and there are codes that come within 1 bit of it (within a vanishing fraction per symbol, if you encode long blocks). The ideal code gives outcome xx a codeword of length −log⁡2p(x)-\log_2 p(x), short codes for common outcomes.

Take four outcomes with probabilities 12,14,18,18\tfrac12, \tfrac14, \tfrac18, \tfrac18. Their surprises are 1, 2, 3, and 3 bits, and the prefix code 0, 10, 110, 111 uses exactly those lengths. The average length is 12⋅1+14⋅2+18⋅3+18⋅3=1.75\tfrac12 \cdot 1 + \tfrac14 \cdot 2 + \tfrac18 \cdot 3 + \tfrac18 \cdot 3 = 1.75 bits, which equals the entropy. A naive fixed-length code would use 2 bits for everything.

Python · cell 1

This link between probability and compression is not a curiosity. A language model is a compressor. Pair it with an arithmetic coder and it can encode text in about as many bits as its loss, which is why bits per byte (below) is a meaningful way to compare models.

Cross-entropy, the loss behind every classifier

Now suppose the data come from pp, but you build your code (or your predictions) from a different distribution qq. Each outcome xx costs you −log⁡q(x)-\log q(x), and the average cost is the cross-entropy

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

In plain words, cross-entropy is the average surprise of a model qq at data that actually come from pp. In the example above, using the fixed-length 2-bit code amounts to qq uniform, and H(p,q)=2H(p, q) = 2 bits, a quarter of a bit more than the 1.75 of the ideal code.

In classification the "data distribution" for one example is the one-hot target ey\mathbf{e}_y, so the cross-entropy collapses to −log⁡q(y)-\log q(y), the negative log-probability of the true class. That is the softmax cross-entropy loss of §0.2. A language model's loss is the same thing averaged over tokens,

L=−1T∑t=1Tlog⁡qθ(wt∣w<t),\mathcal{L} = -\frac{1}{T}\sum_{t=1}^{T}\log q_\theta(w_t \mid w_{<t}) ,

where wtw_t is the token at position tt and w<tw_{<t} are the tokens before it. This is a sample estimate of the cross-entropy between the true distribution of text and the model. When papers report a loss of 2.0 for a language model, they mean the model is, on average, 2.02.0 nats (2.92.9 bits) surprised by each token.

KL divergence, the price of the wrong model

How much worse than ideal is a model qq? Subtract the best possible cost, H(p)H(p), from what you actually pay, H(p,q)H(p, q). That difference is the Kullback-Leibler divergence,

DKL(p ∥ q)=H(p,q)−H(p)=∑xp(x)log⁡p(x)q(x)=Ex∼p ⁣[log⁡p(x)q(x)].D_{\mathrm{KL}}(p \,\Vert\, q) = H(p, q) - H(p) = \sum_x p(x)\log\frac{p(x)}{q(x)} = \mathbb{E}_{x\sim p}\!\left[\log\frac{p(x)}{q(x)}\right] .

In plain words, KL divergence is the extra surprise, per draw, that you suffer by believing qq when the truth is pp.

The most important fact about it is that it is never negative, and it is zero only when q=pq = p. This is Gibbs' inequality, and the proof takes one line. Using log⁡u≤u−1\log u \le u - 1 (the log lies below its tangent line at 1),

−DKL(p ∥ q)=∑xp(x)log⁡q(x)p(x)≤∑xp(x)(q(x)p(x)−1)=∑x: p(x)>0q(x)−1≤0,-D_{\mathrm{KL}}(p\,\Vert\,q) = \sum_x p(x)\log\frac{q(x)}{p(x)} \le \sum_x p(x)\left(\frac{q(x)}{p(x)} - 1\right) = \sum_{x:\,p(x) > 0} q(x) - 1 \le 0 ,

with equality exactly when q(x)=p(x)q(x) = p(x) everywhere. Two corollaries follow at once. Cross-entropy is never below entropy, H(p,q)≥H(p)H(p, q) \ge H(p), so a model's loss is bounded below by the entropy of the data. And with qq the uniform distribution U\mathcal{U} over KK outcomes, DKL(p∥U)=log⁡K−H(p)≥0D_{\mathrm{KL}}(p \Vert \mathcal{U}) = \log K - H(p) \ge 0, which proves that the uniform distribution has the most entropy.

Now the punchline for machine learning. When we train a model qθq_\theta by minimizing cross-entropy on data from pdatap_{\text{data}},

min⁡θH(pdata,qθ)=min⁡θ[H(pdata)+DKL(pdata ∥ qθ)],\min_\theta H(p_{\text{data}}, q_\theta) = \min_\theta \Big[ H(p_{\text{data}}) + D_{\mathrm{KL}}(p_{\text{data}} \,\Vert\, q_\theta) \Big] ,

the entropy term does not depend on θ\theta, so minimizing cross-entropy is minimizing DKL(pdata∥qθ)D_{\mathrm{KL}}(p_{\text{data}} \Vert q_\theta), the extra surprise the model suffers on real data, which is also maximum likelihood (§0.4). The leftover H(pdata)H(p_{\text{data}}) is a floor no model can beat, the inherent unpredictability of the data. The "irreducible loss" term in neural scaling laws (§9.3) is an estimate of it.

Play with two distributions below. Make qq put almost no mass where pp has some, and watch DKL(p∥q)D_{\mathrm{KL}}(p\Vert q) explode while DKL(q∥p)D_{\mathrm{KL}}(q\Vert p) stays moderate.

How do entropy, cross-entropy, and the two KL divergences respond to two distributions?
Set the weights of two distributions p (the truth) and q (the model) over four outcomes. All quantities are in bits. Weights are normalized for you.
Loading interactive figure…
Warm-up

Entropy, cross-entropy, and KL, with the edge cases right

Implement entropy(p, base=np.e), cross_entropy(p, q, base=np.e), and kl(p, q, base=np.e) for discrete distributions given as 1-D arrays. Treat 0log⁡00 \log 0 as 0. Where p(x)>0p(x) > 0 but q(x)=0q(x) = 0, cross-entropy and KL are inf. Return plain floats, with no NaN and no warnings.

Hidden tests, hints, and AI help, from $1.99 a month.

Forward and reverse KL

KL divergence is not symmetric, and the direction you choose changes what you get. This is one of the most important practical ideas in this section, so let's go slowly.

Suppose the truth pp is complicated (here, two separated bumps) and you must approximate it with something simple, a single Gaussian qq. Which Gaussian is "closest" depends on which KL you minimize.

Forward KL, DKL(p∥q)=Ep[log⁡p−log⁡q]D_{\mathrm{KL}}(p \Vert q) = \mathbb{E}_p[\log p - \log q], averages over where pp has mass. If qq is tiny where pp has mass, log⁡q\log q is hugely negative there and the penalty is enormous, infinite if q=0q = 0. So the best qq covers every region of pp, even if that means putting mass in the gap between the bumps. It is called mass-covering or mean-seeking. For a Gaussian qq the answer is exact. Since DKL(p∥q)=−Ep[log⁡q]+constD_{\mathrm{KL}}(p\Vert q) = -\mathbb{E}_p[\log q] + \text{const}, and −Ep[log⁡N(x;μ,σ2)]=Ep[(x−μ)2]2σ2+12log⁡(2πσ2)-\mathbb{E}_p[\log\mathcal{N}(x;\mu,\sigma^2)] = \frac{\mathbb{E}_p[(x-\mu)^2]}{2\sigma^2} + \tfrac12\log(2\pi\sigma^2), setting derivatives to zero gives μ=Ep[x]\mu = \mathbb{E}_p[x] and σ2=Var⁡p(x)\sigma^2 = \operatorname{Var}_p(x). Forward KL matches the moments, and with two bumps the mean sits in the valley between them.

Reverse KL, DKL(q∥p)=Eq[log⁡q−log⁡p]D_{\mathrm{KL}}(q \Vert p) = \mathbb{E}_q[\log q - \log p], averages over where qq has mass. Now the big penalty is for qq putting mass where pp is tiny, and there is no penalty for ignoring parts of pp, since regions where q≈0q \approx 0 contribute nothing to the average. So the best qq squeezes into one bump and fits it well. It is called mode-seeking or zero-forcing.

What does a single Gaussian look like when it is fitted by forward KL, and by reverse KL?
The shaded curve is a two-bump target p. The line is the Gaussian q that minimizes the chosen divergence, found numerically. Move the bumps apart and compare.
Loading interactive figure…
Python · cell 2

The forward fit is centered at 0 with a standard deviation of about 2.1, matching the mixture's moments and putting a large share of its mass, its peak included, in the valley where pp has almost none. The reverse fit locks onto one bump (the grid happens to pick the right-hand bump at +2+2, and the left-hand one ties by symmetry) with exactly that bump's width. Its divergence is log⁡2\log 2, because inside its bump q=2pq = 2p, so log⁡(q/p)=log⁡2\log(q/p) = \log 2 everywhere qq has mass.

These two behaviors show up across the book.

forward DKL(p∥q)D_{\mathrm{KL}}(p\Vert q)reverse DKL(q∥p)D_{\mathrm{KL}}(q \Vert p)
averages overthe target ppthe model qq
behaviorcovers all modes, may blurpicks modes, may drop some
needssamples from ppsamples from qq and the value of pp
where you meet itmaximum likelihood, pretraining, distillation from a teachervariational inference, the KL penalty in RLHF and GRPO

The last row is worth spelling out. Pretraining minimizes the forward KL DKL(pdata∥qθ)D_{\mathrm{KL}}(p_{\text{data}} \Vert q_\theta), because we have samples of text but no formula for its probability. RLHF penalizes the reverse KL DKL(πθ∥πref)D_{\mathrm{KL}}(\pi_\theta \Vert \pi_{\text{ref}}) between the policy being trained and the reference model it started from (§16.4), because the samples come from the policy and both log-probabilities are available. That choice is also what gives the best policy its explicit form, the reference tilted by er/βe^{r/\beta}, on which DPO is built (§17.1). The mode-seeking nature of reverse KL is one commonly offered explanation for why RLHF-tuned models produce less diverse outputs than their base models.

Estimating KL from samples

In RLHF and GRPO you cannot sum over every possible sequence. You estimate DKL(q∥p)D_{\mathrm{KL}}(q \Vert p) from samples x∼qx \sim q, using the ratio r(x)=p(x)/q(x)r(x) = p(x)/q(x). The obvious estimator is k1=−log⁡rk_1 = -\log r, which is unbiased (its mean is exactly the KL) but very noisy, and it is negative for many samples even though KL never is. John Schulman's note on the topic (linked below) popularized a better one,

k3=(r−1)−log⁡r.k_3 = (r - 1) - \log r .

It is unbiased, because Eq[r]=∑xq(x)p(x)q(x)=1\mathbb{E}_q[r] = \sum_x q(x)\frac{p(x)}{q(x)} = 1, so the (r−1)(r - 1) term has mean zero and Eq[k3]=Eq[−log⁡r]=DKL(q∥p)\mathbb{E}_q[k_3] = \mathbb{E}_q[-\log r] = D_{\mathrm{KL}}(q\Vert p). It is never negative, because log⁡r≤r−1\log r \le r - 1. And when pp and qq are close it has much lower variance, because the added r−1r - 1 term is negatively correlated with −log⁡r-\log r and cancels much of its noise. A third choice, k2=12(log⁡r)2k_2 = \tfrac12(\log r)^2, has low variance but is biased. GRPO's KL penalty (§18.4) is exactly k3k_3 with q=πθq = \pi_\theta and p=πrefp = \pi_{\text{ref}}. (It is unbiased only when the samples really come from πθ\pi_\theta. GRPO samples from a slightly older copy of the policy, so in practice it is a close approximation.)

Interview

Three Monte Carlo estimators of KL

Given log-probabilities of samples drawn from qq, logq and logp (arrays of shape (n,), where logp[i] =log⁡p(xi)= \log p(x_i) and logq[i] =log⁡q(xi)= \log q(x_i) for xi∼qx_i \sim q), implement kl_estimators(logq, logp) returning a dict with keys "k1", "k2", "k3", each the per-sample array of that estimator (not its mean), estimating DKL(q∥p)D_{\mathrm{KL}}(q \Vert p). Work from the log-ratio, never from probabilities, because sequence probabilities underflow.

Hidden tests, hints, and AI help, from $1.99 a month.

Mutual information

How much does knowing one variable tell you about another? Start with conditional entropy, the uncertainty left in XX once you know YY,

H(X∣Y)=∑yp(y) H(X∣Y=y)=−∑x,yp(x,y)log⁡p(x∣y).H(X \mid Y) = \sum_y p(y)\, H(X \mid Y = y) = -\sum_{x, y} p(x, y)\log p(x \mid y) .

The mutual information is how much knowing YY reduces the uncertainty about XX,

I(X;Y)=H(X)−H(X∣Y)=∑x,yp(x,y)log⁡p(x,y)p(x) p(y)=DKL(p(x,y) ∥ p(x) p(y)).I(X; Y) = H(X) - H(X \mid Y) = \sum_{x, y} p(x, y)\log\frac{p(x, y)}{p(x)\,p(y)} = D_{\mathrm{KL}}\big(p(x, y) \,\Vert\, p(x)\,p(y)\big) .

In plain words, mutual information is how far the joint distribution is from what it would be if the variables were independent. It is symmetric, never negative, and zero exactly when XX and YY are independent.

Notice the term inside the sum. log⁡p(x,y)p(x)p(y)\log\frac{p(x,y)}{p(x)p(y)} is the pointwise mutual information (PMI), how much more often xx and yy occur together than independence predicts, so mutual information is the average PMI over the joint distribution. PMI between words and their contexts is what classical word vectors are built from (§1.4). A small example makes it concrete. Take the rain and wet-grass table of §0.4, with XX whether it rained and YY whether the grass is wet, and joint probabilities p(rain,wet)=0.3p(\text{rain}, \text{wet}) = 0.3, p(rain,dry)=0.02p(\text{rain}, \text{dry}) = 0.02, p(none,wet)=0.08p(\text{none}, \text{wet}) = 0.08, and p(none,dry)=0.6p(\text{none}, \text{dry}) = 0.6. Rain has entropy H(X)=0.904H(X) = 0.904 bits. Looking at the grass removes more than half of it, I(X;Y)=0.495I(X; Y) = 0.495 bits, leaving H(X∣Y)=0.41H(X \mid Y) = 0.41 bits.

Python · cell 3

Mutual information is the quantity contrastive learning secretly maximizes. The InfoNCE loss used to train CLIP and modern embedding models satisfies I(X;Y)≥log⁡N−LInfoNCEI(X; Y) \ge \log N - \mathcal{L}_{\text{InfoNCE}} for a batch of NN candidates (van den Oord et al., 2018), so driving the loss down pushes up a lower bound on the information shared by the two views. You'll derive this in §7.2.

Core

Mutual information from a joint table

Implement mutual_information(P, base=2) for a joint distribution table P of shape (m, n) (nonnegative, summing to 1). Cells with probability 0 contribute 0. Also implement conditional_entropy(P, base=2) returning H(X∣Y)H(X \mid Y), where rows index XX and columns index YY.

Hidden tests, hints, and AI help, from $1.99 a month.

Perplexity, and bits per byte

A language model's loss is an average cross-entropy in nats per token, which is hard to feel. Perplexity turns it into a count,

PPL⁡=exp⁡ ⁣(−1T∑t=1Tlog⁡qθ(wt∣w<t))=eL=(∏t=1Tqθ(wt∣w<t))−1/T.\operatorname{PPL} = \exp\!\Big(-\frac1T\sum_{t=1}^T \log q_\theta(w_t\mid w_{<t})\Big) = e^{\mathcal{L}} = \Big(\prod_{t=1}^{T} q_\theta(w_t \mid w_{<t})\Big)^{-1/T} .

In plain words, perplexity is one over the geometric mean of the probabilities the model gave to the tokens that actually occurred, which makes it the number of equally likely choices that would leave you as uncertain as the model is, on average. That is why it is often called the effective branching factor.

Work one by hand. A model assigns probabilities 0.5, 0.1, 0.9, and 0.25 to the four tokens of a short text. Their logs are −0.693-0.693, −2.303-2.303, −0.105-0.105, and −1.386-1.386, so the mean loss is 4.487/4=1.1224.487/4 = 1.122 nats per token, and the perplexity is e1.122=3.07e^{1.122} = 3.07. The geometric mean probability is 1/3.07=0.3261/3.07 = 0.326. Notice what perplexity is not. The average of the inverse probabilities, (2+10+1.11+4)/4=4.28(2 + 10 + 1.11 + 4)/4 = 4.28, is a different and meaningless number, and so is the average of per-token perplexities.

Three anchor values follow from the definition.

  1. A uniform model has perplexity VV. If q=1/Vq = 1/V for every token, L=log⁡V\mathcal{L} = \log V and PPL⁡=V\operatorname{PPL} = V. This is also where a freshly initialized model starts, so a GPT-2 model with its vocabulary of 50,257 tokens should begin training near a loss of ln⁡50,257=10.82\ln 50{,}257 = 10.82 nats. Checking that number is the first step of the debugging recipe in §0.7.
  2. A perfect model has perplexity 1. It puts probability 1 on every token that occurs. No real model gets there, because text has entropy of its own, the floor H(pdata)H(p_{\text{data}}) from the KL section above.
  3. One zero sends perplexity to infinity. If any q(wt∣w<t)=0q(w_t \mid w_{<t}) = 0, then log⁡0=−∞\log 0 = -\infty and PPL⁡=∞\operatorname{PPL} = \infty. Short of zero, one confident mistake still costs a lot. A token given probability 10−910^{-9} adds 20.720.7 nats to the total, as much as 20 ordinary tokens at a loss near 1. Perplexity punishes overconfidence far more than it rewards confidence, which is the cross-entropy's character showing through.

The same quantity has three common units, and you should convert between them without thinking. The loss L\mathcal{L} is in nats per token. Dividing by ln⁡2\ln 2 gives bits per token. And perplexity is both eLe^{\mathcal{L}} and 2 raised to the bits per token. A loss of 2.0 nats per token is 2.0/ln⁡2=2.892.0/\ln 2 = 2.89 bits per token and a perplexity of e2=22.89≈7.4e^2 = 2^{2.89} \approx 7.4, as unsure as choosing among 7 or 8 equally likely tokens at every step.

At real scale, the OpenAI GPT-2 checkpoints, evaluated on the OpenWebText validation set, reach a loss of 3.12 nats per token for the 124M-parameter model and 2.54 for the 1.5B-parameter one (Karpathy's nanoGPT reports these baselines). Those are perplexities of e3.12≈22.6e^{3.12} \approx 22.6 and e2.54≈12.7e^{2.54} \approx 12.7. Going from 10.82 at initialization to 3.12 shrinks the effective number of choices per token from 50,257 to about 23.

Computing it over a corpus

Perplexity is a statement about a whole evaluation set, and the most common mistakes are in how the per-token numbers are combined.

  • Pool the tokens, then exponentiate. The perplexity of a corpus is exp⁡(total nats/total counted tokens)\exp(\text{total nats} / \text{total counted tokens}). Averaging per-document perplexities gives too much weight to short documents, and even with equal-length documents it comes out too large, because exe^x is convex, so the average of the exponentials exceeds the exponential of the average whenever the documents' losses differ (Jensen's inequality). Averaging per-batch mean losses is wrong for the same reason whenever batches hold different numbers of counted tokens, the bug that gradient accumulation also has to avoid (§0.9).
  • Count only real predictions. Padding positions, and the first token of a sequence (which nothing predicts), must be excluded from both the total loss and the token count. Whether the end-of-sequence token counts is a convention that has to be stated, because it changes the number (§3.1).
  • Context changes the number. The same model scores lower perplexity when each token sees more context. Cutting a long text into non-overlapping chunks leaves the first tokens of every chunk with almost no context and inflates perplexity. Evaluating with an overlapping sliding window fixes this at extra cost (§6.6 builds it).

Comparing across tokenizers with bits per byte

Perplexity per token depends on the tokenizer. A tokenizer with longer tokens has fewer, harder predictions per document, so two models with different tokenizers cannot be compared by per-token loss (§2.1). What does not depend on the tokenizer is the total probability the model assigns to the text, so the fix is to normalize the total by something every tokenizer shares, the raw bytes of text. If a document of NbytesN_{\text{bytes}} bytes is split into TT tokens and the model's total loss is T⋅LT \cdot \mathcal{L} nats, then

bits per byte=T⋅LNbytes⋅ln⁡2.\text{bits per byte} = \frac{T \cdot \mathcal{L}}{N_{\text{bytes}} \cdot \ln 2} .

In plain words, convert the document's total surprise to bits and divide by its length in bytes. For example, a loss of 2.0 nats per token with an average of 4 bytes per token is 2.0/(4ln⁡2)=0.722.0 / (4 \ln 2) = 0.72 bits per byte. Bits per byte is also directly a compression rate. A model at 0.72 bits per byte, driving an arithmetic coder, would compress text to 9% of its original size (0.72 out of 8 bits). For GPT-2 small, using the common rule of thumb of about 4 bytes of English per token, 3.12 nats per token is 4.504.50 bits per token and about 1.11.1 bits per byte. Bytes are not characters. Most non-English scripts take 2 to 4 bytes per character in UTF-8, so bits per character and bits per byte differ there, and papers should say which they report. You'll use these conversions in §6.6.

Warm-up

Perplexity and bits per byte from token log-probabilities

Implement perplexity(token_logprobs) for an array of natural-log probabilities the model assigned to each actual token, and bits_per_byte(token_logprobs, n_bytes) for a text of n_bytes bytes.

Hidden tests, hints, and AI help, from $1.99 a month.
Interview

Corpus perplexity from a padded batch

An evaluation harness hands you logprobs, an array of shape (B, T) holding the natural-log probability the model gave to each target token, and a boolean mask of the same shape that is True on the positions that count. Padding positions hold garbage, which may include -inf or NaN. Implement corpus_perplexity(logprobs, mask) returning the perplexity of all counted tokens pooled together, and doc_perplexities(logprobs, mask) returning the perplexity of each row, shape (B,). Every row has at least one counted token. No loops, and no floating-point warnings.

Hidden tests, hints, and AI help, from $1.99 a month.

Label smoothing

Cross-entropy with one-hot targets has a strange optimum. Once a training example is classified correctly, the loss −log⁡py-\log p_y keeps decreasing as py→1p_y \to 1, which requires the logit gap between the true class and the others to grow without bound. On data the model can fit perfectly, the logits drift toward infinity, and the model becomes overconfident.

Label smoothing (Szegedy et al., 2016) replaces the one-hot target with a softened one. With smoothing ϵ\epsilon and KK classes,

yLS=(1−ϵ) ey+ϵK1,LLS=H(yLS,p)=(1−ϵ)(−log⁡py)+ϵ⋅1K∑k(−log⁡pk).\mathbf{y}^{\text{LS}} = (1 - \epsilon)\,\mathbf{e}_y + \frac{\epsilon}{K}\mathbf{1}, \qquad \mathcal{L}_{\text{LS}} = H(\mathbf{y}^{\text{LS}}, \mathbf{p}) = (1-\epsilon)\big(-\log p_y\big) + \epsilon\cdot\frac1K\sum_{k}\big(-\log p_k\big) .

In plain words, mix a little of the uniform distribution into every target, which adds a penalty for putting very low probability on any class.

Three consequences follow from what we already know. The gradient is still "predicted minus target", p−yLS\mathbf{p} - \mathbf{y}^{\text{LS}} (the derivation in §0.2 holds for any target distribution). The loss is minimized when p=yLS\mathbf{p} = \mathbf{y}^{\text{LS}}, by Gibbs' inequality, so the optimal logit gap between the true class and any other is finite, log⁡1−ϵ+ϵ/Kϵ/K\log\frac{1 - \epsilon + \epsilon/K}{\epsilon/K}, which is about 9.1 for K=1000K = 1000 and ϵ=0.1\epsilon = 0.1. And the minimum loss is no longer 0 but the entropy H(yLS)H(\mathbf{y}^{\text{LS}}), so do not be alarmed when a smoothed model's training loss plateaus above zero.

Python · cell 4

Without smoothing the gap keeps growing, roughly logarithmically in the number of steps, forever. With smoothing it settles quickly at the predicted value, log⁡91≈4.51\log 91 \approx 4.51 for these 10 classes. Label smoothing became standard in image classification and machine translation, and the original Transformer used ϵ=0.1\epsilon = 0.1. It has a known cost. Müller, Kornblith & Hinton (2019) showed that it tends to erase the information in a network's logits about which wrong classes are similar to the right one, which makes smoothed networks worse teachers for knowledge distillation. Most large language model pretraining does not use it.

Core

Label-smoothed cross-entropy, forward and backward

Implement smoothed_cross_entropy(logits, y, eps) for logits of shape (N, K) and integer labels y of shape (N,), returning (mean loss, dlogits), where dlogits is the gradient of the mean loss (so it includes the factor 1/N1/N), with the smoothed target (1−ϵ)ey+ϵK1(1 - \epsilon)\mathbf{e}_y + \frac{\epsilon}{K}\mathbf{1}. It must be numerically stable. With eps=0 it must reduce to ordinary cross-entropy.

Hidden tests, hints, and AI help, from $1.99 a month.

In PyTorch

🔥 In PyTorchfor a machine with PyTorch

Read more

Watch next

🎬 A Short Introduction to Entropy, Cross-Entropy and KL-Divergence · Aurélien GéronTen clear minutes on the three quantities, framed as code lengths.
🎬 The Key Equation Behind Probability · Artem KirsanovSurprise, entropy, cross-entropy, and KL built from one idea, beautifully animated.
🎬 Solving Wordle using information theory · 3Blue1BrownEntropy as expected information, applied to a game you know.