KatInterview

Write a PyTorch Training Loop from Scratch

Machine LearningModel answer
MediumModel answerMachine Learningpytorchdeep-learningtraining-loop

Last updated

Implement a complete per-batch training loop in PyTorch, covering device placement, gradient management, and per-epoch loss tracking.

Write a PyTorch Training Loop from Scratch

You have the following ingredients already prepared for you:

  • model — a torch.nn.Module representing your neural network
  • train_loader — a DataLoader that yields (inputs, targets) tuples
  • optimizer — a PyTorch optimizer (e.g. Adam, SGD)
  • loss_fn — a callable loss function (e.g. nn.CrossEntropyLoss())
  • device — a string or torch.device indicating where computation should run ("cpu" or "cuda")
  • num_epochs — how many full passes over the dataset to perform

Implement the function below:

def train(
    model, train_loader, optimizer, loss_fn, device, num_epochs, verbose=True
) -> list[float]:
    ...

Your implementation must:

  1. Move the model to device before training begins.
  2. Set the model to training mode at the start of each epoch.
  3. For every batch, execute the following steps in the correct order:
    • Move inputs and targets to device
    • Clear accumulated gradients
    • Run the forward pass
    • Compute the loss
    • Run backpropagation
    • Update model parameters
  4. Return a list of average per-sample training losses, one per epoch. Use size-weighted averaging so partial final batches are handled correctly.
  5. Avoid retaining the computation graph across batches.

When verbose=True, print the epoch number and average loss after each epoch.

What to address in your answer:

  • The exact order of operations inside the batch loop, and why each step must come where it does
  • Common bugs that arise from getting this order wrong
  • How to compute a correct epoch-level average loss
  • Memory and performance considerations
  • Edge cases worth handling

Hints

Hint 1

PyTorch accumulates gradients by default — they don't reset between backward calls unless you explicitly clear them. Where you place that reset relative to the other steps matters more than it seems.

Hint 2

Use loss.item() to extract the scalar loss value for bookkeeping. Accumulating the tensor itself keeps the entire computation graph alive for every batch, which leaks memory fast on GPU.

Hint 3

The last batch from a DataLoader is often smaller than the rest. If your loss function uses reduction='mean', averaging those per-batch means directly gives a slightly wrong epoch average — weight each batch by its actual batch size instead.