Topic 5 of 5 · 5 min read
Debugging shape errors and NaN losses
Goal: Locate the bug in a failing PyTorch script from its traceback or loss log and fix it.
Debug a PyTorch script by reading the traceback for the failing shape, device or value, then printing shapes and checking one batch, before changing any code.
Check yourself · 1 of 3
A traceback says mat1 and mat2 shapes cannot be multiplied (32x784 and 100x10). What does it mean?
Why it matters
PyTorch errors are specific, and most bugs fall into a short list. Agent-written code is usually syntactically clean, so the faults are the quiet kind: a wrong axis, a missing .eval(), a learning rate that is too high. A fixed routine finds them faster than guessing.
How to do it
- Read the traceback from the bottom. The last line names the problem:
mat1 and mat2 shapes cannot be multiplied (32x784 and 100x10)says a Linear layer expects 100 inputs but received 784. - Print shapes at each stage with a single batch:
print(x.shape, y.shape, model(x).shape). - Overfit one batch. Train on 8 examples for 100 steps. If the loss does not approach zero, the bug is in the model, loss or loop, not the data.
- Check devices and dtypes with
x.device,next(model.parameters()).deviceandx.dtype. - Hunt NaN. If the loss becomes
nan, lower the learning rate, check forlog(0)or division by zero, look for bad values in the data withtorch.isnan(x).any(), and consider gradient clipping withclip_grad_norm_.torch.autograd.set_detect_anomaly(True)points to the first operation that produced it, at a speed cost.
Before and after
A loss log from an assistant's script:
epoch 0 loss 2.31
epoch 1 loss 2.30
epoch 2 loss 2.30
A loss stuck near 2.30 on a 10-class problem is about ln(10), the loss of random guessing. The model is not learning. Overfitting one batch fails too, which points to the loop. The code has loss.backward() but never calls optimizer.step(). Adding the call fixes it.
What goes wrong
- Learning rate too high. Loss jumps to
infornanwithin a few steps. - Shape errors patched blindly. Adding
.view(-1)to make an error disappear can scramble batch and feature axes and hide a real bug. - Silent eval bug. Dropout left on in validation never raises an error, only noisy metrics.
- Moving the model after creating the optimizer. On some setups this leaves the optimizer holding stale parameter references; create the optimizer after
.to(device).
Examples
Reading a shape error
RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x784 and 100x10)
The batch has 32 rows of 784 features, but the last Linear layer was built for 100 inputs. Either the previous layer outputs 784 or its size was set wrong. Print the shape after each layer to find where 100 comes from.
Finding a NaN source
assert not torch.isnan(x).any(), "NaN in input batch"
loss = loss_fn(model(x), y)
if not torch.isfinite(loss):
print("bad loss", loss.item())
Checking the input first separates a data problem from a training problem. If the input is clean, lower the learning rate by 10 times and retry.
Key points
- Read a traceback from the last line, which names the shapes or devices that clash.
- Print shapes on a single batch before editing any code.
- Overfitting a handful of examples is the fastest test that the model, loss and loop can learn at all.
- A loss stuck near ln(number of classes) means the model is guessing and nothing is being learned.
- NaN losses usually come from a learning rate that is too high, log or division of zero, or bad values in the data.
Common mistakes
- Changing several things at once after an error instead of printing shapes and isolating one cause.
- Silencing a shape error with view or flatten without checking which axes get merged.
- Using the full dataset to debug instead of overfitting one small batch.
- Trusting that an assistant-written loop is complete because it runs, without checking for zero_grad, step and eval.
Check yourself · 2 of 3
A 10-class model's loss sits at about 2.30 for many epochs. What does that suggest?
Check yourself · 3 of 3
Your loss goes to nan after a few steps. What is a sensible first check?
Practice items, not counted towards your mastery.
Start here
- Learn the Basics (PyTorch tutorials) (opens in a new tab)DocsFree
Official end-to-end walk through tensors, datasets, models, autograd, optimization and saving.
- PyTorch tutorials: automatic differentiation with torch.autograd (opens in a new tab)DocsFree
Short, runnable explanation of requires_grad, backward and no_grad.
- PyTorch notes: autograd mechanics (opens in a new tab)DocsFree
How the graph is built and freed and how gradients accumulate.
More for this topic
- Neural Networks: Zero to Hero (Andrej Karpathy) (opens in a new tab)CourseFree
Video series that builds networks from scratch and shows how to read losses and debug training.