Tensors, autograd & training loops

nn.Module, DataLoader, the forward/backward/step loop, and device management. Interviewers ask you to sketch a training loop cold — practice it.

About 19 min read3-question knowledge check

The mental model

A PyTorch training loop is a thermostat with a memory of how it was wrong. Each cycle: read the room (forward pass — the model turns inputs into predictions), compare to the target (loss — how far off), figure out which knob to turn and in which direction (backward pass — gradients), and nudge every knob a little (optimizer step). Repeat until the room settles. The genius is the middle step: you never compute the derivatives by hand. Autograd records every operation as you run the forward pass, building a graph, and then replays it backward to hand you the gradient of the loss with respect to every parameter automatically.

The analogy that makes autograd click: the forward pass leaves a **breadcrumb trail**. Every tensor operation that touches a parameter drops a breadcrumb recording what it did. When you call loss.backward(), PyTorch walks the trail *backward* from the loss, applying the chain rule at each breadcrumb, and deposits the accumulated gradient in each parameter's .grad. The optimizer then reads .grad and moves each parameter. You describe only the forward computation; the backward is derived.

The **WHY that trips up every beginner and every interviewer's first probe**: gradients *accumulate* by default. PyTorch adds each backward() result into .grad rather than replacing it, because that enables gradient accumulation across micro-batches. The consequence is that you **must call optimizer.zero_grad() every iteration** or gradients from previous batches pile up and training diverges. The three lines — zero_grad(), loss.backward(), optimizer.step() — are the heartbeat of every PyTorch program, and knowing exactly what each does, and why in that order, is the single most common interview request: "sketch a training loop from memory."

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision