In Part 5 of this series, we saw how cross-entropy scores a classifier using -ln(p): assign p = 0.9 to the right support-ticket category and your loss is a tiny 0.105, while assigning p = 0.01 shoots the loss up to 4.605. That formula is easy to memorize, yet one natural question stays unanswered: why does a logarithm sit inside almost every classification loss in deep learning?
This guide opens the hood on three closely linked ideas that power real training pipelines: why multiplying probabilities across examples breaks computer arithmetic and forces us to take the log, how the log-sum-exp trick stops e^z from overflowing when logits get large, and how KL divergence extends cross-entropy from single hard labels to full target distributions.
Why multiplying probabilities breaks in float32
Start with a simple probability rule. Flip one fair coin and the chance of heads is 0.5. Flip two independent fair coins and the chance of getting heads on both is 0.5 × 0.5 = 0.25. When independent events all need to happen together, their probabilities multiply.
Now apply that exact rule to a trained support-ticket classifier checking three independent tickets. Suppose the model assigns 0.90 to the true class on Ticket 1, 0.80 on Ticket 2, and 0.95 on Ticket 3. The joint probability of getting all three right is their product:
With three tickets, 0.684 looks completely harmless. Now scale that same good model (0.9 on every single ticket) up to a realistic training batch or dataset. Ten tickets yield 0.9^10 = 0.3487. One hundred tickets drop to 0.9^100 ≈ 2.66 × 10^-5. By 1,000 tickets, the exact mathematical product is 0.9^1000 ≈ 1.75 × 10^-46.
Standard 32-bit floating-point numbers (float32, the default precision used across PyTorch models) cannot store any positive number smaller than roughly 1.4 × 10^-45. Anything smaller rounds straight down to exact 0.0, an error called numerical underflow. Once the product hits zero, a strong model (0.9 per ticket) and a terrible model (0.2 per ticket) both score 0.0, leaving training with no useful signal to compare them.
What a natural logarithm does, and why it rescues training
A logarithm is simply the inverse of an exponent. In deep learning we almost always use the natural logarithm, written ln(x), which uses Euler's constant e ≈ 2.718 as its base. Asking for ln(x) asks one concrete question: what power must we raise e to in order to get x?
ln(1) = 0, becausee^0 = 1. A perfectly confidentp = 1.0produces zero surprise.ln(0.5) ≈ -0.693, becausee^-0.693 ≈ 0.5. Cutting probability in half moves the log down by0.693.ln(0.1) ≈ -2.303, becausee^-2.303 ≈ 0.1. Lower probabilities pushln(p)deeply negative.
Probabilities between 0 and 1 produce negative values under ln(p), so negating it creates a clean positive penalty that shrinks smoothly to zero as p reaches 1.0.
| Assigned probability p for the true class | ln(p) (always <= 0) | -ln(p) (positive loss) |
|---|---|---|
| 0.05 | -2.996 | 2.996 |
| 0.10 | -2.303 | 2.303 |
| 0.20 | -1.609 | 1.609 |
| 0.30 | -1.204 | 1.204 |
| 0.40 | -0.916 | 0.916 |
| 0.50 | -0.693 | 0.693 |
| 0.60 | -0.511 | 0.511 |
| 0.70 | -0.357 | 0.357 |
| 0.80 | -0.223 | 0.223 |
| 0.90 | -0.105 | 0.105 |
| 1.00 | 0 | 0 |
Notice two superpowers of ln(p) immediately from the curve and its algebra. First, ln(p) is strictly increasing: whenever one model has a higher probability than another, its log is also higher, so maximizing ln(L) picks the exact same best weights as maximizing L. Second, because exponents add when powers multiply (e^a · e^b = e^(a+b)), logarithms turn multiplication into addition:
Verify that rule with concrete numbers. Taking a = 0.9 and b = 0.8, their product is 0.72 and ln(0.72) = -0.329. Separately, ln(0.9) = -0.105 and ln(0.8) = -0.223, and -0.105 + (-0.223) = -0.328 (exact -0.3285 before rounding). Since probabilities sit between 0 and 1, every ln(p_i) is negative, so we put a minus sign in front to build a positive loss that training can minimize:
Run the 1,000-ticket stress test again in log space. Each 0.9 prediction contributes -ln(0.9) ≈ 0.1054, so 1,000 tickets sum to 1,000 × 0.1054 ≈ 105.4 (exact 105.36). No underflow, no vanishing digits, and each ticket adds its own independent piece to the batch loss so gradients accumulate cleanly across examples.
The log-sum-exp trick: stopping exponential overflow
Logarithms solved underflow (numbers crashing to 0.0). Right inside Softmax and cross-entropy sits the opposite danger: overflow (numbers exploding past the largest value float32 can hold).
Remember from Part 4 of this series that a classifier outputs unconstrained raw scores called logits (z), and Softmax turns them into probabilities by exponentiating every logit via e^(z_i). The function e^z grows astonishingly fast:
e^10 ≈ 22,026: already over twenty thousand from a modest logit of10.e^88 ≈ 1.65 × 10^38: still fits insidefloat32, whose ceiling is3.40 × 10^38.e^89 ≈ 4.49 × 10^38: exceeds thefloat32ceiling and overflows straight toinf.e^100 ≈ 2.69 × 10^43ande^1000: both immediately produceinf, turninge^z / sum(e^z)intoinf / inf = NaNand poisoning every weight on the next step.
The cure starts with one surprising numerical fact about Softmax. Compute Softmax on the modest logits [2.0, 1.0, 0.1] and you get [0.659, 0.242, 0.099]. Now add 1,000 to every single logit, giving [1002.0, 1001.0, 1000.1]. Mathematically, the true probabilities are still [0.659, 0.242, 0.099], completely unchanged.
Why does shifting every logit by the same constant c leave Softmax untouched? Because adding c inside the exponent pulls out a common factor e^c from both numerator and denominator, and e^c / e^c cancels to 1. Only the gaps between logits determine the probabilities.
When computing cross-entropy directly from logits, we need the log of the Softmax denominator, called log-sum-exp: ln(sum_j e^(z_j)). Applying the exact same factoring idea with m = max_j(z_j) lets us pull e^m outside the sum and outside the logarithm:
Walk through [1000, 999, 998] step by step. First, find m = 1000 and subtract it from every logit to get [0, -1, -2]. Second, exponentiate those tiny shifted scores: e^0 = 1.000, e^-1 = 0.368, and e^-2 = 0.135, whose sum is 1.503. Third, take ln(1.503) = 0.408 and add m back to get 1000.408, with zero overflow, zero underflow, and full floating-point precision.
KL divergence: measuring distance between full distributions
Standard cross-entropy assumes every training example has one definite ground-truth class, encoded as a one-hot target such as [1.0, 0.0, 0.0]. Real datasets are not always that black and white. Suppose a support ticket reads "I was double-charged after the checkout button crashed", and ten human reviewers vote on the best department: 7 pick billing, 2 pick technical, and 1 picks account.
Their collective verdict is not a single category. It is a soft target distribution p = [0.7, 0.2, 0.1]. Now suppose our classifier predicts q = [0.6, 0.3, 0.1]. How do we score how far the predicted distribution q drifts from the target distribution p?
Build the formula one class at a time, starting with billing (p = 0.7, q = 0.6). First, take the ratio p / q = 0.7 / 0.6 ≈ 1.167, which measures how much q fell short relative to p (a ratio of 1.0 means an exact match). Second, take the natural log ln(1.167) ≈ +0.154 so that an exact match (ratio = 1) scores 0. Third, multiply by the target weight p = 0.7 so major categories matter more than rare ones: 0.7 × 0.154 = +0.108.
Repeat those three operations for every class and sum them together. That sum is Kullback-Leibler (KL) divergence, written D_KL(p || q) (read the KL divergence of p relative to q):
A close prediction stays near the reviewer votes (KL = 0.027), while putting 0.60 on Account and only 0.20 on Billing spikes KL divergence more than 25x higher (0.698).
| Support-ticket department | Target p (reviewers) | Close q (KL = 0.027) | Poor q (KL = 0.698) |
|---|---|---|---|
| Billing | 0.7 | 0.6 | 0.2 |
| Technical | 0.2 | 0.3 | 0.2 |
| Account | 0.1 | 0.1 | 0.6 |
Let's inspect every class row for both q_close = [0.6, 0.3, 0.1] and q_far = [0.2, 0.2, 0.6] so nothing stays hidden inside the summation:
| Department | Target p | Close q term | Poor q term |
|---|---|---|---|
| Billing | 0.70 | 0.7 * ln(0.7/0.6) = +0.108 | 0.7 * ln(0.7/0.2) = +0.877 |
| Technical | 0.20 | 0.2 * ln(0.2/0.3) = -0.081 | 0.2 * ln(0.2/0.2) = 0.000 |
| Account | 0.10 | 0.1 * ln(0.1/0.1) = 0.000 | 0.1 * ln(0.1/0.6) = -0.179 |
| Total KL | 1.00 | 0.027 | 0.698 |
Why are individual rows like -0.081 (Technical in q_close) and -0.179 (Account in q_far) negative? Because whenever q_i > p_i, the model gave that class more probability than the target asked for, so p_i / q_i < 1 and its logarithm is negative. Yet the total KL divergence can never drop below zero: probabilities must sum to 1, so over-allocating mass to one class forces you to steal mass away from other classes, and starving higher-weight classes always costs more than the small negative credit you gained elsewhere.
How KL divergence connects to cross-entropy, and why order matters
Apply the quotient rule of logarithms (ln(a / b) = ln(a) - ln(b)) to the KL formula, and a clean bridge back to Part 5 drops right out:
The first term is cross-entropy CE(p, q), the exact loss we already know. The second term H(p) is the entropy of the target distribution, which simply measures how spread out or uncertain the target itself is. On p = [0.7, 0.2, 0.1] and q_far = [0.2, 0.2, 0.6], cross-entropy is 1.500, the target's entropy is H(p) = 0.802, and 1.500 - 0.802 = 0.698, matching our KL table to three decimal places.
Because the target labels p never change during training, H(p) is just a fixed constant offset. Minimizing KL divergence and minimizing cross-entropy therefore push the model's weights in the exact same direction! Even better, for a sharp one-hot target like [1, 0, 0], there is zero uncertainty (H(p) = 0), so KL divergence reduces literally to standard cross-entropy.
There is one major gotcha before using KL divergence in code: it is not symmetric. Swapping p and q changes which distribution weights the sum, so D_KL(p || q) and D_KL(q || p) are usually different numbers. On our exact example, D_KL(p || q_far) = 0.698, whereas reversing the order gives D_KL(q_far || p) = 0.825.
Because D_KL(p || q) compares full probability distributions cleanly, practitioners reach for it whenever targets are soft rather than one-hot. Two everyday examples are soft reviewer labels (like our 7 / 2 / 1 ticket split) and knowledge distillation, where a small, fast student model learns to copy a larger teacher model's full output probabilities instead of only its single top-1 guess.
import torchimport torch.nn.functional as F# Soft target from 10 reviewers (batch size 1, 3 classes)target_p = torch.tensor([[0.7, 0.2, 0.1]])# Raw logits from our classifier (never pass plain probabilities as input)logits = torch.tensor([[0.9, 0.2, -0.9]])log_q = F.log_softmax(logits, dim=-1) # Uses log-sum-exp internally# Always use reduction="batchmean" for true mathematical KL divergencekl_loss = F.kl_div(log_q, target_p, reduction="batchmean")print(f"KL(p || q): {kl_loss.item():.4f}")
Putting all three pieces together
| Tool | Problem it solves | Key formula or rule |
|---|---|---|
| Natural log (-ln p) | Multiplying probabilities underflows float32 to 0.0 | Turns product into sum: -ln(prod pi) = sum(-ln pi) |
| Log-sum-exp shift | Exponentiating large logits overflows float32 to inf | m + ln(sum e^(z_i - m)) with m = max(z) |
| KL divergence | Hard one-hot labels miss soft probability targets | DKL(p || q) = sum pi ln(pi / qi) = CE(p, q) - H(p) |
Run the interactive Python lab below right in your browser to verify every number in this article, from float32 underflow on 1,000 tickets and shift-invariant Softmax to stable log-sum-exp and both directions of KL divergence. Try changing n_tickets, bumping big_logits to [5000.0, 4999.0, 4998.0], or setting q_close = p to watch KL drop to 0.0000.
import mathimport structdef to_float32(x):return struct.unpack("f", struct.pack("f", x))[0]# 1. Probability product vs. sum of negative logsprobs = [0.90, 0.80, 0.95]likelihood = math.prod(probs)neg_log_prod = -math.log(likelihood)sum_ce = sum(-math.log(p) for p in probs)print(f"3 tickets: likelihood = {likelihood:.3f}, -ln(L) = {neg_log_prod:.4f}, sum CEs = {sum_ce:.4f}")# Stress test in float32 across 1,000 confident ticketsn_tickets = 1000f32_prod = to_float32(0.9 ** n_tickets)log_sum = n_tickets * (-math.log(0.9))print(f"{n_tickets:,} tickets at p=0.9: float32(0.9^N) = {f32_prod}, sum -ln(p) = {log_sum:.2f}")# 2. Shift-invariant Softmax and stable log-sum-expdef stable_softmax(z):m = max(z)exps = [math.exp(v - m) for v in z]total = sum(exps)return [e / total for e in exps]def stable_lse(z):m = max(z)return m + math.log(sum(math.exp(v - m) for v in z))big_logits = [1000.0, 999.0, 998.0]print("Softmax [2, 1, 0.1]: ", [round(v, 3) for v in stable_softmax([2.0, 1.0, 0.1])])print("Softmax [1002, 1001, 1000.1]:", [round(v, 3) for v in stable_softmax([1002.0, 1001.0, 1000.1])])print(f"Stable LSE({[int(v) for v in big_logits]}): {stable_lse(big_logits):.4f}")# 3. KL divergence, entropy offset, and asymmetrydef kl(p, q):return sum(pi * math.log(pi / qi) for pi, qi in zip(p, q) if pi > 0)def ce(p, q):return sum(-pi * math.log(qi) for pi, qi in zip(p, q) if pi > 0)def entropy(p):return sum(-pi * math.log(pi) for pi in p if pi > 0)p = [0.7, 0.2, 0.1]q_close = [0.6, 0.3, 0.1]q_far = [0.2, 0.2, 0.6]ce_far, h_p = ce(p, q_far), entropy(p)print(f"KL(p || p): {kl(p, p):.4f}")print(f"KL(p || q_close): {kl(p, q_close):.4f}")print(f"KL(p || q_far): {kl(p, q_far):.4f} (CE {ce_far:.4f} - H(p) {h_p:.4f} = {ce_far - h_p:.4f})")print(f"Reverse KL(q_far || p): {kl(q_far, p):.4f}")
Brain Link on YouTube
Why Do Loss Functions Use the Log?
Watch the full animated walkthrough of probability underflow, natural logs, the log-sum-exp trick, and KL divergence.
Now the hidden machinery inside cross-entropy is completely transparent: logarithms keep probability products from vanishing into float32 zeros, subtracting max(z) inside log-sum-exp keeps exponentials from exploding to inf, and KL divergence extends the exact same idea from one-hot classes to full probability distributions. In Part 7 of this series, we will step into specialized losses built for imbalanced classes, decision margins, and similarity search: focal loss, hinge loss, and triplet loss.
References
- [1]torch.nn.functional.log_softmax · PyTorch documentationNumerically stable log-probability computation using the log-sum-exp shift.
- [2]torch.nn.functional.cross_entropy · PyTorch documentationCombines log-softmax and negative log-likelihood directly on raw logits.
- [3]torch.nn.functional.kl_div · PyTorch documentationKL divergence implementation, log-probability input contract, and batchmean reduction.
- [4]torch.nn.KLDivLoss · PyTorch documentationModule wrapper for pointwise KL divergence and reduction conventions.
- [5]Why Do Loss Functions Use the Log? (video) · Brain Link on YouTube
- [6]Deep Learning Fundamentals playlist · Brain Link on YouTube







