PyTorch CrossEntropyLoss: Should You Apply Softmax First?
Pass raw logits to PyTorch CrossEntropyLoss. A runnable example shows why applying softmax first changes the loss and gradient even when the predicted class stays the same.
Pass raw logits directly to PyTorch CrossEntropyLoss. For a batch of B examples and C classes, the usual inputs are logits of shape [B, C] and integer class labels of shape [B]. The loss applies log-softmax to the scores internally. If you apply softmax first, PyTorch treats those probabilities as a new set of scores, changing both the loss and the gradient. Compute softmax separately when you need predicted probabilities.
Match the loss function to what your model returns
Read the line immediately before the loss. If the model already returns raw class scores, pass them straight to torch.nn.CrossEntropyLoss or its functional equivalent, F.cross_entropy. The class scores can be negative and their sum can be anything. With one correct class per example, use integer class indices such as [2, 0, 1] as the target for three examples.
A second target format supports soft labels, such as a probability distribution supplied by another model. In that case the target can have shape [B, C]. That option changes what goes on the target side. The predicted input to CrossEntropyLoss still consists of raw logits.
Source: PyTorch CrossEntropyLoss: Inputs, targets, and reduction ↗
Run a three-class example with both loss calls
Imagine a classifier gives one item scores of 4, 1, and −2 and its correct class is 0. The intended loss uses the log probability of class 0 after normalizing those scores. Class 0 gets probability about 0.9503, producing a loss of about 0.05095.
The extra-softmax branch still predicts class 0 because softmax preserves the order of the scores in this example. Its loss call receives roughly [0.9503, 0.0473, 0.0024] and normalizes again. Class 0 now gets about 0.5578 in the loss calculation. The code prints the loss and the gradient with respect to the original class-0 logit. Accuracy alone would miss the difference.
import torch
import torch.nn.functional as F
logits = torch.tensor([[4.0, 1.0, -2.0]], requires_grad=True)
target = torch.tensor([0], dtype=torch.long)
correct = F.cross_entropy(logits, target)
probabilities = logits.softmax(dim=1)
extra_softmax = F.cross_entropy(probabilities, target)
print(logits.argmax(dim=1).item(), probabilities.argmax(dim=1).item()) # 0 0
print(f"{correct.item():.5f}", f"{extra_softmax.item():.5f}") # 0.05095 0.58382
for loss in (correct, extra_softmax):
gradient, = torch.autograd.grad(loss, logits)
print(f"{gradient[0, 0].item():.5f}") # -0.04967, then -0.03152Check for an extra softmax when loss stalls
For this three-class, unweighted example with a hard label, there is a useful clue. Even the limiting case of a first softmax giving [1, 0, 0] would give the correct class only e/(e + 2) after the second normalization. The resulting loss is about 0.55144. A confident correct prediction can therefore retain a sizable loss. Treat this figure as a diagnostic for these specific settings.
To investigate your own loop, capture one batch immediately before the loss call. Trace the classifier’s return value and look for a softmax in the model head, the training step, or a wrapper. Scores summing to one can be a clue. Inspect the code to establish where normalization actually happened.
Source: PyTorch CrossEntropyLoss: Inputs, targets, and reduction ↗
Decide which training line belongs in the loop
Suppose a code question offers three choices: pass the logits directly to cross-entropy, apply softmax first, or detach the logits before computing the loss. The direct call uses the intended objective and preserves the gradient path. The extra softmax changes the objective. Detach cuts the path back to the classifier. If a different loop explicitly uses NLLLoss, feed it log-probabilities from log_softmax instead.
To try the same decision in a different training loop, open the free PTCA sample below and choose Study mode. One of its five code questions asks which loss line preserves the intended multiclass objective and lets gradients reach the model. Trace what enters the loss before checking the explanation.
Your next steps
- Feed raw model scores to CrossEntropyLoss, even when the target consists of soft labels.
- Compare loss and gradients when debugging an unexpected softmax. The predicted class can stay the same.
- Keep the probability calculation separate when returning scores for inference or reporting.
Sources & official resources
Linked resources checked on 2026-11-23. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →