Key takeaways
- Surprise is −logp; entropy is the average surprise, a measure of how uncertain a distribution itself is.
- Cross-entropy: reality follows p, but surprise is measured with q. It equals entropy plus the KL divergence, CE(p,q)=H(p)+KL(p∥q), so minimizing cross-entropy pulls q toward p.
- In training the target is one-hot, so the loss is the negative log probability of the correct token; right after initialization it's about log(vocabulary size). In code, shift by one position and use a loss mask so only the right positions count, dividing by the sum of the mask.
- The heart of numerical stability is subtracting the maximum. Stable softmax, log-softmax and logsumexp all come from it. Never take softmax first and then the log.
- Preview: online softmax gets it done in a single pass, and it's the heart of FlashAttention.
That number in the training log
Train a language model and your screen fills with lines like these:
step 0 loss 10.83
step 200 loss 6.52
step 2000 loss 4.37
step 20000 loss 3.00
The loss starts around 10.8 and keeps falling. But what is this number measuring, and what does it mean once it reaches 3? There's an odd coincidence too: for a model with a vocabulary of about 50 thousand tokens, the loss at the very start of training is almost always near 10.8. Why that number? And a scarier scene: get the arithmetic slightly wrong (say, by switching to half precision to save GPU memory) and the loss can suddenly become nan, "not a number". Training has crashed.
This episode answers in two halves. The first is information theory: surprise, entropy, cross-entropy and KL divergence. All of them answer one question: "if we use one distribution to describe or predict another, how much does it cost us in surprise?" Training a language model means minimizing that surprise. The second half is numerical stability: numbers in a computer are finite, so how do we compute softmax and logs without overflowing or crashing?
Surprise: how much information is in a message?
Imagine you live in a desert town where the forecast says "sunny tomorrow" almost every day (a 99% chance of sun). Then one day it says "snow tomorrow". Which message surprises you more? The snow, of course. The rarer the event, the more surprised we are, and the more information it carries.
We want a number I that measures surprise, depends only on the probability, and meets three requirements:
- Something certain (probability 1) carries no surprise: I=0.
- The smaller the probability, the bigger the surprise.
- When two unrelated events both happen, their probabilities multiply, P(A,B)=pA⋅pB, but their surprises should add, I(A,B)=I(A)+I(B).
Which function turns multiplication into addition? The logarithm: log(a⋅b)=loga+logb. So we define surprise as
I(x)=−logp(x)
The minus sign is there because a probability is at most 1, so its log is zero or negative; flipping the sign makes surprise positive. Check: at p=1, log1=0; as p shrinks, −logp grows; and for independent events, −log(pApB)=−logpA−logpB splits into two terms that add. All three requirements are met.
Any base works for the log; different bases differ only by a constant factor.
- With base 2 the unit is the bit. Heads on a fair coin has p=21, exactly 1 bit of surprise. Three heads in a row has p=81=21⋅21⋅21, so 3 bits =1+1+1.
- Back in the desert: "sunny" carries only about 0.01 bits, almost no information. "Snow" carries 6.6 bits.
- With base e (the natural log) the unit is the nat; 1 nat is about 1.44 bits. In machine learning code,
log means the natural log by default.
Entropy: how surprised are we, on average?
Surprise describes a single outcome. A distribution has many outcomes, so how surprising is it on average? Weight each outcome's surprise by its probability and add them up. That average is entropy:
H(p)=x∑p(x)⋅(−logp(x))=−x∈X∑p(x)logp(x)
Three coins:
- Fair coin: heads and tails each half the time, each 1 bit of surprise, so entropy is 1 bit.
- Rigged coin, 90% heads: heads carries 0.15 bits, tails 3.32 bits but rarely happens. Entropy =0.9×0.15+0.1×3.32≈0.47 bits, less than the fair coin because it's easier to predict.
- Two-headed coin: the outcome is certain, so entropy is 0.
Slide the probability of heads from 0 to 1 and the entropy is 0 at both ends (the outcome is certain) and peaks at 1 bit in the middle, at fifty-fifty. The more even the odds, the harder to guess, and the higher the entropy.
In general, N equally likely outcomes have entropy H=log2N. Four equally likely outcomes, for instance, have 2 bits.
Intuition: Picture 2 bits as two yes-or-no questions: to pin down the answer, the first question rules out half, and the second rules out half of what's left.
Back to language models. After "Once upon a", the next word is almost certainly "time": a sharp distribution, low entropy. After "My favorite fruit is", lots of answers are possible: a flat distribution, high entropy. Entropy measures how uncertain a distribution itself is.
Cross-entropy: guessing one distribution with another
In one city the weather truly works like this, call it p: sunny half the time, cloudy a quarter, rainy a quarter. If you knew this pattern perfectly, your average surprise would be the entropy of p: 1.5 bits.
But a forecaster doesn't know the true pattern. The distribution in his head, q, says sun only a quarter of the time and rain half the time:
| Weather |
true p |
his q |
−log2q |
| sunny |
0.5 |
0.25 |
2 |
| cloudy |
0.25 |
0.25 |
2 |
| rainy |
0.25 |
0.5 |
1 |
The weather still arrives according to p, but his surprise is computed from q. Weighting by how often each really happens: 0.5×2+0.25×2+0.25×1=1.75 bits. That's cross-entropy, the average cost of predicting with a model distribution q when the truth is p:
CE(p,q)=−Ep[logq]=−x∑p(x)logq(x)
Watch out: Don't swap the two. p sits outside as the weights: it decides what happens often. q sits inside the log: it stands for your beliefs.
1.75 is bigger than 1.5, and that's no coincidence: whenever q differs from the true p, the average surprise is larger. Someone totally clueless who guesses one third for each kind of weather gets 1.58 bits, in between. Only when q=p does cross-entropy hit its minimum, which is exactly the entropy.
KL divergence: the extra surprise you pay
The extra 0.25 bits of cross-entropy over entropy is purely the price of using the wrong distribution. It has its own name, the KL divergence:
KL(p∥q)=x∑p(x)(logp(x)−logq(x))
The bracket is how much more surprised you feel than you should be, weighted by p. Split it into two sums:
KL(p∥q)=x∑p(x)logp(x)−x∑p(x)logq(x)=−H(p)+CE(p,q)
Rearrange and you get the key relationship:
CE(p,q)=H(p)+KL(p∥q)
The total cost of describing p with q is the irreducible uncertainty of p itself (entropy) plus the gap between the two distributions (KL).
Intuition: The entropy H(p) is fixed by the data; nothing you do to the model changes it (it's a constant). So minimizing cross-entropy is the same as minimizing KL divergence: either way you pull the model's q toward the true p. It also means the loss can never reach zero. Training can only squeeze out the KL part; the randomness built into language, its entropy, is a floor under the loss.
Two more properties of KL divergence:
- It's always ≥0, and equals 0 only when q=p.
- It isn't symmetric. If the true coin is fifty-fifty but the model thinks ninety-ten, the KL is 0.74 bits; swap the two and it's 0.53 bits. That's why it's called a divergence, not a distance. In episode 19 on RLHF, KL divergence comes back as a penalty term.
Cross-entropy loss: what training actually computes
Back to language models. In training, at each position we only know the one token that actually came next in the corpus. So the "true distribution" puts probability 1 on the correct token and 0 on everything else. A distribution with a single 1 like this is called one-hot. Say the context is "The cat sat" and the corpus continues with "on":
| Candidate |
target y |
model q |
| on |
1 |
0.62 |
| down |
0 |
0.14 |
| there |
0 |
0.08 |
| by |
0 |
0.05 |
| in |
0 |
0.03 |
| all the rest |
0 |
0.08 |
Plug into cross-entropy (from here on, natural log). Every term with y=0 vanishes, leaving only the correct answer:
L=−x∑y(x)lnq(x)=−lnq(on)=−ln0.62≈0.48
That's the loss from episode 0: the negative log of the correct answer's probability, the negative log-likelihood. And since a one-hot distribution has zero entropy, cross-entropy and KL divergence are exactly equal here.
Intuition: If every target is one-hot, how does the model learn a whole distribution? Because the same context shows up many times in the corpus, followed by different words. Say "The weather is so" appears 5 times: 3 times followed by "nice", once by "good", once by "cold". Each is a one-hot target, but averaged together they give the true distribution 53,51,51. So the loss averaged over the corpus is CE(pdata,q), and it's smallest exactly when q equals the data distribution.
For a whole piece of text, add up the loss at every position:
L(x)=−t=1∑Tlogp(xt∣x<t)
That's the negative log-likelihood. In practice we usually divide by the number of tokens to get an average, so the loss doesn't depend on how long the text is.
Now we can answer the opening question. A freshly initialized model knows nothing, so it treats all 50,257 tokens roughly alike, giving each a probability of about one in 50 thousand. Its loss is ln50257≈10.82: the number at the top of the training log.
Turn it around: e to the loss is called perplexity, perplexity=eL. It's as if the model were hesitating evenly among that many words: eln50257=50257, and when the loss drops to 3, e3≈20, a perplexity of about 20.
Implementation: shifting and the loss mask
Text is split into tokens and fed to the model all at once, and every position outputs a distribution over the next token. The key is alignment: the output at position 1 predicts token 2, position 2 predicts token 3, and so on. Feed in "I love eating water melon", and the first four outputs should predict "love", "eating", "water", "melon". The last position's output has no answer after it, so it goes unused, and nothing predicts the first token. So in code we shift by one:
shift_logits = logits[:, :-1, :] # drop the last position
shift_labels = input_ids[:, 1:] # drop the first token
Watch out: A common trap: some libraries do this shift for you internally. Hugging Face language models, for example, shift automatically when you pass in labels. Shift again yourself and the model learns to predict the token two steps ahead. The loss still goes down, but it's quietly learning the wrong thing.
The second detail is the loss mask. Sentences in a batch differ in length, so short ones get filled out with padding tokens (like "Hi there <pad> <pad> <pad>"). Those positions aren't real text and shouldn't count. Likewise, in post-training we often want the model to learn only from the assistant's answers, not the user's questions. The recipe: give every position a mask value mt of 0 or 1:
L=∑tmt∑tℓtmt
If the three unmasked positions have losses 0.8, 2.0 and 0.4, then L=30.8+2.0+0.4≈1.07.
Watch out: The denominator is the sum of the mask, not the total length. Otherwise, the more padding you add, the more the loss gets watered down.
In code: shift, take log probabilities, pick out the correct token's term, multiply by the mask, and average.
shift_logits = logits[:, :-1, :]
shift_labels = input_ids[:, 1:]
logprobs = F.log_softmax(shift_logits, dim=-1)
token_logprobs = logprobs.gather(index=shift_labels.unsqueeze(-1), dim=-1).squeeze(-1)
masked_logprobs = -token_logprobs * mask.float()
return masked_logprobs.sum() / mask.sum()
(Here mask is aligned with shift_labels.) Notice the middle uses log_softmax rather than softmax followed by log. Why? That's the second half of the episode.
Numbers in a computer are finite
In math a number can be as big as you like, but a floating-point number has a fixed number of bits, so its range is limited.
- The everyday float32 tops out at about 3.4×1038. And ex grows ridiculously fast: at x=88 it still just fits, but at x=89 it becomes infinity. That's overflow.
- The other way, once x drops below about −103, ex is too small to represent and becomes 0. That's underflow.
- Half-precision float16 is narrower still: its maximum is only 65,504, so ex overflows once x>11. And model scores above 11 are nothing unusual.
So there are three kinds of trap:
- ex overflows to ∞ when x is large;
- logx heads to −∞ as x approaches 0, and if x has already underflowed to 0, log0=−∞;
- logx loses precision when x is near 1: in float32, 1+10−8 is exactly 1, so its log is 0 and the 10−8 is simply gone.
A concrete example: logits [90, 88, 87.2], softmax computed directly. e90 overflows to ∞, so the denominator is ∞ too. ∞∞ gives NaN, and the other two, ∞finite, become 0. The result is [NaN, 0, 0].
Watch out: NaN is contagious: NaN+1=NaN and NaN×0=NaN. Once one NaN sneaks in, every parameter in the model soon becomes NaN.
Stable softmax: subtract the maximum
The key observation: softmax only cares about the gaps between scores, not their overall size. Proof: subtract a constant c in every exponent and multiply by ec to compensate, which changes nothing; every denominator term carries the same ec, so pull it out and cancel it with the numerator:
softmax(x)i=∑jexjexi=ec⋅∑jexj−cexi−c⋅ec=∑jexj−cexi−c=softmax(x−c)i
Any c works, but the best choice is the maximum, xmax:
softmax(x)i=∑jexj−xmaxexi−xmax
Now the largest term is e0=1, so nothing overflows; and since at least one denominator term is 1, the denominator is ≥1, so there's no dividing by zero either.
Back to the example: subtract 90 from [90, 88, 87.2]:
| x |
x−90 |
ex−90 |
softmax |
| 90 |
0 |
1 |
0.836 |
| 88 |
−2 |
0.135 |
0.113 |
| 87.2 |
−2.8 |
0.061 |
0.051 |
The exponentials sum to 1.196: perfectly ordinary numbers, no overflow anywhere. The result is exactly softmax(3, 1, 0.2), because the gaps are identical. Every deep learning framework does exactly this inside its softmax.
log-softmax and logsumexp
Softmax is stable now, but the loss wants the log of the probabilities. The direct approach is softmax first, then log. Take logits [0, −120] where the correct answer is the second one: the model is badly wrong.
softmax(x)≈[1, 7.7×10−53] float32 [1, 0]
The second probability is below the smallest positive number float32 can represent, so it becomes 0. Taking the log gives log0=−∞, so the loss is infinite and the gradient turns into NaN. Yet the true loss is finite, about 120. The problem is that we actually computed that tiny probability (taking the log of a low-probability class is unstable).
The fix is to simplify on paper first:
log(softmax(x))i=log∑jexjexi=logexi−logj∑exj=xi−logj∑exj
That last term, "exponentiate, sum, then log", is called logsumexp, or LSE. So log-softmax is just xi−LSE(x), and we never compute the tiny probability at all.
But logsumexp has its own risk: ex can overflow. Same trick: subtract the maximum m=xmax and add it back:
logi∑exi=logi∑(exi−m⋅em)=log(emi∑exi−m)=logem+logi∑exi−m=m+logi∑exi−m
Why is this safe? The largest term in the sum is e0=1, so nothing overflows, and the sum is at least 1, so we never take log0.
Plug in the example:
LSE(0,−120)=0+log(1+e−120)≈0
The second token's log probability is logp2=−120−0=−120, so the loss is 120, matching the true answer.
Computing the loss straight from logits
So the cross-entropy loss for one token (with y the correct token) can be written directly as
−logsoftmax(x)y=LSE(x)−xy
without ever computing the probabilities. That's why PyTorch's cross_entropy wants the raw logits, not probabilities: internally it fuses the two steps and computes them stably.
loss = F.cross_entropy(logits, labels) # pass raw logits, not probabilities
Entropy can come straight from the logits too: replace logpi with xi−LSE(x) and use ∑ipi=1:
H=−i∑pilogpi=−i∑pi(xi−LSE(x))=LSE(x)−i∑pixi
Entropy is logsumexp minus the probability-weighted average of x (that average is ∑ipixi=∑iexi∑iexixi, the expected value E[x]).
Intuition: The general trick: whenever an expression with ex needs to be numerically stable, multiply by e−m (usually m=xmax) and see what survives. Nearly every technique here is this one move: subtract a big constant, then add it back at the end.
Preview: online softmax in a single pass
Stable softmax passes over the data twice: once to find the maximum, then again for the denominator. In attention, the list can be too long to hold all at once. Can we do it in one pass, computing as we read?
We can, with the online softmax trick. As we read, keep two numbers: the largest value so far, m, and the denominator d, measured relative to m. Read 2, 5, 3:
- Read 2: m=2, d=e0=1.
- Read 5: the maximum jumps to 5. The old d was measured relative to 2, so rescale it by e2−5 and add the new term: d=1⋅e−3+e0≈1.050.
- Read 3: the maximum is unchanged, so the rescaling factor is 1; just add e3−5: d≈1.050+0.135=1.185.
Check: e−3+1+e−2≈1.185. One pass, exactly right. As formulas:
mk+1=max(mk,xk+1),dk+1=dkemk−mk+1+exk+1−mk+1
When the maximum doesn't change, mk=mk+1 and the rescaling factor emk−mk+1=1. If you need the softmax itself at the end, one more pass returns exi−mN/dN.
Why is the update for d correct? (optional derivation)
Let mk=max(x1,…,xk) and dk=∑j=1kexj−mk. Split off the last term, then add and subtract mk in the exponent:
dk+1=j=1∑k+1exj−mk+1=exk+1−mk+1+j=1∑kexj−mk+mk−mk+1=exk+1−mk+1+emk−mk+1j=1∑kexj−mk=dkemk−mk+1+exk+1−mk+1
The first term rescales the previous terms; the second is the new term.
Intuition: Why does this matter for FlashAttention? The same trick can stream in xi=q⋅ki and value vectors vi while computing the weighted sum o=∑ipivi, without ever storing the whole attention matrix: keep one more running numerator ok, update it just like dk, and output oN/dN at the end. Episode 14 derives it carefully.
Recap
Surprise is −logp and entropy is the average surprise. Cross-entropy measures surprise with q while reality follows p; it equals entropy plus KL divergence, so minimizing it pulls q toward p, with entropy as the floor. In training the target is one-hot, so the loss is the correct token's negative log probability, about ln50257≈10.82 at initialization; in code, shift by one and mask out positions that shouldn't count, dividing by the sum of the mask. Numerically, nearly every trick is "subtract the maximum": stable softmax, log-softmax =xi−LSE(x), stable logsumexp, and single-pass online softmax. That wraps up the foundations. Next time we put the whole Transformer together and see where those logits come from.