{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"cross-entropy-and-kl-divergence","title":"Cross-entropy and KL: the cost of believing the wrong distribution","url":"https://addaly.com/learn/maths-you-need/cross-entropy-and-kl-divergence","position":44,"of":76,"minutes":10,"answer":"Cross-entropy is entropy plus KL divergence, so minimising it against fixed data can only shrink the KL and never go below the data's own entropy.","keyIdea":"Cross-entropy is entropy plus KL divergence, so minimising it against fixed data can only shrink the KL and never go below the data's own entropy, which is why a loss plateau above zero can be the floor rather than a failure."},"body":{"format":"markdown","text":"## Paying with the wrong code\n\nEntropy is what you pay when your predictions match reality. Cross-entropy is what you pay when they do not. If outcomes arrive with probabilities `p` but you built your code, or your model, around probabilities `q`, the average cost is\n\n```\nH(p, q) = − Σ p_i × log2(q_i)\n```\n\nThe probabilities that decide how often you pay are the true ones, `p`. The probabilities that decide how much you pay each time are yours, `q`.\n\nTake the reality from the last lesson, `p = (0.5, 0.25, 0.125, 0.125)`, whose entropy is 1.75 bits. Suppose your model believes the four outcomes are equally likely, `q = (0.25, 0.25, 0.25, 0.25)`. Every outcome now costs `−log2(0.25) = 2` bits, so `H(p, q) = 2` bits. You pay a quarter of a bit more per outcome than a perfect model would.\n\nNow a model that is wrong in a different way, `q = (0.7, 0.1, 0.1, 0.1)`:\n\n```\n0.5   × −log2(0.7) = 0.5   × 0.515 = 0.257\n0.25  × −log2(0.1) = 0.25  × 3.322 = 0.830\n0.125 × −log2(0.1) = 0.125 × 3.322 = 0.415\n0.125 × −log2(0.1) = 0.125 × 3.322 = 0.415\n                                     -----\nH(p, q) = 1.918 bits\n```\n\nThis model is overconfident in the first outcome and pays for it on the second, which it thought was rare and which happens a quarter of the time.\n\n## The gap has a name\n\nThe extra cost over the entropy is the **Kullback-Leibler divergence**:\n\n```\nKL(p ‖ q) = H(p, q) − H(p) = Σ p_i × log2(p_i / q_i)\n```\n\nFor the uniform model it is `2 − 1.75 = 0.25` bits; for the overconfident one, `1.918 − 1.75 = 0.168` bits. KL is never negative, and it is zero only when `q` equals `p` exactly. It measures, in bits per outcome, how wrong a belief is.\n\n> Figure: Where a cross-entropy of 2.00 bits actually goes. Layers, top to bottom: Cross-entropy, 2.00 bits (what a model believing q pays per outcome); KL divergence, 0.25 bits (the removable part: how wrong the belief is); Entropy of the data, 1.75 bits (the floor, which no model can go beneath). Cross-entropy is entropy plus KL divergence. Training against fixed data can only shrink the second term, so a loss that plateaus above zero may be sitting on the floor rather than failing. Compute the floor from your own label column before judging any curve.\n\nThat identity, `H(p, q) = H(p) + KL(p ‖ q)`, is the most useful line in this module. When you train a model by minimising cross-entropy against data, `H(p)` is a property of the data and does not move. So minimising cross-entropy is minimising KL, and the loss can never go below the data's own entropy. A language model's loss plateaus above zero not because it has failed but because language is uncertain: the floor is real. The previous lesson computed that floor for a label column; the same logic applies to every token.\n\n## With one-hot labels\n\nIn classification the \"true\" distribution for a single example is a one-hot: probability 1 on the correct class, 0 elsewhere. Every term in the sum vanishes except one, and the cross-entropy collapses to `−log q(correct)`: the surprise of the right answer. That is why the loss you see in a training loop is minus the log of the probability the model gave the label. The elaborate definition and the simple one are the same thing.\n\n## KL is not symmetric\n\nSwap the roles and you get a different number. With `p = (0.5, 0.25, 0.125, 0.125)` and `q` uniform:\n\n```\nKL(p ‖ q) = 0.25 bits\nKL(q ‖ p) = 0.25 × (log2(0.25/0.5) + log2(0.25/0.25) + 2 × log2(0.25/0.125))\n          = 0.25 × (−1 + 0 + 2) = 0.25 bits\n```\n\nEqual in this case, by coincidence of the round numbers. Change `p` to `(0.7, 0.1, 0.1, 0.1)` and `KL(p ‖ uniform) = 0.53` while `KL(uniform ‖ p) = 0.64`. The direction matters, and it matters most when one distribution puts probability near zero where the other does not.\n\nThe practical consequence: if `q` assigns probability 0 to something `p` can produce, `KL(p ‖ q)` is infinite, because you would pay `−log 0` when it happened. A model trained against exact one-hot targets is therefore pushed to make the correct logit infinitely larger than the rest, and never gets there. Label smoothing, which replaces the target `(1, 0, 0, 0)` with something like `(0.97, 0.01, 0.01, 0.01)`, exists to give the model a finite place to stop.\n\nThe direction also changes behaviour. Minimising `KL(p ‖ q)` over `q` makes `q` cover everywhere `p` has mass, even if it must spread thin. Minimising `KL(q ‖ p)` makes `q` sit on one mode of `p` and ignore the others. When a preference-trained language model is penalised for drifting from its reference model, the penalty is the second kind, taken over the model's own samples, which is one reason such models become narrower rather than broader.\n\n## Two things KL is not\n\nIt is not a distance: it is asymmetric and does not satisfy the triangle inequality, so \"the KL between two embeddings\" is not a meaningful phrase unless both are distributions. And it is not bounded: a single near-impossible event can make it arbitrarily large, so an average KL across a dataset can be dominated by one row.\n\n## The trap in the library\n\n`torch.nn.functional.kl_div(input, target)` expects `input` to be **log** probabilities and `target` to be plain probabilities, and it computes `KL(target ‖ exp(input))`. Passing probabilities for both runs without error and returns nonsense. `scipy.special.rel_entr(p, q)` takes plain probabilities for both and returns the elementwise terms; sum them yourself. Compute one small example by hand, as above, and check the library agrees before trusting it on anything larger."},"check":{"question":"A classifier's cross-entropy falls to 0.90 nats and stays there, with a flat rather than rising curve, while the labels' own entropy is estimated at 0.85 nats. What is going on?","options":[{"text":"The model is underfitting and needs more layers to push the loss toward zero.","correct":false,"tempting":"Ignores the floor: no model can score below the entropy of the labels, so there is at most 0.05 nats left to gain."},{"text":"The learning rate is too high and the optimiser is bouncing around the minimum.","correct":false,"tempting":"A bouncing optimiser shows as a noisy or rising curve, not a flat one sitting a few hundredths above the theoretical floor."},{"text":"The two figures cannot be compared, because entropy and cross-entropy use different units.","correct":false,"tempting":"Both are given in nats here; cross-entropy equals entropy plus KL, so they are directly comparable and the difference is the KL."},{"text":"The model is within 0.05 nats of the best possible loss.","correct":true}]},"prev":{"slug":"entropy-by-hand","title":"Entropy: the average surprise, computed by hand","url":"https://addaly.com/learn/maths-you-need/entropy-by-hand"},"next":{"slug":"maximum-likelihood-and-where-losses-come-from","title":"Loss functions are not arbitrary: maximum likelihood","url":"https://addaly.com/learn/maths-you-need/maximum-likelihood-and-where-losses-come-from"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Cross-entropy and KL: the cost of believing the wrong distribution', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/cross-entropy-and-kl-divergence (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Cross-entropy and KL: the cost of believing the wrong distribution","courseTitle":"The Maths You Actually Need","module":{"index":5,"slug":"logs-information-and-loss","title":"Logarithms, information and the shape of a loss"},"answer":null,"keyIdea":"Cross-entropy is entropy plus KL divergence, so minimising it against fixed data can only shrink the KL and never go below the data’s own entropy, which is why a loss plateau above zero can be the floor rather than a failure.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"Cross-entropy is entropy plus KL divergence. Training against fixed data can only shrink the second term, so a loss that plateaus above zero may be sitting on the floor rather than failing. Compute the floor from your own label column before judging any curve.","layers":[{"label":"Cross-entropy, 2.00 bits","detail":"what a model believing q pays per outcome"},{"label":"KL divergence, 0.25 bits","detail":"the removable part: how wrong the belief is"},{"label":"Entropy of the data, 1.75 bits","detail":"the floor, which no model can go beneath"}],"title":"Where a cross-entropy of 2.00 bits actually goes","type":"stack"},"alt":"Figure: Where a cross-entropy of 2.00 bits actually goes. Layers, top to bottom: Cross-entropy, 2.00 bits (what a model believing q pays per outcome); KL divergence, 0.25 bits (the removable part: how wrong the belief is); Entropy of the data, 1.75 bits (the floor, which no model can go beneath). Cross-entropy is entropy plus KL divergence. Training against fixed data can only shrink the second term, so a loss that plateaus above zero may be sitting on the floor rather than failing. Compute the floor from your own label column before judging any curve."}},"blocks":[{"t":"h2","id":"paying-with-the-wrong-code","runs":[{"text":"Paying with the wrong code"}]},{"t":"p","runs":[{"text":"Entropy is what you pay when your predictions match reality. Cross-entropy is what you pay when they do not. If outcomes arrive with probabilities "},{"text":"p","code":true},{"text":" but you built your code, or your model, around probabilities "},{"text":"q","code":true},{"text":", the average cost is"}]},{"t":"code","lang":"","label":"Text","text":"H(p, q) = − Σ p_i × log2(q_i)"},{"t":"p","runs":[{"text":"The probabilities that decide how often you pay are the true ones, "},{"text":"p","code":true},{"text":". The probabilities that decide how much you pay each time are yours, "},{"text":"q","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"Take the reality from the last lesson, "},{"text":"p = (0.5, 0.25, 0.125, 0.125)","code":true},{"text":", whose entropy is 1.75 bits. Suppose your model believes the four outcomes are equally likely, "},{"text":"q = (0.25, 0.25, 0.25, 0.25)","code":true},{"text":". Every outcome now costs "},{"text":"−log2(0.25) = 2","code":true},{"text":" bits, so "},{"text":"H(p, q) = 2","code":true},{"text":" bits. You pay a quarter of a bit more per outcome than a perfect model would."}]},{"t":"p","runs":[{"text":"Now a model that is wrong in a different way, "},{"text":"q = (0.7, 0.1, 0.1, 0.1)","code":true},{"text":":"}]},{"t":"code","lang":"","label":"Text","text":"0.5   × −log2(0.7) = 0.5   × 0.515 = 0.257\n0.25  × −log2(0.1) = 0.25  × 3.322 = 0.830\n0.125 × −log2(0.1) = 0.125 × 3.322 = 0.415\n0.125 × −log2(0.1) = 0.125 × 3.322 = 0.415\n                                     -----\nH(p, q) = 1.918 bits"},{"t":"p","runs":[{"text":"This model is overconfident in the first outcome and pays for it on the second, which it thought was rare and which happens a quarter of the time."}]},{"t":"h2","id":"the-gap-has-a-name","runs":[{"text":"The gap has a name"}]},{"t":"p","runs":[{"text":"The extra cost over the entropy is the "},{"text":"Kullback-Leibler divergence","b":true},{"text":":"}]},{"t":"code","lang":"","label":"Text","text":"KL(p ‖ q) = H(p, q) − H(p) = Σ p_i × log2(p_i / q_i)"},{"t":"p","runs":[{"text":"For the uniform model it is "},{"text":"2 − 1.75 = 0.25","code":true},{"text":" bits; for the overconfident one, "},{"text":"1.918 − 1.75 = 0.168","code":true},{"text":" bits. KL is never negative, and it is zero only when "},{"text":"q","code":true},{"text":" equals "},{"text":"p","code":true},{"text":" exactly. It measures, in bits per outcome, how wrong a belief is."}]},{"t":"p","runs":[{"text":"That identity, "},{"text":"H(p, q) = H(p) + KL(p ‖ q)","code":true},{"text":", is the most useful line in this module. When you train a model by minimising cross-entropy against data, "},{"text":"H(p)","code":true},{"text":" is a property of the data and does not move. So minimising cross-entropy is minimising KL, and the loss can never go below the data’s own entropy. A language model’s loss plateaus above zero not because it has failed but because language is uncertain: the floor is real. The previous lesson computed that floor for a label column; the same logic applies to every token."}]},{"t":"h2","id":"with-one-hot-labels","runs":[{"text":"With one-hot labels"}]},{"t":"p","runs":[{"text":"In classification the “true” distribution for a single example is a one-hot: probability 1 on the correct class, 0 elsewhere. Every term in the sum vanishes except one, and the cross-entropy collapses to "},{"text":"−log q(correct)","code":true},{"text":": the surprise of the right answer. That is why the loss you see in a training loop is minus the log of the probability the model gave the label. The elaborate definition and the simple one are the same thing."}]},{"t":"h2","id":"kl-is-not-symmetric","runs":[{"text":"KL is not symmetric"}]},{"t":"p","runs":[{"text":"Swap the roles and you get a different number. With "},{"text":"p = (0.5, 0.25, 0.125, 0.125)","code":true},{"text":" and "},{"text":"q","code":true},{"text":" uniform:"}]},{"t":"code","lang":"","label":"Text","text":"KL(p ‖ q) = 0.25 bits\nKL(q ‖ p) = 0.25 × (log2(0.25/0.5) + log2(0.25/0.25) + 2 × log2(0.25/0.125))\n          = 0.25 × (−1 + 0 + 2) = 0.25 bits"},{"t":"p","runs":[{"text":"Equal in this case, by coincidence of the round numbers. Change "},{"text":"p","code":true},{"text":" to "},{"text":"(0.7, 0.1, 0.1, 0.1)","code":true},{"text":" and "},{"text":"KL(p ‖ uniform) = 0.53","code":true},{"text":" while "},{"text":"KL(uniform ‖ p) = 0.64","code":true},{"text":". The direction matters, and it matters most when one distribution puts probability near zero where the other does not."}]},{"t":"p","runs":[{"text":"The practical consequence: if "},{"text":"q","code":true},{"text":" assigns probability 0 to something "},{"text":"p","code":true},{"text":" can produce, "},{"text":"KL(p ‖ q)","code":true},{"text":" is infinite, because you would pay "},{"text":"−log 0","code":true},{"text":" when it happened. A model trained against exact one-hot targets is therefore pushed to make the correct logit infinitely larger than the rest, and never gets there. Label smoothing, which replaces the target "},{"text":"(1, 0, 0, 0)","code":true},{"text":" with something like "},{"text":"(0.97, 0.01, 0.01, 0.01)","code":true},{"text":", exists to give the model a finite place to stop."}]},{"t":"p","runs":[{"text":"The direction also changes behaviour. Minimising "},{"text":"KL(p ‖ q)","code":true},{"text":" over "},{"text":"q","code":true},{"text":" makes "},{"text":"q","code":true},{"text":" cover everywhere "},{"text":"p","code":true},{"text":" has mass, even if it must spread thin. Minimising "},{"text":"KL(q ‖ p)","code":true},{"text":" makes "},{"text":"q","code":true},{"text":" sit on one mode of "},{"text":"p","code":true},{"text":" and ignore the others. When a preference-trained language model is penalised for drifting from its reference model, the penalty is the second kind, taken over the model’s own samples, which is one reason such models become narrower rather than broader."}]},{"t":"h2","id":"two-things-kl-is-not","runs":[{"text":"Two things KL is not"}]},{"t":"p","runs":[{"text":"It is not a distance: it is asymmetric and does not satisfy the triangle inequality, so “the KL between two embeddings” is not a meaningful phrase unless both are distributions. And it is not bounded: a single near-impossible event can make it arbitrarily large, so an average KL across a dataset can be dominated by one row."}]},{"t":"h2","id":"the-trap-in-the-library","runs":[{"text":"The trap in the library"}]},{"t":"p","runs":[{"text":"torch.nn.functional.kl_div(input, target)","code":true},{"text":" expects "},{"text":"input","code":true},{"text":" to be "},{"text":"log","b":true},{"text":" probabilities and "},{"text":"target","code":true},{"text":" to be plain probabilities, and it computes "},{"text":"KL(target ‖ exp(input))","code":true},{"text":". Passing probabilities for both runs without error and returns nonsense. "},{"text":"scipy.special.rel_entr(p, q)","code":true},{"text":" takes plain probabilities for both and returns the elementwise terms; sum them yourself. Compute one small example by hand, as above, and check the library agrees before trusting it on anything larger."}]}],"check":{"question":[{"text":"A classifier’s cross-entropy falls to 0.90 nats and stays there, with a flat rather than rising curve, while the labels’ own entropy is estimated at 0.85 nats. What is going on?"}],"options":[{"text":[{"text":"The model is underfitting and needs more layers to push the loss toward zero."}],"correct":false,"tempting":[{"text":"Ignores the floor: no model can score below the entropy of the labels, so there is at most 0.05 nats left to gain."}]},{"text":[{"text":"The learning rate is too high and the optimiser is bouncing around the minimum."}],"correct":false,"tempting":[{"text":"A bouncing optimiser shows as a noisy or rising curve, not a flat one sitting a few hundredths above the theoretical floor."}]},{"text":[{"text":"The two figures cannot be compared, because entropy and cross-entropy use different units."}],"correct":false,"tempting":[{"text":"Both are given in nats here; cross-entropy equals entropy plus KL, so they are directly comparable and the difference is the KL."}]},{"text":[{"text":"The model is within 0.05 nats of the best possible loss."}],"correct":true,"tempting":null}],"order":[2,0,1,3],"why":null},"prev":{"slug":"entropy-by-hand","title":"Entropy: the average surprise, computed by hand","minutes":9},"next":{"slug":"maximum-likelihood-and-where-losses-come-from","title":"Loss functions are not arbitrary: maximum likelihood","minutes":10}}}