All four chapters, worked examples, comparison fallback, answers and sources. Controls are omitted; each diagram shows the default worked example.
Chapter 1
Start with surprise
A forecast is a set of bets. Give each possible outcome a score before averaging anything.
One delivery, two possible outcomes
Imagine a delivery service. In this invented example, a delivery arrives on time with probability 75%, and late with probability 25%. Call on time A and late B.
P is our reference event mix: 75% A, 25% B. Q is a forecast we want to judge: it says 50% A, 50% B. A distribution is simply this complete list of probabilities. Each list adds to 100%.
Keep this little table in mind throughout the guide.
Outcome
P: reference
Q: forecast
A · on time
0.75 = 75%
0.50 = 50%
B · late
0.25 = 25%
0.50 = 50%
P · reference: A 75% · B 25%
Q · forecast: A 50% · B 50%
Solid length = A (on time). Remaining length = B (late).
Over 100 deliveries, that reference gives expected counts of 75 on-time and 25 late deliveries. An actual batch could differ. We will use these counts to make an average easy to see.
Q is too pessimistic about A and too optimistic about B. How much does that mismatch cost? We first need a scoring rule for one outcome.
The halving ladder
If you give an outcome a 100% chance, seeing it is unsurprising. If you give it a 1% chance, seeing it contradicts a confident forecast. We want a score that grows as the assigned probability shrinks.
Use this rule: every halving of probability adds one unit of surprise. Start at 100%, with score zero.
100%0 halvings 0 bits
50%1 halving 1 bit
25%2 halvings 2 bits
12.5%3 halvings 3 bits
Here a bit is the unit of this surprise score. It is not a percentage point. Halving again adds another bit; it does not double the score.
The logarithm extends the ladder to probabilities between its rungs. To score 75%, ask: what exponent on ½ gives 0.75? The answer is about 0.415, because one half raised to 0.415 is about 0.75. Fractional scores are allowed.
(21)0.4150375≈0.75
The compact way to calculate this is below. r means the probability your chosen forecast assigned to the outcome that happened; “log₂” is the base-two logarithm. The minus sign makes this score positive for probabilities below one.
surprise(r)=−log2r
For example, log₂(½)=−1, so −log₂(½)=1. This is a mathematical score, not a claim about a person's emotions. It is useful for repeated events: for independent events, probabilities multiply, while these surprise scores add.
P assigns A a surprise of 0.4150375 bits and B a surprise of 2 bits. Averaging those two numbers equally would pretend the events happened equally often.
Instead, imagine the expected 75 A outcomes each contributing 0.4150375, and the 25 B outcomes each contributing 2. Add all the scores, then divide by 100:
10075(0.4150375)+25(2)≈0.811278bits
Equivalently, multiply by the fractions 0.75 and 0.25. That is a weighted average. The average surprise when P scores its own event mix is called entropy. The name comes after the operation; you do not need it to do the arithmetic.
Before continuing: Q gives both events a score of 1 bit. What is its average score over the same 75/25 mix?
Show the reasoning
0.75 × 1 + 0.25 × 1 = 1 bit. Every event scores 1, so any mix averages to 1.
P's own average is about 0.811 bits. Q's is 1 bit. The extra amount is the idea behind KL.
Chapter 2
The extra amount is KL
Keep the event mix fixed. Change the forecast used to score it. Subtract the two averages.
Two rows, one extra average
We still use P = [0.75, 0.25] and Q = [0.50, 0.50]. Both scoring rules see the same event mix from P. Under Q the average is 1 bit; under P it is 0.811278 bits.
1−0.8112781245=0.1887218755bits
KL divergence is this extra average surprise. Here it is about 0.189 bits per delivery. It is neither an 18.9% error rate nor the surprise of every individual delivery.
You can also subtract first, one outcome at a time:
A: Q scores it 1 instead of 0.4150375. Extra = 0.5849625. It has P weight 0.75, giving +0.4387219.
B: Q scores it 1 instead of 2. Extra = −1. It has P weight 0.25, giving −0.25.
Add the weighted contributions: 0.4387219 − 0.25 = 0.1887219 bits. Q is less surprised by B than P is, so B's contribution is negative. A happens more often in this reference mix, and its positive contribution is larger.
Predict what will happen when you swap the two distributions. Then use the calculator. Reset returns to the delivery example.
Default: reference 75% on time; forecast 50% on time.
P · reference: A 75% · B 25%
Q · forecast: A 50% · B 50%
Solid length = A (on time). Remaining length = B (late).
Each row uses its P probability as the weight. Scores in bits; decimals rounded.
Event
P weight
Q
Extra score
Weighted contribution
A · on time
0.75
0.50
0.584963
0.438722
B · late
0.25
0.50
-1.000000
-0.250000
1.000000 − 0.811278 = 0.188722 bits
Average using Q − average using P, both over the P event mix.
Write D with a KL subscript for “KL divergence.” Write P first to say whose event mix we average over, and Q second to say which alternative forecast we use. The two vertical bars separate those roles.
DKL(P∥Q)=x∑P(x)log2Q(x)P(x)
x
One possible outcome: A, then B in our example.
P(x)
The probability of that outcome in the reference mix. This is also its averaging weight.
Q(x)
The probability the alternative forecast gives the same outcome.
log₂(P(x)/Q(x))
The extra surprise for that outcome. Subtracting −log₂ P(x) from −log₂ Q(x) gives this log ratio.
Σ (capital sigma)
“Add the following expression for every outcome.” Here there are only two terms.
The formula is a compressed set of instructions: find the extra score, multiply by how often the outcome occurs under P, and add.
Optional: connect the two average names
H(P) is entropy: P's own average surprise. H(P,Q) is cross-entropy: Q's surprise averaged over P. For finite discrete distributions with Q positive wherever P is positive:
DKL(P∥Q)=H(P,Q)−H(P)
The log identity log a − log b = log(a/b) combines the two surprises into the ratio above.
The first argument is not decoration
Swap P and Q. You now average over a 50/50 mix and score it using the 75/25 forecast. The new baseline is the 50/50 mix's own surprise.
DKL(Q∥P)=0.5log20.750.5+0.5log20.250.5
≈−0.292481+0.5=0.207519bits
0.207519 is different from 0.188722. The event mix changed as well as the scoring rule. Because swapping can change the answer, KL is not an ordinary distance.
For valid probability distributions the total KL is nonnegative, and it is zero exactly when they match. Individual rows can still be negative, as we saw. You cannot beat the reference's own forecast on average under that reference using this scoring rule.
Our ladder uses log₂ and reports bits. Using the natural logarithm, written ln, reports nats. The natural log uses the mathematical base e, about 2.718, instead of 2. You do not need a new scoring idea: only the scale changes.
Dnats=Dbitsln2
Multiply bits by about 0.693147 to get nats. Our 0.1887219 bits becomes 0.1308120 nats. The unit switch changes the numbers, never which forecast is better. The landscape in the next chapter keeps its height axis in bits.
Two probabilities choose a place on the floor. Extra average surprise sets its height.
Read the three directions
Our outcomes have not changed. A is on time; B is late. A two-outcome distribution is also called a Bernoulli distribution. Since its probabilities sum to 1, we only need the probability of A.
p = P(A): move along the reference direction on the floor. P(B) is automatically 1 − p.
q = Q(A): move along the forecast direction on the floor. Q(B) is automatically 1 − q.
Height: KL(P‖Q), the extra average surprise in bits.
Every point on the surface is a different pair of probability tables. The line p=q lies on the floor: if both forecasts agree, there is no extra score. A ring shows the pair currently chosen below.
Predict: keep p at 75%. Should moving q from 50% toward 75% lower or raise the ring?
Change a forecast, follow its height
Default: reference 75% on time; forecast 50% on time.
P · reference: A 75% · B 25%
Q · forecast: A 50% · B 50%
Solid length = A (on time). Remaining length = B (late).
The diagonal line is p=q: every matching pair has zero extra surprise. For finite KL, the ring marks the current pair.
Surface height is in bits, capped at 4. Exact result below is uncapped.
Each row uses its P probability as the weight. Scores in bits; decimals rounded.
Event
P weight
Q
Extra score
Weighted contribution
A · on time
0.75
0.50
0.584963
0.438722
B · late
0.25
0.50
-1.000000
-0.250000
1.000000 − 0.811278 = 0.188722 bits
Average using Q − average using P, both over the P event mix.
Start with Equal: the ring sits in the valley. Try Moderately wrong, then Confidently wrong. The latter says A has only a 1% chance even though P says 75%: its extra surprise rises sharply.
The slice beneath the surface holds your current p fixed and varies only q. Its dashed line marks q=p, where the curve reaches zero. Top view helps you locate the pair on the floor; return to 3D surface to see height. Swap moves to a different scoring problem, so the height usually changes.
The mesh draws q from 0.01 to 0.99, with p from 0 to 1. Surface and slice heights are capped at 4 bits, with no log transformation. This keeps the valley visible; KL itself has no upper bound. The displayed calculations use the actual formula, not the mesh approximation. Finite endpoint markers can appear just outside the mesh.
Read the landscape without moving it
Keep P(A)=0.75 and change the forecast. Exact formula, rounded bits.
Q(A)
Extra bits
What changes
0.75
0
Forecast matches: valley floor.
0.50
0.188722
Moderate mismatch: a little above the floor.
0.01
4.175239
Confidently wrong: above the drawn 4-bit ceiling.
0
∞
A can happen but Q calls it impossible.
If both distributions put all probability on A, KL is zero. Their unused B row contributes zero even though both B probabilities are zero.
Zero is not “very unlikely”
Choose Impossible forecast. Q(A)=0 while P(A)=0.75. The forecast rules out an outcome that can happen. As q approaches zero, −log₂ q grows without limit; at exact zero the extra average is infinity.
Infinity is not the top of the drawn surface. It has no finite location, so the ring disappears and the numerical answer says ∞. We do not replace zero with a small positive number.
Now consider a different zero: P(x)=0. That outcome never occurs in the mix being averaged, so its contribution is defined as zero. We skip the term before evaluating a logarithm. This includes P(x)=Q(x)=0; we never try to divide 0 by 0.
Certain & equal puts all probability on A in both distributions. A contributes zero because they agree; the unused B row contributes zero too. Total: zero.
Try a new case mentally: P=[1,0], Q=[0.5,0.5]. What is KL? What changes when you swap?
Show the answer
Only A occurs under P. Its extra surprise is 1−0=1 bit. After swapping, the first mix gives B positive probability but the second forecast gives B zero. The swapped KL is infinite.
A teacher can supply the reference distribution. The first argument still decides the weights.
Same table, a new source of probabilities
Imagine a teacher model and a student model looking at the same input. They assign probabilities to the same possible outputs. For a language model, an output here could be the next token.
Keep the two-outcome teaching table: teacher T=[0.75,0.25], student S=[0.5,0.5]. These remain invented numbers. We now call A and B two possible outputs rather than delivery outcomes; the arithmetic is unchanged.
Knowledge distillation can train the student to match the teacher's probability distribution, using soft targets rather than only the most likely answer. The teacher is a reference here; that does not make it infallible.
Soft-target distillation: Hinton, Vinyals & Dean, section 2. Temperature and mixtures with hard labels are outside this small example.
Say the direction explicitly
In this guide, forward KL means teacher first:
DKL(T∥S)=x∑T(x)log2S(x)T(x)
The teacher supplies the weights. Our example gives 0.188722 bits. If the teacher is fixed, reducing this KL by changing S is equivalent to reducing cross-entropy, because the teacher's own entropy is constant.
Here, reverse KL means student first:
DKL(S∥T)=x∑S(x)log2T(x)S(x)
The student supplies the weights. The same table gives 0.207519 bits. Changing the student now also changes those weights. Always read the written arguments; the words “forward” and “reverse” need a declared reference.
This is one comparison at one fixed input. On-policy distillation adds another question: which inputs or prefixes does the student visit during training? That question is separate from the direction of KL at an individual input.
KL(P‖Q) is the extra average surprise from using Q to score outcomes drawn from P, compared with using P itself.
Read it left to right: P sets the event mix, Q is the alternative scoring forecast. For each outcome, find the extra surprise, weight it by P, then add. You have now built the equation rather than memorized its shape.
A teacher gives one output a 10% chance. A student gives it exactly zero. Which direction is certainly infinite, and why?
Explain the boundary
Forward T‖S is infinite because the first distribution gives positive weight to an output the second calls impossible. That output contributes zero to reverse S‖T because S gives it zero weight. Reverse could still be infinite for a different output; its finiteness depends on the whole table.
A small vocabulary
Probability distribution
A complete list of outcome probabilities, adding to one.
P and Q
In KL(P‖Q), P supplies the averaging weights; Q is the alternative forecast. P need not be the true world.
Surprise
The score −log of the probability assigned to an outcome. Smaller probability gives a larger score.
Logarithm
The exponent needed to reach a number from a chosen base. The halving ladder is −log₂ probability.
Entropy
Average surprise when a distribution scores its own outcomes.
Cross-entropy
Average surprise when Q scores outcomes averaged under P.
KL divergence
Cross-entropy minus the reference entropy; extra average surprise.
Bit and nat
Units from base-two and natural logarithms respectively; one bit equals ln(2) nats.
Bernoulli
A two-outcome distribution: probabilities p and 1−p.
Forward / reverse KL
Here forward is T‖S and reverse is S‖T. State the reference convention explicitly.
Geoffrey Hinton, Oriol Vinyals and Jeff Dean (2015), section 2: teacher soft targets.
Boundary and example notes
All probability tables are invented teaching inputs. Calculations use normalized, finite, discrete distributions. P-zero rows are omitted from the expectation before taking logarithms. For positive P, decreasing Q to zero sends the log ratio to infinity. Both-zero rows contribute zero by convention, not by evaluating 0/0.
The landscape is a three-coordinate mathematical mesh projected into SVG. It needs no WebGL. Its finite mesh excludes q=0 and q=1; its height is capped at four bits. Exact labels use the formula directly and preserve infinity. No probability smoothing is applied.
This guide does not model sampling noise, continuous densities, gradient updates or a full distillation pipeline. Implementation checks do not establish improved comprehension.