Loss Functions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A loss function turns predictions and targets into one scalar that autograd differentiates. The mathematics (maximum likelihood, cross-entropy, KL divergence, Huber) is derived in Loss Functions & Information Theory; the pairing of output layer and loss is summarized in Neural Network Fundamentals. This page is the PyTorch contract for each loss: whether it takes logits or probabilities, what shape and dtype the target must have, and how reduction, weight, ignore_index and label_smoothing interact. Most losses live in torch.nn as classes and in torch.nn.functional as functions.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31.
The loss catalogue
The 2.15 torch.nn page lists these losses: L1Loss, MSELoss, CrossEntropyLoss, LinearCrossEntropyLoss (new), CTCLoss, NLLLoss, PoissonNLLLoss, GaussianNLLLoss, KLDivLoss, BCELoss, BCEWithLogitsLoss, MarginRankingLoss, HingeEmbeddingLoss, MultiLabelMarginLoss, HuberLoss, SmoothL1Loss, SoftMarginLoss, MultiLabelSoftMarginLoss, CosineEmbeddingLoss, MultiMarginLoss, TripletMarginLoss and TripletMarginWithDistanceLoss.
| Task | Loss | Input and target |
|---|---|---|
Multi-class classification |
|
Raw logits |
Binary or multi-label classification |
|
Raw logits of any shape; float target of the same shape in \([0, 1]\) |
Regression |
|
Same shape and float dtype for input and target |
Probabilistic regression |
|
Mean (and variance) outputs; counts for Poisson |
Distribution matching, distillation |
|
Input is log-probabilities; target is probabilities (or log-probabilities with |
Sequence alignment without alignments |
|
Log-probabilities |
Metric learning, ranking |
|
Embeddings or scores, labels in \(\{-1, 1\}\) |
Reductions
Every loss has a reduction argument with the values none, mean (the default) and sum. none returns one value per element, which you need for per-sample weighting, masking, hard-example mining or logging the loss distribution. The arguments size_average and reduce are deprecated and, when set, override reduction; do not use them.
Cross-entropy
nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', label_smoothing=0.0) combines log_softmax and negative log-likelihood. Its contract is the most frequent source of bugs:
-
The input is raw logits. Do not apply softmax first; doing so squashes the gradients and trains poorly without any error.
-
Input shapes:
©,(N, C), or(N, C, d1, ..., dK)for per-pixel or per-token classification. Note that the class dimension is dimension 1, so language-model logits of shape(N, L, V)must be reshaped to(N * L, V)or permuted to(N, V, L). -
Class-index target:
longdtype, values in[0, C), shape(),(N)or(N, d1, ..., dK). Class-probability target: float, same shape as the input, values in \([0, 1]\); PyTorch does not check that they sum to one. Index targets are generally faster. -
weightis a 1-D tensor of lengthCrescaling each class, for imbalanced data. With index targets and'mean'reduction the sum is divided by the sum of the weights of the non-ignored targets, so the mean is a weighted mean and not simply divided byN. With probability targets'mean'divides byN. -
ignore_index(default -100) drops targets with that value from the loss and gradient; it only applies to index targets. Use it for padding tokens. If every target in a batch is ignored, the'mean'result is NaN. -
label_smoothingin \([0, 1]\) mixes the one-hot target with a uniform distribution, which tempers over-confident predictions. It is not the same as manually changing targets because it composes withweightandignore_index.
import torch
from torch import nn
logits = torch.randn(8, 5, requires_grad=True) # (N, C), no softmax
target = torch.randint(0, 5, (8,)) # class indices, long
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
loss = criterion(logits, target)
loss.backward()
# Class weights for an imbalanced dataset: weight by inverse frequency
counts = torch.bincount(target, minlength=5).clamp(min=1).float()
weights = counts.sum() / (5 * counts)
weighted = nn.CrossEntropyLoss(weight=weights)(logits, target)
# Language modelling: (N, L, V) logits and (N, L) targets, padding id 0 ignored
lm_logits = torch.randn(4, 12, 100, requires_grad=True)
lm_target = torch.randint(0, 100, (4, 12))
lm_target[:, 9:] = 0
lm_loss = nn.CrossEntropyLoss(ignore_index=0)(lm_logits.reshape(-1, 100), lm_target.reshape(-1))
# Soft targets (mixup, distillation): float probabilities with the same shape as the logits
soft = torch.softmax(torch.randn(8, 5), dim=-1)
soft_loss = nn.CrossEntropyLoss()(logits, soft)
nn.NLLLoss is the second half: it expects log-probabilities (the output of nn.LogSoftmax) and index targets, with the same weight, ignore_index and reduction semantics. A model that ends in LogSoftmax pairs with NLLLoss; a model that ends in raw logits pairs with CrossEntropyLoss. Mixing them (LogSoftmax followed by CrossEntropyLoss) is mathematically harmless but wasteful, while Softmax followed by either is a bug.
LinearCrossEntropyLoss (new in 2.15)
nn.LinearCrossEntropyLoss(in_features, num_classes, *, out_features=(), bias=False, device=None, dtype=None, reduction='mean', weight=None, ignore_index=None, label_smoothing=0.0, options=None) appears in the 2.15 documentation: it projects the input to logits with its own linear weight and computes the cross-entropy, with the purpose of letting the implementation chunk the computation so that the full (tokens, vocabulary) logits tensor need not be materialized for large vocabularies. The functional form is F.linear_cross_entropy. The options argument takes a LinearCrossEntropyOptions chunking configuration; passing it makes the module incompatible with torch.jit.script and imposes backward-pass restrictions described in the page’s warning. The documentation does not label the stability level of the API, so treat it as new and check the release notes before depending on it.
import torch
from torch import nn
loss_fn = nn.LinearCrossEntropyLoss(in_features=5, num_classes=10, out_features=(4, 3))
inp = torch.randn(2, 5, requires_grad=True)
target = torch.randint(0, 10, (2, 4, 3))
loss_fn(inp, target).backward()
The snippet is the example from the reference page. For the conventional large-vocabulary alternative today, keep nn.Linear plus CrossEntropyLoss and reduce memory with activation checkpointing or by computing the loss in chunks yourself.
Binary and multi-label classification
nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None) fuses the sigmoid with binary cross-entropy using the log-sum-exp trick, so it is numerically stable; nn.BCELoss expects probabilities that have already passed through a sigmoid and can produce infinities when a probability reaches exactly 0 or 1. Prefer the logits version. The target must be a float tensor of the same shape as the input; integer labels raise a dtype error.
pos_weight is a tensor with one entry per class that multiplies the positive term, so pos_weight = n_negative / n_positive balances rare positives. A multi-label problem uses the same loss with an (N, C) target of independent 0/1 labels. For a single binary output use the same shape, (N) or (N, 1), for both tensors.
import torch
from torch import nn
logits = torch.randn(16, 3, requires_grad=True) # 3 independent labels
labels = torch.randint(0, 2, (16, 3)).float()
pos_weight = ((1 - labels.mean(0)) / labels.mean(0).clamp(min=1e-6))
loss = nn.BCEWithLogitsLoss(pos_weight=pos_weight)(logits, labels)
loss.backward()
probs = torch.sigmoid(logits) # only for reporting
Regression losses
-
MSELosssquares the error: smooth, but dominated by outliers. -
L1Losstakes the absolute error: robust, with a constant gradient magnitude and a kink at zero. -
HuberLoss(delta=1.0)is quadratic belowdeltaand linear above it. -
SmoothL1Loss(beta=1.0)is the same idea with a different scaling: it equals Huber divided bybeta. The two coincide when the threshold is 1. -
GaussianNLLLosstrains a mean and a variance together, so the model reports its own uncertainty; the variance is passed as a second argument and clamped byeps. -
Broadcasting pitfall:
MSELosswarns when input and target shapes differ, because(N, 1)against(N)broadcasts to(N, N)and produces a wrong, plausible-looking loss. Make the shapes identical with.squeeze(-1).
import torch
from torch import nn
pred = torch.randn(32, 1, requires_grad=True)
y = torch.randn(32)
# wrong: (32, 1) against (32,) broadcasts to (32, 32)
# right: align the shapes first
loss = nn.HuberLoss(delta=1.0)(pred.squeeze(-1), y)
loss.backward()
KL divergence and distillation
nn.KLDivLoss(reduction='mean', log_target=False) expects the input as log-probabilities and the target as probabilities (log-probabilities if log_target=True). The default 'mean' averages over all elements, not over the batch, which is mathematically not the KL divergence; use reduction='batchmean' to obtain the standard value. Knowledge distillation therefore reads:
import torch
import torch.nn.functional as F
T = 2.0
student_logits = torch.randn(8, 10, requires_grad=True)
teacher_logits = torch.randn(8, 10)
loss = F.kl_div(
F.log_softmax(student_logits / T, dim=-1),
F.softmax(teacher_logits / T, dim=-1),
reduction="batchmean",
) * (T * T)
loss.backward()
CTC loss
nn.CTCLoss(blank=0, reduction='mean', zero_infinity=False) trains sequence models (speech and handwriting recognition) without frame-level alignments. forward(log_probs, targets, input_lengths, target_lengths) takes log-probabilities of shape (T, N, C) from log_softmax (class blank is the extra symbol), padded or concatenated integer targets and the true lengths of each sequence. Set zero_infinity=True when some inputs are shorter than their targets, which would otherwise give an infinite loss and NaN gradients. The CUDA implementation can have stricter input requirements than the CPU one; if results differ between devices, check the notes on the reference page (not re-checked here).
Writing your own loss
A loss is any differentiable function of tensors that returns a scalar. Writing it as an nn.Module allows constant configuration to be stored, while a plain function is enough for one-off use. Keep the computation in float32 when training in half precision (autocast already does this for the built-in losses; see Mixed Precision with torch.amp).
import torch
from torch import nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
"""Multi-class focal loss: down-weights easy examples."""
def __init__(self, gamma: float = 2.0, ignore_index: int = -100):
super().__init__()
self.gamma = gamma
self.ignore_index = ignore_index
def forward(self, logits: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
ce = F.cross_entropy(logits, target, ignore_index=self.ignore_index, reduction="none")
pt = torch.exp(-ce) # probability of the true class
loss = (1 - pt) ** self.gamma * ce
valid = target != self.ignore_index
return loss.sum() / valid.sum().clamp(min=1)
criterion = FocalLoss()
logits = torch.randn(8, 5, requires_grad=True)
target = torch.randint(0, 5, (8,))
criterion(logits, target).backward()
Check that a custom loss gives a finite value and gradient on a tiny batch, that it is zero (or minimal) on a perfect prediction, and that torch.autograd.gradcheck passes in float64 when it uses custom operations (see Custom autograd Functions).
Debugging a loss that does not decrease
-
Loss stuck near \(\ln C\): the model predicts uniformly; check learning rate, labels and that the data and targets are aligned.
-
NaN loss: look for
log(0)in a hand-written loss, an all-ignored batch with'mean', too large a learning rate, or overflow in half precision.torch.autograd.set_detect_anomaly(True)finds the operation (see Autograd Fundamentals). -
Loss decreases but accuracy does not: wrong target dtype or shape,
SoftmaxbeforeCrossEntropyLoss, or evaluation withoutmodel.eval(). -
Remember to call
optimizer.zero_grad(),loss.backward()andoptimizer.step()in the order covered in The Training Loop & Evaluation.