Neural networks, deep learning, NLP · insight-0405
Feed raw logits to CrossEntropyLoss, never softmax outputs
- Evidence type
- documented fact
- Difficulty
- easy
- Roles
- Data scientist, ML engineer, Applied AI
- Industries
- cross-industry
Summary: situation, action, reason, boundary
Situation
A multi-class model ends in
nn.Softmaxand its output goes straight intonn.CrossEntropyLoss.Action
Return logits from
forward, pass them to the loss, and applysoftmaxonly in a separate predict function used for reporting, calibration and thresholds.Reason
PyTorch's cross-entropy expects unnormalized logits and applies log-softmax internally in a numerically stable way.
Boundary
PyTorch classification heads; check the equivalent contract in other frameworks, where some losses take a from-logits flag.
Symptom or risk
Softmax is applied twice. Gradients shrink, training is slow and plateaus early, and reported probabilities are squeezed towards uniform.
Exceptions
If you deliberately work in log-probabilities, use log_softmax with NLLLoss, which is equivalent.
Trade-offs
A predict wrapper adds a code path that must stay consistent with training and serving.
Pitfalls
Exporting the training forward to serving and reading logits as probabilities; thresholds tuned on probabilities then fail silently.
Lessons and concepts
Claims and their sources
PyTorch CrossEntropyLoss expects its input to contain unnormalized logits for each class.