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.
Cross-Entropy trains EVERY image classifier AND EVERY Large Language Model (predicting next tokens across 128k classes)!
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.
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!
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!'
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?
- 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
BCEWithLogitsLossandCrossEntropyLossMUST 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
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
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!
Exact Stable Identities (Used Inside PyTorch!)
- Multi-Class Cross-Entropy from Logits:
- Binary Cross-Entropy from Logits (
BCEWithLogitsLoss): Noticeexp(-|z|)ALWAYS has a non-positive exponent (≤ 0) — making overflow mathematically IMPOSSIBLE for any float from−10³⁸to+10³⁸!
Push Logits to z = [800, 799, 797] & Cure the NaN Crash
2. Why Cross-Entropy Beats MSE for Classification: The Magic (p − y) Gradient
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!
One-Line Gradient Beauty
For both Binary (BCEWithLogitsLoss) and Multi-Class (CrossEntropyLoss), differentiating w.r.t. raw logits gives:
- Confident wrong guess (): gradient is (maximum corrective force!).
- Confident right guess (): gradient is (leaves good weights alone!).
3. Focal Loss (Extreme Imbalance) & Label Smoothing (Overconfidence Cure)
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×!
Two Essential Modern Upgrades
- Focal Loss: (standard ). When (easy), (100× smaller!). When (hard), (full focus!).
- Label Smoothing (): Replaces hard one-hot targets with: Why? Hard 1.0 targets force logits toward (overfitting & terrible calibration!). Label smoothing bounds logits cleanly and improves both accuracy and calibration!
With K = 5 classes and Label Smoothing ε = 0.10, what is the smoothed target vector for true Class 0?
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)!
Sweep Predicted Probability p_t (0.03 → 0.98): Watch Focal Loss Silence Easy Examples
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.
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))
torch.sigmoid or F.softmax before BCEWithLogitsLoss or CrossEntropyLoss.float targets to nn.CrossEntropyLoss (for class indices) or long targets to BCEWithLogitsLoss.CrossEntropyLoss indices = torch.long (B,); BCEWithLogitsLoss targets = torch.float matching logit shape.torch.log(torch.exp(z).sum()) in custom loss functions.torch.logsumexp or subtract z.max(dim=-1, keepdim=True).values!nn.Softmax() right before nn.CrossEntropyLoss()?