Chapter 11 of 42 · ~30 min read & lab+80 XP
Chapter 11 · Deep Learning

Loss Functions II: Classification Losses (Log-Sum-Exp, BCE, Cross-Entropy, Focal & Smoothing)

Master the workhorse losses of Deep Learning: why Cross-Entropy gives the clean (p − y) gradient, the Log-Sum-Exp NaN fix, Focal Loss for 1000:1 imbalance, and Label Smoothing.

Why ML Engineers & Data Scientists Actually Need This

Cross-Entropy trains EVERY image classifier AND EVERY Large Language Model (predicting next tokens across 128k classes)!

ML / AI Engineer

Passing Softmax probabilities into nn.CrossEntropyLoss or computing naive torch.log(torch.exp(z).sum()) without Max-Shift are two of the top 5 PyTorch bugs in real codebases.

Data Scientist

When 99.9% of pixels or transactions are negative, standard Cross-Entropy drowns in easy negatives — Focal Loss lets your network focus 100% of its gradient budget on hard cases!

Interview & Debug Edge

Guaranteed DL interview question: 'Derive the gradient of Softmax + Cross-Entropy with respect to raw logits z, explain how to make it numerically stable, and explain how Label Smoothing regularizes the model!'

Step 0 · Test Your Gut Before Any Math!

In a 3-class classifier, the true label is Class 0 (y = [1, 0, 0]) and Softmax outputs p = [0.20, 0.50, 0.30]. What is the exact gradient ∂L / ∂z of Cross-Entropy with respect to the 3 raw logits z?

What You Will Master in This Chapter
  • Derive Binary Cross-Entropy & Multi-Class Cross-Entropy from Maximum Likelihood and prove ∂L/∂z = p − y
  • Implement the Log-Sum-Exp Max-Shift trick to prevent float32 exp(z) = inf / NaN crashes
  • Explain why PyTorch's BCEWithLogitsLoss and CrossEntropyLoss MUST receive raw logits (never Sigmoid/Softmax!)
  • Use Focal Loss −(1 − p_t)^γ log(p_t) for extreme class imbalance and Label Smoothing ε to prevent overconfident logits
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
zSay aloud:“Raw logits”
Plain-English Meaning
Unconstrained scores output by the final nn.Linear layer before Softmax/Sigmoid
Everyday Example
z ∈ (−∞, +∞)
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Cross-Entropy measures surprise (−log p_true). If the true answer is Cat and your network says 99% Cat, surprise is 0.01 (tiny nudge). If your network arrogantly says 0.1% Cat, surprise explodes to 6.9 and fires a crisp (p − y) gradient straight back into the weights — without ever suffering Sigmoid saturation!

1. Numerical Stability: The Log-Sum-Exp & BCE-With-Logits Tricks

Everyday Story First (Zero Math Yet!)

In float32, exp(89) overflows to +inf! If you naively compute Softmax then log, huge logits crash training into NaN, and tiny probabilities underflow log(0) = -inf. Try crashing and rescuing LogSumExp live below!

The Log-Sum-Exp Max-Shift Trick: Preventing Float32 NaN Crashes ForeverNaive log(Σ exp(z)) on z = [1000, 999]exp(1000) = +inf (Float32 max = 3.4e38)Loss = NaN → Training Crashes!Overflow starts as low as z > 88.7 in fp32!Max-Shifted LSE (m = max(z) = 1000)m + log(exp(0) + exp(−1))= 1000 + log(1.368) = 1000.31 ✓100% mathematically identical, zero overflow!
Log-Sum-Exp Max-Shift Trick: subtracting m = max(z) shifts the largest exponent to 0 (exp(0) = 1.0), eliminating float32 exp(1000) = inf/NaN crashes forever.

Exact Stable Identities (Used Inside PyTorch!)

  1. Multi-Class Cross-Entropy from Logits: LCE(z,y)=−zy+m+log⁡∑j=1Kezj−m⏟Stable Log-Sum-Exp,m=max⁡jzj\mathcal{L}_{\text{CE}}(\mathbf{z}, y) = -z_y + \underbrace{m + \log\sum_{j=1}^K e^{z_j - m}}_{\text{Stable Log-Sum-Exp}}, \qquad m = \max_j z_j
  2. Binary Cross-Entropy from Logits (BCEWithLogitsLoss): LBCE(z,y)=max⁡(z,0)−z⋅y+log⁡(1+e−∣z∣)\mathcal{L}_{\text{BCE}}(z, y) = \max(z, 0) - z\cdot y + \log\big(1 + e^{-|z|}\big) Notice exp(-|z|) ALWAYS has a non-positive exponent (≤ 0) — making overflow mathematically IMPOSSIBLE for any float from −10³⁸ to +10³⁸!
Mini-Lab • Float Overflow & Max-Shift Stability

Push Logits to z = [800, 799, 797] & Cure the NaN Crash

Computed LogSumExp:Infinity / NaN CRASH! (exp > 1.8e308)

2. Why Cross-Entropy Beats MSE for Classification: The Magic (p − y) Gradient

Everyday Story First (Zero Math Yet!)

Why does every classifier and LLM use Cross-Entropy instead of MSE? Because when you combine Softmax/Sigmoid with −log(p), the messy σ'(z) saturation term cancels out identically, leaving ∂L/∂z = p − y!

Cross-Entropy Loss −log(p_y): Infinite Penalty for Confident Mistakes!p = 0.01 → Loss = 4.61!p = 0.99 → 0.01The Magic Logit Gradient∂L / ∂z = p − yNo tiny σ'(z) saturation factor!Big mistake → big crisp gradient!
Cross-Entropy −log(p) punishes confident wrong predictions toward +∞ while yielding the remarkably clean gradient (p − y) with respect to raw logits!

One-Line Gradient Beauty

For both Binary (BCEWithLogitsLoss) and Multi-Class (CrossEntropyLoss), differentiating w.r.t. raw logits z\mathbf{z} gives: ∂L∂z=p−y\frac{\partial \mathcal{L}}{\partial \mathbf{z}} = \mathbf{p} - \mathbf{y}

  • Confident wrong guess (p=0.001,y=1p = 0.001, y = 1): gradient is −0.999-0.999 (maximum corrective force!).
  • Confident right guess (p=0.999,y=1p = 0.999, y = 1): gradient is −0.001-0.001 (leaves good weights alone!).

3. Focal Loss (Extreme Imbalance) & Label Smoothing (Overconfidence Cure)

Everyday Story First (Zero Math Yet!)

In object detection (RetinaNet / YOLO), an image has 100,000 easy background boxes and only 5 real objects. Even if each easy box has tiny CE loss 0.02, 100,000 × 0.02 = 2,000 completely overwhelms the 5 real objects! Focal Loss multiplies CE by (1 − p_t)^γ — crushing easy boxes by 100×!

Focal Loss −(1 − p_t)^γ log(p_t) vs. Label Smoothing (ε = 0.1)Easy zone (p_t > 0.7): crushed 100×!Focal Loss (γ = 2):Silences 10k easy background boxes!Label Smoothing (ε = 0.1):Target [1, 0, 0] → [0.93, 0.03, 0.03]Prevents overconfident logits in LLMs!
Focal Loss multiplies Cross-Entropy by (1 − p_t)^γ so 10,000 easy background examples contribute ~0 gradient while hard minority examples drive learning.

Two Essential Modern Upgrades

  1. Focal Loss: LFocal=−αt(1−pt)γlog⁡(pt)\mathcal{L}_{\text{Focal}} = -\alpha_t (1 - p_t)^\gamma \log(p_t) (standard γ=2\gamma = 2). When pt=0.9p_t = 0.9 (easy), (1−0.9)2=0.01(1 - 0.9)^2 = \mathbf{0.01} (100× smaller!). When pt=0.1p_t = 0.1 (hard), (1−0.1)2=0.81(1 - 0.1)^2 = \mathbf{0.81} (full focus!).
  2. Label Smoothing (ϵ=0.1\epsilon = 0.1): Replaces hard one-hot targets yk∈{0,1}y_k \in \{0, 1\} with: yksmooth=(1−ϵ)yk+ϵKy^{\text{smooth}}_k = (1 - \epsilon) y_k + \frac{\epsilon}{K} Why? Hard 1.0 targets force logits toward +∞+\infty (overfitting & terrible calibration!). Label smoothing bounds logits cleanly and improves both accuracy and calibration!
Pause & Check · Quick Intuition Pulse

With K = 5 classes and Label Smoothing ε = 0.10, what is the smoothed target vector for true Class 0?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

nn.CrossEntropyLoss expects integer class indices of shape (B,) and dtype torch.long (e.g., tensor([0, 2, 1])). nn.BCEWithLogitsLoss expects float targets 0.0 / 1.0 matching the exact shape of logits (dtype torch.float32)!

Interactive Visual Lab
Lab Challenge: In the Animated Classification Loss Stage below, crank Focal γ up from 0.0 to 3.0 and watch the easy-example loss curve (p_t > 0.7) collapse flat to 0 while hard errors keep full gradient!
Interactive Animation • Cross-Entropy vs. Focal Loss

Sweep Predicted Probability p_t (0.03 → 0.98): Watch Focal Loss Silence Easy Examples

CE = 3.51 | Focal = 3.299
-- Standard Cross-Entropy— Focal Loss (γ = 2.0)
0%
Hard Mistake (High Gradient!)
Intuition Takeaway: Always feed raw logits into Cross-Entropy / BCEWithLogitsLoss (which use Max-Shift Log-Sum-Exp stability and deliver the clean p − y gradient), add Focal Loss for severe imbalance, and add Label Smoothing to prevent overconfident logits!
Where This Powers Real ML, Deep Learning & Generative AI

LLM Pre-Training & SFT

Next-token Cross-Entropy over 128k vocabulary logits (with ignore_index=-100 for prompt masking).

RetinaNet & YOLOv8 Object Detection

Focal Loss solves 1000:1 background-vs-object imbalance during dense anchor training.

ImageNet Vision Classifiers

Cross-Entropy with label_smoothing=0.1 boosts Top-1 accuracy and probability calibration.

Multi-Label Medical Imaging

BCEWithLogitsLoss(pos_weight=...) handles rare co-occurring diagnoses cleanly.

Production NumPy & PyTorch Code Patterns
import torch
import torch.nn as nn
import torch.nn.functional as F

# 1. Numerically Stable Cross-Entropy with Label Smoothing from Scratch
def label_smoothing_ce_scratch(logits: torch.Tensor, targets: torch.Tensor, eps: float = 0.1) -> torch.Tensor:
    # logits: (B, K), targets: (B,) integer indices
    log_probs = logits - torch.logsumexp(logits, dim=-1, keepdim=True)  # stable LogSoftmax!
    nll = -log_probs.gather(dim=-1, index=targets.unsqueeze(-1)).squeeze(-1)
    smooth = -log_probs.mean(dim=-1)
    return ((1.0 - eps) * nll + eps * smooth).mean()

# 2. Idiomatic PyTorch Production Losses (ALWAYS pass raw logits!)
logits  = torch.randn(16, 10)
targets = torch.randint(0, 10, (16,))
ce_loss = nn.CrossEntropyLoss(label_smoothing=0.1)(logits, targets)
print("PyTorch CE:", round(ce_loss.item(), 4), "| Scratch:", round(label_smoothing_ce_scratch(logits, targets, 0.1).item(), 4))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Applying torch.sigmoid or F.softmax before BCEWithLogitsLoss or CrossEntropyLoss.
Best Practice: NEVER! Both losses fuse the activation internally via Log-Sum-Exp for numerical stability.
Trap #2: Passing float targets to nn.CrossEntropyLoss (for class indices) or long targets to BCEWithLogitsLoss.
Best Practice: CrossEntropyLoss indices = torch.long (B,); BCEWithLogitsLoss targets = torch.float matching logit shape.
Trap #3: Computing naive torch.log(torch.exp(z).sum()) in custom loss functions.
Best Practice: Always use torch.logsumexp or subtract z.max(dim=-1, keepdim=True).values!
Trap #4: Forgetting that Label Smoothing raises training loss slightly on purpose.
Best Practice: Minimum possible loss with ε > 0 is the entropy of the smoothed target, NOT 0.0 — check validation accuracy & calibration!
Chapter Mastery Check (+80 XP)
Score: 0 / 5
1What is the gradient ∂L/∂z of Softmax + Cross-Entropy with respect to raw logits z?
2What happens in Focal Loss −(1 − p_t)^γ log(p_t) when you set γ = 0?
3How does Label Smoothing regularize deep classifiers?
4If an LLM has average next-token Cross-Entropy of 1.5 nats, what is its Perplexity?
5Why should you NEVER put nn.Softmax() right before nn.CrossEntropyLoss()?

Apply What You Learned — Solve Matching Coding Problems