Skip to content
mentoor

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?

Choose one answer

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

  1. 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.
  2. Print shapes at each stage with a single batch: print(x.shape, y.shape, model(x).shape).
  3. 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.
  4. Check devices and dtypes with x.device, next(model.parameters()).device and x.dtype.
  5. Hunt NaN. If the loss becomes nan, lower the learning rate, check for log(0) or division by zero, look for bad values in the data with torch.isnan(x).any(), and consider gradient clipping with clip_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 inf or nan within 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?

Choose one answer

Check yourself · 3 of 3

Your loss goes to nan after a few steps. What is a sensible first check?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic