PyTorch interview questions and answers, from autograd to distributed training
PyTorch interview questions check whether you can write and debug a training loop by hand: tensors and autograd, nn.Module, Dataset and DataLoader, the zero_grad, backward, step order, train versus eval mode, and saving a state_dict. Senior candidates also get scenarios such as a loss that turns NaN, a GPU out-of-memory error or a slow input pipeline. Interviewers care less about memorized API names than about whether you know where gradients live and when they are cleared.
By Evin JohnPublished 8 min read
How PyTorch shows up in interviews
PyTorch is widely used in research groups and many product ML teams, so it appears in interviews for ML engineers, research engineers, applied and research scientists, and computer vision or NLP roles. The questions are rarely trivia. A typical round hands you a half-written model or a broken loop and asks you to make it train, then asks why each line is there. Version details matter less than habits, but say which release you last used, since APIs such as compile and export have moved across 2.x releases.
- Concept checkTen to fifteen minutes on autograd, modules, modes and devices, often as quick-fire questions.
- Live codingWrite a Dataset, a small model and a training loop in a notebook or shared editor, sometimes on synthetic data you generate yourself.
- DebuggingA loop with planted bugs: a missing zero_grad, softmax before CrossEntropyLoss, eval mode never set, or tensors on two devices.
- Scaling discussionFor senior roles: multi-GPU training, memory budgets, profiling and how the model leaves the notebook for serving.
PyTorch fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| How is a tensor different from a NumPy array? | Core data type | Same idea of a typed n-dimensional array, plus a device (CPU or GPU) and optional gradient tracking. torch.from_numpy shares memory with the array on CPU. |
What does requires_grad=True do? | Autograd | Operations on that tensor are recorded so backward() can compute gradients into its .grad. Parameters of nn.Module layers have it set by default. |
| What does a dynamic computation graph mean? | Define-by-run | The graph is built as the Python code runs, so ordinary loops and if statements work and a new graph forms on every forward pass. |
Why call optimizer.zero_grad() every step? | Gradient accumulation | backward() adds into .grad rather than overwriting it. Without clearing, each step uses the sum of all earlier gradients. |
What is the difference between model.train() and model.eval()? | Module modes | They flip layers such as dropout and batch norm. Eval mode does not turn off gradient tracking; that is a separate switch. |
torch.no_grad() versus torch.inference_mode()? | Grad tracking | Both skip graph recording. Inference mode goes further and its tensors cannot be used later in autograd, which makes it a little faster for pure serving code. |
What does .detach() return? | Graph boundaries | A tensor sharing the same data but cut from the graph, used for logging, targets or stopping gradients through one branch. |
view versus reshape? | Memory layout | view never copies and needs compatible strides, so it fails on many non-contiguous tensors. reshape returns a view when it can and copies when it must. |
| How do you move a model and a batch to the GPU? | Devices | model.to(device) moves parameters and buffers in place; tensors need x = x.to(device) because .to on a tensor returns a new one. Mixing devices raises an error. |
What does .item() do and when should you use it? | Python scalars | It copies a one-element tensor to a Python number. Use it for logging so you do not keep the graph alive, and avoid it in hot loops because it forces a sync with the GPU. |
import torch
w = torch.tensor(2.0, requires_grad=True)
for _ in range(3):
loss = (w * 3) ** 2 # d(loss)/dw = 18 * w = 36
loss.backward() # no zero_grad: gradients accumulate
print(w.grad) # tensor(108.)
t = torch.arange(6).reshape(2, 3).t() # transpose makes it non-contiguous
print(t.is_contiguous()) # False
print(t.reshape(-1)) # tensor([0, 3, 1, 4, 2, 5])
try:
t.view(-1)
except RuntimeError:
print("view needs compatible strides")The training loop question
Almost every PyTorch interview asks you to write this from memory. Say the order out loud as you type it: clear gradients, forward pass, loss, backward, optimizer step. Then switch to eval mode and turn off gradient tracking for validation. If you can also explain why CrossEntropyLoss gets raw logits and integer class labels, you have answered three common follow-ups at once.
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(256, 4)
y = (X[:, 0] + X[:, 1] > 0).long() # two classes
model = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 2))
loss_fn = nn.CrossEntropyLoss() # expects raw logits and class indices
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
for epoch in range(20):
model.train()
for i in range(0, len(X), 32):
xb, yb = X[i:i + 32], y[i:i + 32]
opt.zero_grad() # grads add up unless cleared
loss = loss_fn(model(xb), yb)
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
acc = (model(X).argmax(dim=1) == y).float().mean().item()
print(f"train accuracy {acc:.2f}")Intermediate PyTorch questions
- How does `nn.Module` know which tensors are parameters? Assigning an
nn.Parameteror a submodule as an attribute in__init__registers it. A plain Python list of layers is invisible to.parameters(), which is whynn.ModuleListexists. - What is a buffer, and when do you register one? State that should move with the model and be saved, but not trained, such as batch norm running means. Use
register_bufferso.to(device)andstate_dict()include it. - Why call the model as `model(x)` rather than `model.forward(x)`?
__call__runs registered hooks around forward. Calling forward directly skips them, which breaks some tooling quietly. - What do you implement in a custom `Dataset`?
__len__and__getitem__returning one sample. Keep heavy work such as decoding images there so DataLoader workers can run it in parallel. - When do you need a custom `collate_fn`? When samples differ in shape, such as token sequences of different lengths. The function pads them to a common length and often returns a mask or the true lengths.
- What do `num_workers` and `pin_memory` change? Workers load batches in background processes so the GPU is not left waiting. Pinned host memory makes copies to the GPU faster and allows
non_blocking=Truetransfers. - What goes wrong if you add softmax before `CrossEntropyLoss`? The loss already applies log-softmax internally, so the model trains on squashed values and gradients shrink. Feed logits and apply softmax only when you need probabilities.
- How do you save and resume training properly? Save a dict with the model's and the optimizer's
state_dict, the scheduler state, the epoch and the random seeds. Saving the whole pickled model ties the file to your code layout. - When do you call `scheduler.step()`? After
optimizer.step(), once per epoch or per batch depending on the scheduler. Calling it in the wrong place shifts the whole learning-rate curve. - How do you use different learning rates for parts of a model? Pass parameter groups to the optimizer, for example a small rate for a pretrained backbone and a larger one for a new head. Freezing layers means setting
requires_grad_(False)on their parameters. - How does mixed precision work in PyTorch?
torch.autocastruns suitable ops in float16 or bfloat16. With float16, a gradient scaler multiplies the loss so small gradients do not underflow and unscales before the optimizer step. bfloat16 usually does not need the scaler. - When would you write a custom `autograd.Function`? When you need a hand-written backward, for numerical stability or for an op autograd cannot see through. Mention
gradcheckto test it against finite differences.
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Linear(8, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loader = [(torch.randn(16, 8), torch.randn(16, 1)) for _ in range(8)]
accum_steps = 4 # effective batch = 16 * 4
opt.zero_grad()
running = 0.0
for step, (xb, yb) in enumerate(loader, start=1):
loss = nn.functional.mse_loss(model(xb), yb) / accum_steps
loss.backward() # gradients add up across micro-batches
running += loss.item() # .item(): keep a float, not the graph
if step % accum_steps == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
opt.step()
opt.zero_grad()
print(f"mean loss per update {running / (len(loader) / accum_steps):.3f}")Senior and scenario questions
| Scenario | What it tests | What a strong answer shows |
|---|---|---|
| The loss becomes NaN after a few hundred steps. | Numerical debugging | Check the inputs for NaN or infinite values, lower the learning rate, clip gradients, look for log of zero or division by a tiny number, and check float16 overflow. torch.autograd.set_detect_anomaly(True) finds the op, slowly. |
| Training hits CUDA out of memory. | Memory budget | Smaller batch with gradient accumulation, mixed precision, activation checkpointing, and looking for tensors kept alive by logging a loss without .item(). |
| GPU utilization sits low while training. | Input pipeline | Profile first. Usually the DataLoader is the bottleneck: raise workers, move decoding off the main process, pin memory, or pre-process data once. |
| Validation accuracy in the notebook is high but production predictions are poor. | Train and serve parity | Eval mode left off in serving, different preprocessing or normalization, a different tokenizer version, or a label mapping that drifted. |
| DataParallel or DistributedDataParallel? | Multi-GPU | DDP runs one process per GPU and all-reduces gradients, and is the recommended route. DataParallel is single-process and bottlenecks on one device. For very large models, mention sharded approaches such as FSDP. |
What does torch.compile give you, and what can go wrong? | Compilation (2.x) | It traces the model into graphs and generates faster kernels. Expect a warm-up cost, recompiles when shapes change, and graph breaks on unsupported Python. Measure before and after. |
| How would you ship this model to a C++ or mobile runtime? | Export | Options include TorchScript (older), torch.export, and ONNX for other runtimes. Say which you used and how you checked that outputs match the eager model on real inputs. |
| Two runs with the same seed give different results. | Reproducibility | Seed Python, NumPy and torch, seed DataLoader workers, enable deterministic algorithms where possible, and accept that some GPU kernels are nondeterministic unless you trade speed for it. |
| Fine-tune a large pretrained model on a small labeled set. | Transfer learning | Freeze most layers at first, use a low learning rate with warmup, watch the validation curve closely, and consider adapter or LoRA-style methods to train fewer weights. |
Fictional example
- Interviewer
- Your loss is fine for 400 steps and then becomes NaN. What do you do?
- Candidate
- First I want to know whether the data or the optimization caused it, so I would log the batch indices and save the batch that produced the NaN. I check that batch for NaN or infinite inputs and for empty sequences that could cause a division by zero in a masked mean. If the data is clean, I log the gradient norm per step. A norm climbing before step 400 points to a learning rate that is too high for this point in the schedule, so I add warmup or lower the peak rate and clip gradients at a norm of 1. Since we train in float16, I also check whether the gradient scaler keeps skipping steps, which would suggest overflow, and I would try bfloat16 if the hardware supports it. Once it trains, I keep a NaN check in the loop that stops the run and dumps the batch, so the next failure is quicker to trace.
A one-week PyTorch practice plan
- Day 1: write the training loop above from a blank file three times, then once with a validation split and early stopping.
- Day 2: build a custom Dataset and a
collate_fnthat pads text sequences and returns a mask. - Day 3: checkpoint and resume a run, then prove that the resumed curve matches an uninterrupted one.
- Day 4: plant five bugs in a working loop, swap with a friend or wait a day, and find them by reading only.
- Day 5: add autocast, gradient accumulation and clipping; profile one epoch and fix the slowest step.
- Day 6: read how DDP launches processes and write down how you would explain it in two minutes.
- Day 7: a timed mock: implement a small model plus loop in 30 minutes while explaining each line.
If the job asks for both frameworks, compare this page with TensorFlow interview questions, and use scikit-learn interview questions for the classical baselines many teams still expect. Research-track candidates should also read machine learning scientist interview questions.
PyTorch rounds reward people who narrate why each line exists, and that is hard to judge from inside your own head. Natively, an AI interview assistant for Mac and Windows, can transcribe a mock coding session on your computer so you can reread where you went quiet or skipped the eval switch. In practice it can also read a traceback or a planted-bug exercise from a screenshot and talk through a fix, and with Pro or the free trial it can use the résumé and job description you add to shape answer suggestions. Transcripts and notes stay saved for later review.
Questions people ask
What PyTorch questions are asked in interviews?
Expect autograd and why gradients accumulate, nn.Module and parameter registration, train versus eval mode, Dataset and DataLoader, loss function inputs, checkpoints, and for senior roles NaN losses, out-of-memory errors and multi-GPU training.
How do I prepare for a PyTorch coding interview?
Write a full training loop from a blank file until it is automatic, then practice finding planted bugs in someone else's loop. Explain each line out loud as you go, because interviewers score the reasoning as much as the code.
What is the most common PyTorch interview question?
Writing or fixing a training loop: zero_grad, forward, loss, backward, step, then eval mode with gradients off for validation. Follow-ups ask why each step is there.
Do PyTorch interviews ask about distributed training?
Mostly for senior and research engineering roles. Know why DistributedDataParallel is preferred over DataParallel, what gradient all-reduce does, and when sharded training such as FSDP is used.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
