The training loop is the iterative process that transforms random weights into a trained model. At its core, it implements empirical risk minimization: find parameters θ that minimize average loss over training data.
WHY these components? Each step solves a specific problem:
Forward pass: "What does my current model predict?"
Loss: "How wrong am I?" (scalar measure of error)
Backward: "Which weights caused this error?" (gradient flow)
Update: "How should I adjust weights to reduce error?"
Iteration: "Am I generalizing, or just memorizing?"
Imagine you're learning to shoot basketball free throws, but you're blindfolded and can only feel how far you missed.
Training loop is like this practice routine:
Shoot the ball (forward pass) - you take a shot with your current technique
Feel where it landed (compute loss) - did you miss left, right, short, or long?
Figure out what went wrong (backward pass) - was your elbow too high? Did you use too much power?
Adjust your form (update parameters) - bend your elbow a little less, ease up on the power
Shoot again (next iteration) - try with your adjusted technique
Each shot teaches you something small. After hundreds of shots (epochs), your muscle memory (weights) gets really good at hitting the basket. The "learning rate" is like how much you adjust each time - big changes early when you're way off, tiny tweaks later when you're close.
The magic is that you never need to see the basket - just feeling the error and adjusting step-by-step eventually makes you a great shooter!
What are the five core components of a training loop? :: 1. Forward pass (compute predictions), 2. Loss computation (measure error), 3. Backward pass (compute gradients), 4. Parameter update (apply optimizer), 5. Iteration (repeat over batches/epochs)
Why do we use mini-batch SGD instead of full-batch gradient descent?
Full-batch requires computing gradients over entire dataset (slow and memory-intensive). Mini-batches approximate the gradient with much less computation while providing less noisy updates than single-example SGD. Balances variance and efficiency.
What is empirical risk minimization?
Minimizing the average loss over training data as a proxy for minimizing expected risk over the true data distribution. Formula: R^(θ)=N1∑i=1NL(f(xi;θ),yi)
Why must you call optimizer.zero_grad() before backward()?
PyTorch accumulates gradients by default. Without zeroing, gradients from previous batches add to current gradients, causing incorrect gradient magnitudes and exploding gradients. Only intentionally skip when implementing gradient accumulation.
What happens if you forget model.eval() during validation?
Layers like Dropout and BatchNorm use training-mode behavior (random drops, batch statistics instead of running statistics), giving incorrect and typically pessimistic evaluation metrics. Always call model.eval() before validation and model.train() before training.
What is the update rule for SGD with mini-batches?
θt+1=θt−∣Bt∣η∑(x,y)∈Bt∇θL(f(x;θt),y) where Bt is the mini-batch, η is learning rate, and we average the gradient over the batch.
Why do we shuffle training data each epoch?
Prevents model from learning batch order artifacts and correlations between consecutive batches. Without shuffling, corelated samples bias gradient estimates and the model may learn the sequence pattern instead of true underlying patterns.
What is early stopping and why does it work?
Monitoring validation loss and stopping training when it stops improving (after patience period). Works because validation loss increases when model starts overfitting (memorizing training noise), so stopping before this point preserves generalization.
How do you implement gradient accumulation correctly?
Divide loss by accumulation_steps before backward(), accumulate gradients over multiple batches without zero_grad(), then call optimizer.step() and zero_grad() after accumulation_steps batches. This simulates a larger effective batch size.
What is the purpose of learning rate scheduling?
Adapts learning rate during training - large steps early to escape initialization quickly, small steps later to settle into minima without overshooting. Common schedules: step decay, exponential decay, cosine annealing, reduce on plateau.
Training loop deep learning ka dil hai, dost. Socho tumhare pas ek model hai jo bilkul nayi hai, kuch nahi janta. Training loop woh process hai jisse model seekhta hai data se.
Pehle forward pass hota hai - matlab model apna current guess deta hai (prediction). Fir loss function bata hai kitna galat tha (error). Ab magic shuru hoti hai: backpropagation se har weight ko pata chalta hai ki usne kitna contribution diya is error mein. Yeh gradients hain. Phir optimizer (jaise SGD ya Adam) un gradients ka use karke weights ko thoda adjust karta hai, taki agle baar error kam ho.
Yeh sab ek batch ke liye hota hai (32-256 examples). Pura dataset khatam hone tak yeh repeat karta rehta hai - iskoek epoch kehte hain. Kai epochs ke bad model expert ban jata hai. Lekin dhyaan rakho - agar validation loss badhne lage toh early stopping lagao, warna overfitting ho