The actual code isn't that hard but I second-guessed myself on where to zero the gradients.
Start by clarifying the problem: define a function that takes a model, data loader, optimizer, loss function, and device, then loops over epochs and batches. For each batch, move data to the device, perform forward pass, compute loss, zero gradients, backpropagate, and update weights. Emphasize correct order of operations and device placement.
Pro tip: Mention that you typically set the model to training mode (model.train()) at the start and consider using a learning rate scheduler or gradient clipping for robustness, but keep the core loop simple and correct.
Define the function with parameters: model, dataloader, optimizer, loss_fn, device, and num_epochs. Move the model to the device and set it to training mode.
Iterate over the specified number of epochs. Optionally, you can shuffle data or use a sampler, but the dataloader typically handles that.
For each batch, move inputs and targets to the device. This ensures computations happen on the correct hardware.
Perform forward pass, compute loss, zero gradients, backpropagate, and update weights. The correct order is: optimizer.zero_grad(), loss.backward(), optimizer.step().
Optionally, return the trained model or track and return loss metrics. You might also include validation after each epoch.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.