A margin-based replacement for cross-entropy loss

Michael W. Spratling, Heiko H. Schütt · Submission to ICLR 2026 · Rejected

TL;DR

Cross-entropy (CE) loss is the default objective for training deep classifiers, but its relentless pursuit of infinite confidence leads to severe overconfidence, catastrophic forgetting, and vulnerability to adversarial attacks. The authors introduce High Error Margin (HEM) loss, a generalized margin-based alternative that selectively focuses gradients on the highest-error logits. Across image classification, out-of-distribution detection, continual learning, and semantic segmentation, HEM matches or outperforms CE and domain-specialized losses while pruning unnecessary backpropagation updates.

What Problem Does This Paper Address?

While Cross-Entropy loss is ubiquitous, it suffers from several core structural flaws:

  1. Never-ending gradient updates: Even when a sample is correctly classified with 99.9% probability, CE loss is strictly positive. It constantly pushes correct logits toward $+\infty$ and incorrect logits toward $-\infty$. This leads to extreme overconfidence on unseen or out-of-distribution (OOD) data.
  2. Weight overwriting: Continuously modifying parameters for well-learned examples causes catastrophic forgetting in continual learning and washes out representations for minority classes in imbalanced data.
  3. Flaws in prior margin losses: Classical Multi-Class Margin (MM / hinge) loss stops updating when a margin is satisfied, but standard error averaging across all logits causes gradient magnitudes to collapse as most errors reach zero later in training, leading to premature stagnation.

While specialized losses exist for specific problems (e.g., LogitNorm for OOD detection, logit-adjusted loss for long-tailed data, DICE for segmentation), they typically fail outside their narrow niche. The paper asks: Can a single margin loss serve as a universal replacement for cross-entropy?

Methods

HEM builds upon the multi-class margin error. For a sample with ground-truth label $l$ and logit vector $y$, the error for logit $i$ is: $$e_i = \begin{cases} \max(0, y_i - y_l + \mu_i) & \text{if } i \neq l \\ 0 & \text{if } i = l \end{cases}$$

The fundamental novelty lies in how errors are aggregated:

  • Dynamic Thresholding: For each sample, HEM computes the mean error across all $n$ classes and zeros out any error falling below this mean: $e_i \ge \frac{1}{n}\sum_j e_j$. Crucially, the mean calculation is detached from the autograd computational graph.
  • Selective Mean: Instead of averaging across all $n$ classes, HEM computes the mean of only the remaining above-zero errors. At the batch level, samples with zero loss are similarly excluded from the batch mean.
  • Class-Dependent Margins:
  • Standard Shared Margin ($\text{HEM}^-$): $\mu = \sqrt{M / \sum s_i}$, where $s_i$ is the number of samples in class $i$, and $M$ is a fixed scaling hyperparameter ($M=2000$).
  • Adjusted Margin ($\text{HEM}$): To combat class imbalance, per-class margins are set inversely proportional to sample count: $\mu_i = \sqrt{M / (n s_i)}$.

Datasets

The authors conduct an extensive empirical study across 19 architectures (from LeNet and ResNet to Swin-T and ViT-B/16):

  • Balanced Image Classification: MNIST, CIFAR-10, CIFAR-100, TinyImageNet, and ImageNet-1k.
  • Robustness & Corruptions: Evaluated on MNIST-C, CIFAR-10-C, CIFAR-100-C, TinyImageNet-C, and ImageNet-C (15–18 corruption types across multiple severities).
  • Unknown Class / OOD Rejection: Evaluated against Omniglot, Fashion-MNIST, K-MNIST, DTD Textures, SVHN, iNaturalist 2021, ImageNet-O, and 4 synthetic datasets (random noise, blobs, pixel-shuffled, and phase-randomized images).
  • Adversarial Evaluation: AutoAttack ($l_\infty$ and $l_2$ norms) measured via Detection Accuracy Rate (DAR).
  • Long-Tailed / Imbalanced Data: CIFAR-10-LT (imbalance ratios 10 and 100), CIFAR-100-LT (ratios 10 and 100), and ImageNet-LT (imbalance ratio 256).
  • Continual Learning: PermutedMNIST, SplitMNIST, SplitCIFAR-10, SplitCIFAR-100 combined with five anti-forgetting strategies (Replay, SI, EWC, LFL, LwF).
  • Semantic Segmentation: CamVid, Cityscapes, SBD, and ADE20k evaluated using FPN across 4 distinct backbones.

Key Insights and Ideas

  • Preventing Gradient Collapse: In standard margin losses, as the network learns, 99% of logits hit zero error. Averaging over all classes shrinks the total gradient to near zero, leaving lingering errors uncorrected. HEM's adaptive thresholding and non-zero pooling ensures the gradient scale remains active and focused strictly on hard negatives.
  • Zero Loss Yields Free Compute Savings: Because HEM outputs zero loss once the margin is met, PyTorch's autograd can prune entire subgraphs during backprop. This reduced training wall-clock time by ~10% on TinyImageNet and ~4% on Cityscapes.
  • Margin Behavior Naturally Calibrates OOD: LogitNorm achieved state-of-the-art OOD rejection primarily because its temperature parameter forced margin-like behavior (stopping updates once logits separated). HEM achieves superior OOD rejection directly via its margin formulation without squashing feature representations.

Key Results

  • OOD Detection & Adversarial Defense: HEM beats CE in 14 of 15 standard dataset setups on OOD AUROC and outperforms CE in all 15 conditions on AutoAttack rejection (DAR). On CIFAR-100 (ResNet-18), DAR improves from 9.01% (CE) to 22.36% ($\text{HEM}^-$).
  • Continual Learning: HEM outperforms CE in 11 out of 16 tested continual learning scenarios. On SplitCIFAR-100 with EWC, test accuracy increased from 20.44% (CE) to 28.04% ($\text{HEM}^-$).
  • Semantic Segmentation: On Cityscapes, $\text{HEM}^-$ achieved ~80.0–82.3% mIoU across backbones compared to CE's ~63.2–67.2% mIoU. On ADE20k, $\text{HEM}^-$ reached ~41.5–43.0% mIoU compared to CE's ~11.8–12.8%.
  • Clean Accuracy Trade-off: Across 15 balanced image classification conditions, CE retains a modest 1.19% average advantage on clean accuracy. However, adjusting learning rates specifically for HEM (e.g., dropping initial LR on WRN22-10 from 0.1 to 0.05) eliminated this gap (raising clean accuracy from 94.73% to 95.32%).

Limitations and Future Work

  • Slight Drop in Clean Accuracy: When using training hyper-parameters tuned exclusively for CE, HEM experiences a minor penalty on clean, balanced image classification.
  • Margin Heuristics for Dense Prediction: While class-adjusted margins ($\mu_i$) helped long-tailed image classification, shared margin ($\text{HEM}^-$) outperformed adjusted HEM on semantic segmentation, indicating the inverse-frequency heuristic does not seamlessly transfer to pixel-level classification.
  • Domain Scope: Evaluation was restricted entirely to computer vision tasks; applicability to natural language processing and multimodal models remains untested.
  • Exploiting Zero-Loss Samples: The authors note that samples yielding zero loss could be adaptively augmented during training rather than merely skipped, potentially boosting generalization further.

Summary updated

Abstract

Cross-entropy (CE) loss is the de-facto standard for training deep neural networks (DNNs) to perform classification. Here, we propose an alternative loss, high error margin (HEM), that is more effective than CE across a range of image-based tasks: unknown class rejection, adversarial robustness, learning with imbalanced data, continual learning, and semantic segmentation (a pixel-wise classification task). HEM loss is evaluated extensively using a wide range of DNN architectures and benchmark datasets. Despite all the experimental settings, such as the training hyper-parameters, being chosen for CE loss, HEM is inferior to CE only in terms of clean and corrupt image classification with balanced training data, and this difference is small. We also compare HEM to specialised losses that have previously been proposed to improve performance for specific vision tasks. LogitNorm, a loss achieving state-of-the-art performance on unknown class rejection, produces similar performance to HEM for this task, but is much poorer for continual learning and semantic segmentation. Logit-adjusted loss, designed for imbalanced data, has superior results to HEM for that task, but performs worse on unknown class rejection and semantic segmentation. DICE, a popular loss for semantic segmentation, is inferior to HEM loss on all tasks, including semantic segmentation. Thus, HEM often out-performs specialised losses, and in contrast to them, is a general-purpose replacement for CE loss.
BibTeX
@misc{spratling2025margin,
  author = {Michael W. Spratling and Heiko H. Schütt},
  title = {{A margin-based replacement for cross-entropy loss}},
  year = {2025},
  eprint = {2501.12191},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2501.12191},
}

Loading related content...

Figure