Writing a Training Loop
🔁 What is a training loop? A training loop repeats one step: take a batch, run the model, compute the loss, backpropagate and let the optimizer update the weights. Around that step sit the parts that make it trustworthy: shuffling, a held-out evaluation, checkpoints, and a way to tell when something is wrong.
Almost every ML coding round that trains anything ends in one, and the "train it end to end" mini-projects, like training a tiny GPT, are mostly a training loop with a model plugged in.
The Prompt
The step itself is five lines, so the interviewer grades everything around it: the order of the calls, train and eval modes, checkpoints, and how fast you find out why a loss is stuck.
"Here is a small classifier and a dataset. Write the training loop with mini-batches, a validation pass and checkpointing. Then I'll show you a loop whose loss doesn't fall."
Clarifying Questions
You: PyTorch? And is the dataset in memory as tensors, or should I write a Dataset and DataLoader?
Interviewer: PyTorch, in-memory tensors. Batch it yourself so I can see it.
You: What should the loop report? I'd log mean train loss per epoch, plus validation loss and accuracy.
Interviewer: That's fine. Return the history.
You: For checkpoints, do you want the best model by validation loss, the latest state for resuming, or both?
Interviewer: Both. Resuming should continue as if it was never stopped.
You: Fixed number of epochs, and can I pick the optimizer and learning rate?
Interviewer: Fixed epochs, your choice of optimizer. Make it reproducible with a seed.
What You'll Build
batches(X, y, batch_size, shuffle, gen) -> iterator of (xb, yb): one pass over the data.train_epoch(model, opt, X, y, batch_size, gen) -> float: mean training loss.evaluate(model, X, y) -> (loss, accuracy): no gradients, eval mode.fit(model, data, epochs, ckpt_dir, resume=False) -> list: the full loop with best and last checkpoints.