Why Deep Learning Loss Turns to NaN—and How to Fix It
Résumé
Pixel’s announcement explores how manually combining softmax and log can cause underflow, negative infinity, and NaN during deep learning training. It connects the debugging lesson to the KI-Campus Foundations of Deep Learning micro-degree and the value of a classic textbook for understanding MLPs, backpropagation, and SGD.
DEV Community
My Loss Went NaN, and a 2016 Textbook Explained Why
Every deep learning journey has the same plot twist: the loss curve goes flat, or worse, turns into NaN at epoch 3 like it just discovered nihilism. The framework error says nothing useful. Stack Overflow says "lower your learning rate." You lower it by 10x. Nothing changes—now it just reaches NaN with more dignity. The first time this happened to me, I had written a custom classification loop where I manually applied torch.softmax() at the end of forward() and then fed the probabilities into torch.log() inside my own cross-entropy function. On clean toy inputs, it looked fine. On a real batch with one wildly confident misprediction (a logit gap over 104 in float32), the target class probability underflowed past IEEE 754 subnormals straight to 0.0, torch.log(0.0) returned -inf, and the backward pass cheerfully multiplied -inf * 0.0 into NaN across the network. I spent two hours blaming my learning rate scheduler before realizing I had reinvented numerical instability from scratch. I am currently working through the Foundations of Deep Learning micro-degree on KI-Campus. The resource that has turned its lectures into real intuition is, surprisingly, a 2016 book: Deep Learning by Ian Goodfellow, Yoshua Bengio, and Aaron Courville. It predates Transformers as we know them, yet I use it less as a cover-to-cover textbook and more as a debugging manual. Why a 2016 book next to a modern course? Courses give you structure, deadlines, and graded checkpoints. But a 10-minute lecture video has to compress derivations to fit the clock. When a slide skips three algebraic steps and expects you to nod along, you need a reference that explains things from first principles—ideally one that is freely readable online. The KI-Campus micro-degree is split into three courses (~36 hours total), and they map remarkably well to the book: KI-Campus Course Topics Book Chapters I: Basics Math prereqs, MLPs, backprop, SGD/Adam, regularization Ch. 2–8 II: Architectures & Methodology CNNs, RNNs/LSTMs, Transformers, transfer learning, debugging Ch. 9–11, 15 III: Advanced Topics Autoencoders, VAEs, GANs, diffusion, VI, MCMC, HPO Ch. 11, 14, 17, 19–20 The cheat sheet: symptom → chapter → PyTorch fix Instead of reading the book front to back, I look up whatever is currently on fire. Here is the quick-reference table, followed by the exact PyTorch patterns each chapter explains. Your symptom Look here The idea that helps Loss becomes NaN Ch. 4 Finite-precision floats: overflow, underflow, and log-sum-exp stability Training is painfully slow or oscillates Ch. 4, 8 Ill-conditioning, momentum, adaptive optimizers, batch normalization Great train accuracy, bad test accuracy Ch. 5, 7 Optimization ≠ learning: you are minimizing a surrogate on finite data "Why cross-entropy and not MSE?" Ch. 3, 5, 6 Cross-entropy is maximum likelihood (minimizing KL divergence) RNN forgets everything or explodes Ch. 10 Repeated Jacobian multiplication → vanishing/exploding gradients "I don't know what to try next" Ch. 11 Baseline first, overfit a micro-batch, change one variable at a time VAEs feel like black magic Ch. 19–20 ELBO and the reparameterization trick 1. Loss becomes NaN (Chapter 4: Numerical Computation) Chapter 4 explains why float32 is not real-number arithmetic: exp(89) overflows to inf, and exp(-104) underflows past the smallest float32 subnormal (1.4e-45) to 0.0. Even though torch.softmax shifts by max(z) internally to prevent overflow, computing torch.log(torch.softmax(z)) in two separate steps still underflows to 0.0 whenever a wrong class logit beats the target class logit by 104 or more. Fusing the log and the softmax via log-sum-exp keeps the math in log-space from start to finish: import torch
import torch.nn.functional as F
Class 0 logit is 105.0; true target (Class 1) logit is 0.0 -> gap of 105
logits = torch.tensor([[105.0, 0.0, 0.0]], requires_grad=True)
targets = torch.tensor([1])
❌ Fragile: exp(0 - 105) underflows to 0.0 in float32 -> log(0.0) = i...

Powered by Readybot.io