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
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
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
| Choice | Use when | Avoid when |
|---|---|---|
| torch.no_grad() | Evaluation where you still need ordinary tensors | Outputs must later take part in autograd |
| torch.inference_mode() | Pure serving or inference | Outputs will later enter a backward pass |
| detach() | Cutting one path, logging, target networks | You need gradient through that path |
| find_unused_parameters=True in DDP | Some steps skip parameters | Every parameter always runs, since it slows each step |
| SyncBatchNorm | Per-GPU batch too small for stable BN stats | Single GPU, where it changes nothing |
| torch.compile(dynamic=True) | Input shapes vary per batch | Shapes are fixed and speed matters most |
| GradScaler | float16 autocast | bfloat16, which has float32's exponent range |
Traps interviewers probe
- 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.
- 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.
- 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.
- 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.
- 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.