Debugging a Network That Will Not Learn
A network that does not learn rarely crashes. It runs, prints a loss, and the loss stays at 2.30, or creeps down slowly, or turns into nan at step 4000, or reaches 99 % training accuracy and 10 % on validation. Deep-learning bugs are mostly silent: the code is valid, the shapes broadcast, and the optimizer faithfully minimises the wrong thing. The defence is a fixed routine of cheap checks that each rule out one class of bugs, run in an order where every check relies on the ones before it. This lesson is that routine, each step with a demonstration on the course's Digits split (1077 training and 360 validation images, 10 classes).
| Step | Check | Rules out |
|---|---|---|
| 1 | loss at initialisation is about | wrong loss, wrong labels, broken output layer, bad init scale |
| 2 | the model can overfit one small batch | bugs in forward, backward, optimizer wiring |
| 3 | gradients match finite differences (custom code only) | wrong hand-written backward |
| 4 | gradient and activation norms per layer are sensible | vanishing or exploding signals, dead units |
| 5 | learning rate from a range test | a learning rate far too small or too large |
| 6 | no nan / inf, and where they first appear |
numerical overflow, log of zero, division by zero |
| 7 | the usual suspects | the bugs in the last section |
1. The loss at initialisation
A freshly initialised classifier knows nothing, so its predicted distribution should be close to uniform over the classes: . The cross-entropy of the true class is then
which is for ten classes and for a binary problem. A starting loss far above means the network starts out confidently wrong, typically because the logits are too large (weights initialised with too much variance, inputs not scaled); the first hundreds of steps are then spent undoing the overconfidence. A starting loss far below before any training means information leaks: labels in the inputs, or the loss computed on the wrong tensors. (For imbalanced classes the sensible starting value is the entropy of the class frequencies, reached by setting the last bias to the log class frequencies.)
The check also comes with a free gradient check of the output layer. For softmax with cross-entropy the gradient of the mean loss over examples with respect to the logits is , derived in softmax and cross-entropy gradient; compared with central differences
it should agree to a relative error around or better in float64 (gradient checking has the details). In NumPy, for softmax regression:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
def loss_and_grad(W, b, X, y):
z = X @ W + b
z = z - z.max(axis=1, keepdims=True)
p = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True)
loss = -np.log(p[np.arange(len(y)), y]).mean()
p[np.arange(len(y)), y] -= 1 # softmax minus one-hot
return loss, X.T @ p / len(y), p.mean(axis=0)
rng = np.random.default_rng(0)
for scale in (0.01, 1.0, 5.0):
W = rng.normal(0, scale, (64, 10))
print(f"init scale {scale:4}: loss {loss_and_grad(W, np.zeros(10), X_tr, y_tr)[0]:.3f} ln 10 = {np.log(10):.3f}")
# gradient check: analytic dL/dW against central differences on a few entries
W, b = rng.normal(0, 0.1, (64, 10)), np.zeros(10)
_, gW, _ = loss_and_grad(W, b, X_tr[:50], y_tr[:50])
h, worst = 1e-5, 0.0
for i, j in [(10, 0), (20, 3), (36, 7), (60, 9)]:
E = np.zeros_like(W); E[i, j] = h
num = (loss_and_grad(W + E, b, X_tr[:50], y_tr[:50])[0] - loss_and_grad(W - E, b, X_tr[:50], y_tr[:50])[0]) / (2 * h)
rel = abs(num - gW[i, j]) / max(abs(num) + abs(gW[i, j]), 1e-12)
worst = max(worst, rel)
print(f"W[{i},{j}]: analytic {gW[i, j]: .6f} numerical {num: .6f}")
print("largest relative error below 1e-6:", worst < 1e-6)init scale 0.01: loss 2.305 ln 10 = 2.303
init scale 1.0: loss 6.130 ln 10 = 2.303
init scale 5.0: loss 32.237 ln 10 = 2.303
W[10,0]: analytic -0.023131 numerical -0.023131
W[20,3]: analytic -0.075585 numerical -0.075585
W[36,7]: analytic -0.067046 numerical -0.067046
W[60,9]: analytic 0.064225 numerical 0.064225
largest relative error below 1e-6: True
With weights of standard deviation 0.01 the starting loss is 2.305, practically . With standard deviation 1 it is 6.130, and with 5 it is 32.237: the same model, just confidently wrong from the start. The analytic gradient matches the numerical one to six decimals on every entry checked.
2. Overfit one batch, then check autograd
A model with 9 610 parameters must be able to memorise 32 examples. If it cannot drive the loss on a single fixed batch to nearly zero, something between the input and the optimizer is broken (a detached tensor, a frozen layer, the optimizer built on the wrong parameters, a missing zero_grad), and no amount of tuning will help. PyTorch's torch.autograd.gradcheck performs step 3 for custom functions and layers: it compares autograd's gradient with finite differences, in float64.
import math
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
Xt, yt = torch.tensor(X_tr, dtype=torch.float32), torch.tensor(y_tr)
def mlp(seed=0):
torch.manual_seed(seed)
return nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
loss_fn = nn.CrossEntropyLoss()
model = mlp()
with torch.no_grad():
print(f"1. loss at init {loss_fn(model(Xt), yt).item():.3f} vs ln 10 = {math.log(10):.3f}")
bad = mlp(); bad[2].weight.mul_(30)
print(f" overconfident init (last layer x30): {loss_fn(bad(Xt), yt).item():.3f}")
xb, yb = Xt[:32], yt[:32]
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for step in range(1, 101):
loss = loss_fn(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
if step in (1, 25, 100):
print(f"2. one batch of 32, step {step:3d}: loss {loss.item():.4f}")
def f(w, x):
return torch.tanh(x @ w).pow(2).sum()
w = torch.randn(5, 3, dtype=torch.float64, requires_grad=True)
xx = torch.randn(4, 5, dtype=torch.float64)
print("3. gradcheck (float64):", torch.autograd.gradcheck(lambda w: f(w, xx), (w,)))1. loss at init 2.309 vs ln 10 = 2.303
overconfident init (last layer x30): 5.150
2. one batch of 32, step 1: loss 2.3103
2. one batch of 32, step 25: loss 0.0088
2. one batch of 32, step 100: loss 0.0003
3. gradcheck (float64): True
The PyTorch MLP starts at 2.309 against , while the same network with its last layer multiplied by 30 starts at 5.150. On one batch of 32 images, Adam brings the loss from 2.3103 to 0.0088 in 25 steps and 0.0003 in 100: the whole pipeline can learn. gradcheck returns True for a small custom function. With these three checks passed, the remaining problems are about how well the network learns, not whether it can.
3. Watch gradients and activations per layer
The global loss hides which layer is in trouble. Hooks report each layer's activation spread during the forward pass, and the gradient norm per weight matrix after backward() shows where the learning signal dies. The example compares eight hidden layers with sigmoid and with ReLU, PyTorch's default initialisation, one full-batch backward pass.
import math
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
Xt, yt = torch.tensor(X_tr, dtype=torch.float32), torch.tensor(y_tr)
def deep(act, seed=0, depth=8):
torch.manual_seed(seed)
layers, d = [], 64
for _ in range(depth):
layers += [nn.Linear(d, 64), act()]
return nn.Sequential(*layers, nn.Linear(64, 10))
for act in (nn.Sigmoid, nn.ReLU):
model = deep(act)
act_std = {}
hooks = [m.register_forward_hook(lambda m, i, o, k=k: act_std.__setitem__(k, o.std().item()))
for k, m in enumerate(model) if isinstance(m, act)]
nn.functional.cross_entropy(model(Xt), yt).backward()
g = [model[k].weight.grad.norm().item() for k in range(0, 17, 2)]
print(f"{act.__name__:7s} grad norm per Linear (first -> last):", " ".join(f"{v:.0e}" for v in g))
print(f"{'':7s} activation std per layer:", " ".join(f"{v:.2f}" for v in act_std.values()))
for h in hooks:
h.remove()Sigmoid grad norm per Linear (first -> last): 1e-07 3e-07 3e-06 2e-05 1e-04 9e-04 7e-03 5e-02 3e-01
activation std per layer: 0.07 0.07 0.08 0.08 0.07 0.06 0.07 0.07
ReLU grad norm per Linear (first -> last): 4e-04 4e-04 4e-04 5e-04 6e-04 9e-04 2e-03 4e-03 9e-03
activation std per layer: 0.16 0.08 0.05 0.05 0.05 0.04 0.05 0.04
With sigmoids, the gradient norm drops by about six orders of magnitude from the last weight matrix () to the first (): each sigmoid multiplies the backward signal by at most its largest slope, , and eight of them in a row leave almost nothing. The first layers would barely move. With ReLU the decay is far milder, from to , but the activation spread still shrinks from 0.16 to about 0.04 across the layers: PyTorch's default initialisation is slightly too small for deep ReLU stacks. Both effects, and their cures, are the subject of vanishing and exploding gradients and weight initialisation in practice. As a rule of thumb, gradient norms that differ across layers by more than a factor of 100 or so, activations that collapse towards 0, or a large share of ReLUs that output 0 for every example (dead units) all deserve a look.
4. Find the learning rate
The learning rate is the hyperparameter most likely to be wrong by a factor of ten. Too small and training crawls; too large and the loss oscillates or explodes. On the narrow valley of the lab below, plain gradient descent is stable only for ; the lab starts at , just above the limit. Watch the path zig-zag ever wider until the lab reports that the loss is diverging, then lower the slider below 0.2.
A real network has no formula for its , so measure instead. The learning-rate range test trains for a short while with a learning rate that grows exponentially from tiny to huge, , records a smoothed loss, and stops when the loss explodes. A good learning rate lies somewhat below the point of the lowest loss, often taken as about a tenth of it.
import math
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
ds = TensorDataset(torch.tensor(X_tr, dtype=torch.float32), torch.tensor(y_tr))
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
opt = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
loader = DataLoader(ds, batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(0))
lr_min, lr_max, steps = 1e-4, 10.0, 100
gamma = (lr_max / lr_min) ** (1 / (steps - 1))
lrs, losses, smooth, it = [], [], None, iter(loader)
for k in range(steps):
lr = lr_min * gamma ** k
for g in opt.param_groups:
g["lr"] = lr
try:
xb, yb = next(it)
except StopIteration:
it = iter(loader); xb, yb = next(it)
loss = nn.functional.cross_entropy(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
smooth = loss.item() if smooth is None else 0.8 * smooth + 0.2 * loss.item()
lrs.append(lr); losses.append(smooth)
if not math.isfinite(smooth) or smooth > 4 * min(losses):
break
for k in range(0, len(lrs), 10):
print(f"lr {lrs[k]:.1e} smoothed loss {losses[k]:.3f}")
best = min(range(len(losses)), key=losses.__getitem__)
print(f"stopped at step {len(lrs)} (lr {lrs[-1]:.1e}); lowest loss at lr {lrs[best]:.1e} -> try about {lrs[best] / 10:.1e}")lr 1.0e-04 smoothed loss 2.271
lr 3.2e-04 smoothed loss 2.309
lr 1.0e-03 smoothed loss 2.302
lr 3.3e-03 smoothed loss 2.297
lr 1.0e-02 smoothed loss 2.269
lr 3.4e-02 smoothed loss 2.153
lr 1.1e-01 smoothed loss 1.735
lr 3.4e-01 smoothed loss 0.776
lr 1.1e+00 smoothed loss 1.738
stopped at step 87 (lr 2.2e+00); lowest loss at lr 5.5e-01 -> try about 5.5e-02
Up to about the loss hardly moves from 2.3: those rates are too small to matter in a few dozen steps. It falls fastest between about and , reaches its lowest smoothed value at , and blows up beyond 1, so the test stopped at step 87 with . The suggestion of about 0.055 for SGD with momentum 0.9 is a starting point to confirm on validation, not a final answer, and the test is a few seconds of work instead of a grid search. (With Adam the same procedure applies; the numbers come out much smaller.)
5. NaN and inf
A nan loss usually comes from log(0), a division by zero, the square root of zero in a backward pass, or overflow in exp. Once one nan appears it spreads through every later operation, so the question is where it first appeared. Three tools:
torch.isfinite(t).all()as an assertion on the loss, or in a forward hook on every module;torch.autograd.set_detect_anomaly(True)(slow: debugging only) makes backward check every function's output and, when one returnsnan, raises an error naming that function and prints the traceback of the forward line that created it;- the stable formulations:
log_softmaxinstead oflog(softmax(...)),BCEWithLogitsLossinstead of a sigmoid followed byBCELoss, an inside square roots and denominators (overflow and softmax).
import warnings
import torch
from torch import nn
x = torch.tensor([1.0, 0.0, 2.0], requires_grad=True)
print("finite:", torch.isfinite(torch.log(x)).tolist()) # log(0) = -inf
with warnings.catch_warnings(record=True) as caught, torch.autograd.set_detect_anomaly(True):
warnings.simplefilter("always")
try:
(torch.sqrt(x) * 0).sum().backward() # d sqrt(x)/dx at 0 is inf, and inf * 0 = nan
except RuntimeError as e:
print("RuntimeError:", e)
print("anomaly mode also names the forward line:", str(caught[0].message).splitlines()[0])
model = nn.Linear(3, 2)
def check_finite(module, inputs, output):
if not torch.isfinite(output).all():
raise FloatingPointError(f"non-finite output in {module.__class__.__name__}")
model.register_forward_hook(check_finite)
try:
model(torch.tensor([[1.0, float("inf"), 0.0]]))
except FloatingPointError as e:
print("FloatingPointError:", e)
torch.manual_seed(0)
logits = torch.randn(4, 10)
for name, target in [("float labels", torch.tensor([1.0, 2.0, 3.0, 4.0])),
("shape (N, 1)", torch.tensor([[1], [2], [3], [4]]))]:
try:
nn.functional.cross_entropy(logits, target)
except RuntimeError as e:
print(f"{name}: RuntimeError: {e}")finite: [True, False, True]
RuntimeError: Function 'SqrtBackward0' returned nan values in its 0th output.
anomaly mode also names the forward line: Error detected in SqrtBackward0. Traceback of forward call that caused the error:
FloatingPointError: non-finite output in Linear
float labels: RuntimeError: expected target dtype to be Long or Byte, but got Float
shape (N, 1): RuntimeError: 0D or 1D target tensor expected, multi-target not supported
The derivative of at 0 is infinite, and infinity times the zero coming from the * 0 is nan: anomaly mode stops at SqrtBackward0 and its warning starts with the traceback of the forward call. The forward hook catches an inf input at the first module it passes. The last two lines are the errors you get for labels in the wrong form: cross-entropy wants int64 class indices of shape .
6. The usual suspects
Each of these bugs trains without an error message. The same MLP, 10 epochs of SGD with momentum, with one bug at a time:
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
T = lambda a: torch.tensor(a, dtype=torch.float32)
Xv, yv = T(X_va), torch.tensor(y_va)
def run(bug=None, epochs=10):
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
if bug == "softmax":
model.append(nn.Softmax(dim=1))
feats, labels = X_tr, y_tr.copy()
if bug == "sorted":
order = labels.argsort(kind="stable") # all 0s, then all 1s, ...
feats, labels = feats[order], labels[order]
if bug == "misaligned":
labels = labels[torch.randperm(len(labels)).numpy()] # X and y shuffled separately
ds = TensorDataset(T(feats), torch.tensor(labels))
loader = DataLoader(ds, batch_size=32, shuffle=(bug != "sorted"), generator=torch.Generator().manual_seed(0))
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
for _ in range(epochs):
for xb, yb in loader:
loss = nn.functional.cross_entropy(model(xb), yb)
if bug != "no_zero_grad":
opt.zero_grad()
loss.backward(); opt.step()
with torch.no_grad():
out = model(Xv)
pred = out.argmax(1)
return nn.functional.cross_entropy(out, yv).item(), (pred == yv).float().mean().item(), pred.unique().numel()
for bug in (None, "softmax", "no_zero_grad", "misaligned", "sorted"):
loss, acc, k = run(bug)
print(f"{str(bug):13s} val loss {loss:.3f} val acc {acc:.3f} classes predicted {k}")None val loss 0.121 val acc 0.975 classes predicted 10
softmax val loss 1.600 val acc 0.869 classes predicted 9
no_zero_grad val loss 894.876 val acc 0.108 classes predicted 2
misaligned val loss 2.418 val acc 0.119 classes predicted 9
sorted val loss 2.399 val acc 0.100 classes predicted 1
| Bug | Symptom in the run | Fix |
|---|---|---|
| none | val loss 0.121, accuracy 0.975 | |
softmax before CrossEntropyLoss |
loss stuck high (1.600) although accuracy is 0.869: the loss applies its own log-softmax, so the model's probabilities are treated as logits and the gradients are squashed | return logits; the loss does the softmax |
no optimizer.zero_grad() |
gradients add up over all steps; the effective step keeps growing and training diverges (val loss 894.876, accuracy 0.108, chance level, only 2 classes ever predicted) | zero every step, or accumulate deliberately |
| labels shuffled separately from inputs | accuracy 0.119, about chance: there is nothing to learn, the network can only memorise | shuffle indices, never X and y separately |
| data sorted by class, no shuffling | accuracy 0.100: each run of batches teaches one class, and the final model predicts a single class for all 360 images | shuffle=True for training |
Other regulars that this demo does not show: forgetting model.eval() for validation (dropout makes scores noisy and too low, batch norm updates its statistics on validation data), forgetting model.train() afterwards, preprocessing fitted on all data instead of the training split (data leakage), different preprocessing at training and serving time, and augmentation that changes the label (a horizontal flip turns a 2 into something else).
Pitfalls
- Tuning before checking. If the model cannot overfit one batch, hyperparameters are not the problem.
- Trusting the training loss alone. A falling loss with chance-level validation accuracy points at misaligned labels, leakage or a train/validation preprocessing mismatch.
- Leaving
set_detect_anomaly(True)on. It slows training a lot; use it to locate the problem, then switch it off. - Running
gradcheckin float32. Finite differences need float64 to be meaningful. - Changing several things at once. Each check above isolates one cause; change one thing, rerun, compare.
Practice
- A 5-class classifier starts at a loss of 1.61 and a 100-class one at 9.8. Which one has a problem?
Answer
, so the first is fine. , so the second starts far too high: its logits are too large at initialisation (too large weights, unscaled inputs), or the loss is wrong.
- A model overfits one batch of 32 easily, the training loss on the full data falls steadily, but validation accuracy stays at chance. Name two likely causes and a quick test for each.
Answer
Labels misaligned with the inputs (check a few examples by eye: show an image with its label) and a preprocessing difference between training and validation (compare feature means and ranges of both after preprocessing). Leakage in the other direction cannot cause chance-level validation; a validation set from a different distribution can, so check how it was built.
- In the range test, why does the loss barely change for , and why is the suggested learning rate below the one with the lowest loss?
Answer
With tiny learning rates and only a few steps at each value, the weights hardly move, so the loss stays near its initial value. At the lowest-loss point the learning rate is already close to the unstable region (the loss rises right after it); training for many epochs at that rate tends to oscillate, so a value about ten times smaller is a safer start.
Test yourself
A 10-class classifier at initialisation should have a cross-entropy loss of about
- 0
- 1
- 10
Your model cannot get the loss on one fixed batch of 32 examples near zero. What does that indicate?
- The learning-rate schedule is too short
- A bug in the model, the backward pass or the optimizer wiring
- The data set is too small
- Overfitting
In the eight-layer sigmoid network, the first layer's gradient norm was about and the last layer's about . What is this?
- Exploding gradients
- Vanishing gradients: each sigmoid scales the backward signal by at most
- A bug in the hooks
- Overfitting
Why does putting nn.Softmax before nn.CrossEntropyLoss hurt training?
- It raises an error
- The loss applies log-softmax itself, so probabilities in are treated as logits and the gradients become very small
- It makes predictions wrong at test time
- It doubles memory use