LearnQuestion bank

Name the most common silent bugs in PyTorch training code and how you would detect each one.

ResearchTechnicalMedium

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Softmax over the wrong dimension: assert logits shape and use the correct dim; unit-test against a hand-computed reference.
  • Probabilities passed to CrossEntropyLoss: feed raw logits; verify loss matches manual log_softmax + NLL and decreases on a tiny batch.
  • Missing zero_grad: call optimizer.zero_grad(set_to_none=True) each step; check one fresh-grad step matches the accumulated path and grad norms behave.
  • Forgetting eval(): use model.eval() and no_grad for validation; compare train vs eval outputs and confirm dropout is off and batch norm uses running stats.
  • Broadcasting, label alignment, in-place ops, flipped mask sign: shape asserts, label/input alignment checks, direct mask/loss tests, avoid in-place on autograd-needed tensors.
  • Detection: shape asserts, unit tests, tiny-batch overfitting as the final gate.

In full

The big silent ones are shape/semantics mistakes that still run: softmax over the wrong axis, probabilities fed to CrossEntropyLoss instead of logits, missing zero_grad so gradients accumulate, and forgetting eval()/no_grad so dropout and batch norm behave like training at test time. I’d also watch for accidental broadcasting such as (N,1) against (N,), unshuffled or misaligned labels, in-place ops that invalidate autograd, and a flipped mask sign. Detection is mostly cheap: assert shapes and dims at every boundary, unit-test loss/gradient against a hand-computed reference, verify labels align with inputs, and run a tiny batch until it overfits. For eval, compare train vs eval outputs and confirm dropout is off and batch norm uses running stats; for gradients, check that one step with fresh grads matches the accumulated-grad path and that grad norms don’t grow unexpectedly. In-place and mask bugs show up as wrong gradients or loss, so I’d test the masked/loss path directly and avoid in-place ops on tensors needed for backward. The tiny-batch overfit test is the final gate: if the model can’t memorise a few examples, the bug is usually in the loss, labels, or data pipeline rather than capacity.

Corrected by an independent AI reviewer.

What a strong answer covers

  • Softmax over the wrong dimension.
  • Probabilities passed to CrossEntropyLoss, which expects logits.
  • Missing zero_grad, so gradients accumulate.
  • Forgetting eval(), so dropout and batch norm behave wrongly at test time.
  • Accidental broadcasting, e.g. shape (N,1) against (N,); unshuffled or misaligned labels; in-place operations that break autograd; a flipped mask sign.
  • Detection: shape asserts, unit tests, tiny-batch overfitting.

Common mistakes

  • Listing only bugs that crash.
  • Giving no detection strategy.