Write a PyTorch training loop
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Dec 2025. It tests pytorch and deep learning.
Write a training loop in PyTorch. You are given a model, a DataLoader that yields (inputs, targets) batches, an optimizer and a loss function. Train for a number of epochs and report the average training loss of each epoch. Show clearly the order of the steps inside the loop.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
train(model, train_loader, optimizer, loss_fn, device, num_epochs) -> list[float]— moves the model and every batch todevice("cpu"or"cuda"), runsnum_epochsepochs, and returns the average batch loss of each epoch (0.0 for an epoch with no batches).
Example
A check you can do by hand. A linear model with one weight and a bias, both starting at 0, MSE loss, plain SGD with learning rate 0.1, one batch inputs = [[1.0], [2.0]], targets = [2.0, 4.0], one epoch:
predictions [0, 0] -> loss = (2² + 4²) / 2 = 10.0
dL/dw = 2/2 · ((0-2)·1 + (0-4)·2) = -10 -> w = 0 - 0.1 · (-10) = 1.0
dL/db = 2/2 · ((0-2) + (0-4)) = -6 -> b = 0 - 0.1 · (-6) = 0.6
train(...) -> [10.0]
Constraints
- Any model and loss; batches may differ in size (the last one is often smaller).
Clarifying questions
- Is there a validation set to evaluate on each epoch?
- Should the loop handle mixed precision, gradient clipping or a learning-rate scheduler?
- Should it save checkpoints, and how often?
What a strong answer covers
- The order within a batch:
optimizer.zero_grad(), forward pass,loss = loss_fn(outputs, targets),loss.backward(),optimizer.step(), and why zeroing is needed (PyTorch accumulates gradients). -
model.train()for training andmodel.eval()withtorch.no_grad()for evaluation, and what they change (dropout, batch norm, memory). - Averaging loss correctly:
loss.item()to avoid keeping the graph alive, and weighting by batch size if the epoch average should be per sample. - Moving data with
.to(device), andpin_memory/non_blockingfor speed. - Checkpoints that save the model, optimizer and scheduler state and the epoch, so training can resume.
Follow-ups
- Add gradient accumulation to simulate a batch four times larger.
- Add mixed precision with
torch.autocastand a gradient scaler. - Add early stopping on validation loss.
- Train on several GPUs with
DistributedDataParallel. What changes in the loop?
Where it's asked
- Amazon · Coding · Last asked Dec 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
pytorch · deep learning
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
