Skip to content
Tech Interview Prep
Technical interview guideNew

PyTorch Fundamentals for Training and Debugging

How PyTorch tensors, autograd, modules and the training loop work, and how to diagnose shape, device, dtype and gradient failures in training code for ML engineering interviews.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v2
Editorial status
Reviewed

Scope: PyTorch 2.x stable releases. Behaviour of torch.compile, DDP, autocast and GradScaler is stated for 2.x; check the release notes for the exact version a team runs and note the version in the answer..

Overview

Curated: · Written: · Reviewed:

PyTorch Fundamentals for Training and Debugging

In one line

A tensor is storage plus metadata, autograd records the ops behind a scalar loss, and the training loop runs zero_grad, forward, loss, backward, step in that order. Reach for this when a question asks why a shape, device, dtype or gradient failure happens, or how to find it. Checked against PyTorch 2.x; state the exact version your team runs.

Key definitions

  • Leaf tensor: a user-created tensor such as a parameter. Its .grad survives backward.
  • Non-leaf tensor: an intermediate. Its .grad is None unless you call retain_grad().
  • Buffer: module state that is not trained, such as BatchNorm running stats, registered with register_buffer.
  • Broadcasting: shapes align from the trailing dimension and size-1 dimensions stretch, so a bad shape can run without error.
  • Graph freeing: backward frees saved tensors, so a second backward raises unless retain_graph=True.
  • Recompile: torch.compile rebuilds its graph when a guard fails, most often on a new input shape.

Formulas and complexity

∇(1k∑i=1kLi)=1k∑i=1k∇Li\nabla\Big(\frac{1}{k}\sum_{i=1}^{k}\mathcal{L}_i\Big)=\frac{1}{k}\sum_{i=1}^{k}\nabla\mathcal{L}_i Beff=k⋅bmicro⋅NranksB_{\text{eff}}=k\cdot b_{\text{micro}}\cdot N_{\text{ranks}} θt+1=θt−ηλθt−ηm^tv^t+ϵ\theta_{t+1}=\theta_t-\eta\lambda\theta_t-\eta\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}

The last line is AdamW: decay acts on the weights directly, not through the adaptive denominator. Adam keeps two tensors per parameter (m and v) plus a step count. SGD with momentum keeps one buffer per parameter.

How it works

zero_grad forward builds graph loss backward fills leaf grads and frees graph clip_grad_norm_ optional optimizer.step scheduler.step

Each differentiable op whose input requires grad stores a backward function that refers to its inputs. backward walks that graph once, accumulates into leaf .grad, and discards saved buffers. zero_grad must run before the backward pass, or earlier gradients add in. Clipping goes after backward and before step. The optimizer reads only .grad and its own state, so a checkpoint without optimizer state restarts Adam's moments.

When to use and when not to

ChoiceUse whenAvoid when
torch.no_grad()Evaluation where you still need ordinary tensorsOutputs must later take part in autograd
torch.inference_mode()Pure serving or inferenceOutputs will later enter a backward pass
detach()Cutting one path, logging, target networksYou need gradient through that path
find_unused_parameters=True in DDPSome steps skip parametersEvery parameter always runs, since it slows each step
SyncBatchNormPer-GPU batch too small for stable BN statsSingle GPU, where it changes nothing
torch.compile(dynamic=True)Input shapes vary per batchShapes are fixed and speed matters most
GradScalerfloat16 autocastbfloat16, which has float32's exponent range

Traps interviewers probe

  1. Softmax inside forward, then CrossEntropyLoss. The loss applies log-softmax again, so a 10-class head sits near ln 10 and barely learns. Fix: return logits and apply softmax only where probabilities are needed.
  2. Evaluating without model.eval(). Dropout stays random, and BatchNorm uses batch statistics and keeps updating its running stats, so results drift between runs. Fix: call model.eval() and no_grad for validation, then model.train() again. If validation already overwrote the stats, reload the checkpoint saved before it.
  3. Layers in a plain Python list. The optimizer, state_dict and .to() never see them, and parameters() yields nothing for them. Fix: nn.ModuleList or nn.Sequential.
  4. Silent broadcasting in the loss. pred of shape (4,1) minus y of shape (4,) builds a 4 by 4 difference. With pred and y both [1,2,3,4], the default MSE is 2.5, not 0. Fix: assert pred.shape == y.shape before the loss.
  5. Ignoring the return value of .to(). x.to('cuda') returns a new tensor, so the original stays on the CPU. Fix: x = x.to(device), and build new tensors on the input's device.

Interview tips

Open by naming the order you check things in: shapes, devices and dtypes at module boundaries, then whether logits or probabilities reach the loss, then per-layer gradient norms. A GPU at 30 percent utilisation usually means data prep is slower than the step, so raise num_workers before touching the model.

Follow-ups to expect:

  • What breaks at the second GPU? Gradient buckets and DDP's rule that every rank produces gradients for the same parameters in the same order. find_unused_parameters=True trades speed for safety.
  • How do you resume? Save model, optimizer, scheduler and step. torch.load defaults to weights_only=True from PyTorch 2.6, so checkpoints holding arbitrary Python objects need weights_only=False from a trusted source.
  • Why does loss go NaN? Find the first non-finite step, then use torch.autograd.set_detect_anomaly(True) on a reproducible failing step. It names the backward op that produced NaN, which the loss value cannot.
  • Why does memory grow? Appending loss tensors to a list keeps every graph alive. Append loss.item() instead.

30-second outline: "Each step zeroes grads, runs forward to a scalar loss, calls backward to fill leaf grads and free the graph, then steps the optimizer. My first checks are shapes, devices and dtypes at module boundaries, then whether logits reach the loss. For a flat loss I overfit one batch. For NaN I find the first bad step and turn on anomaly detection."

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.