43. Backpropagation Intuition (No Heavy Maths)
43.4 Beginner Backprop Mistakes
Why. Beginners forget zero_grad, call backward twice without clearing, or expect backprop without a differentiable loss.
What. Gradients accumulate by default in PyTorch. Always optimizer.zero_grad() before backward in a normal loop. Also: vanishing/exploding gradients are advanced topics — start with short nets and ReLU.
How.
Checklist
- zero_grad → backward → step (order matters).
- Do not detach tensors if you still need gradients.
- If loss is NaN, lower lr and check inputs for NaNs (Chapter 40).
print("OK order: zero_grad → backward → step")
print("BAD: backward → backward (grads stack up)")
Ravindra Bagale's Tip
If you forget zero_grad(), PyTorch adds the new gradients on top of the old ones, so the training behaves strangely. Make it a habit to clear the gradients before every backward() call.
Ravindra Bagale's Tip – मराठी
zero_grad() विसरलात तर PyTorch नवीन gradients जुन्या gradients वर जोडत राहतो, त्यामुळे training विचित्र वागतं. प्रत्येक backward() call आधी gradients clear करण्याची सवय लावा.
Ravindra Bagale's Tip – हिंदी
zero_grad() भूल गए तो PyTorch नए gradients को पुराने gradients में जोड़ता रहता है, इसलिए training अजीब तरह से चलती है. हर backward() call से पहले gradients clear करने की आदत बनाओ.