DL
    intermediate

    The PyTorch Training Loop

    ML Engineer path · lesson 42 of 80

    Six lines, and what each one defends against

    for epoch in range(n_epochs):
    loss.backward() — Autograd in action: walk the graph backwards and compute the gradient of the loss with respect to every parameter. Crucially, this accumulates into each parameter's .grad rather than replacing it.
    Gradients cleared each iteration, as they should be.
    0.10
    with zero_grad()withouttraining step → (loss on a log scale)
    Loss at step 1
    49.76
    Loss at step 16
    0.09
    Converging
    yes
    The loss falls from 49.8 to 0.094 over sixteen steps. Every gradient is computed fresh, so each update is the step the optimiser actually intended.

    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

    Test your knowledge

    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?

    Learn these first

    Interview Questions

    Meta
    NVIDIA
    OpenAI
    Anthropic
    Google
    Amazon
    Tesla
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required