IntermediateAbout 18 min

    The PyTorch Training Loop

    Read the full article on Substack

    5 min read.

    Scikit-Learn hides training behind fit(). PyTorch makes you write the loop, and two of its lines exist purely to work around how autograd stores gradients. Forget one of them and the model quietly fails to train — no exception, no warning. Run both versions side by side.

    0.10
    0.010.1110step 1step 16loss, log scale
    With zero_grad(), the loss falls from 49.8 to 0.09 in 16 steps. The faint line is the other run.

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    Write the training loop

    Sequence

    Order the five lines inside a PyTorch batch loop.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    What does calling backward() on a tensor do to the .grad attribute of every variable used to compute it?

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going