Skip to main content

1. PyTorch Training Loop

A training loop repeatedly:
  1. Takes input data.
  2. Makes predictions.
  3. Calculates loss.
  4. Calculates gradients.
  5. Updates model weights.
  6. Repeats for multiple epochs.

Basic structure

Flow


2. What is an Epoch?

An epoch means the model has gone through the entire training dataset once.
Here, the model sees the complete dataset 10 times.

3. What is a Batch?

Instead of giving the entire dataset to the model at once, we divide it into smaller groups called batches. Example:
The model updates its weights after each batch.

4. zero_grad()

PyTorch accumulates gradients by default. Therefore, we clear the previous gradients before calculating new ones.
Simple meaning:

5. loss.backward()

This performs backpropagation.
It calculates how much each model parameter contributed to the error. For example:
These gradients are stored in:

6. optimizer.step()

This updates the model parameters using the calculated gradients.
Conceptually:

7. Adam Optimizer

Adam = Adaptive Moment Estimation Adam is one of the most commonly used optimizers in deep learning.
It automatically adjusts how each parameter is updated using information from previous gradients.

Why Adam?

Compared with basic SGD, Adam generally:
  • Converges quickly
  • Adapts the learning rate for individual parameters
  • Works well for many neural networks
  • Requires relatively little manual tuning

8. Learning Rate

The learning rate controls how much the model changes its weights during each update.
Conceptually:
Example:

9. Adam Example

Training:

10. Learning-Rate Scheduler

A learning-rate scheduler changes the learning rate during training. Instead of keeping:
for the entire training process, we can gradually reduce it. Example:
This can help the model make smaller updates as it gets closer to a good solution.

11. StepLR Scheduler

One simple scheduler is StepLR.
Meaning:
For example:

12. Using Scheduler in Training

The important order is:

13. Complete Example


14. The Whole Training Process

Think of it as:

15. Important PyTorch Functions


16. One-Line Memory Trick

Meaning:

Key takeaway

The training loop teaches the model, Adam updates its weights efficiently, and the learning-rate scheduler controls how aggressively those weights are updated over time.