PyTorch
PyTorch is the research default and increasingly the production one: tensors, autograd, nn.Module models, a training loop you write yourself, and export paths for serving. This subtree follows that order, from the tensor up to deployment.
on this pageshowhide
guide
overview
~1 minPyTorch is a Python library for building and training neural networks: multidimensional tensors that run on CPU or GPU, an automatic differentiation engine that records operations as they execute, and a module system for composing models. Interviewers probe it because it hides less than most frameworks. You write the training loop yourself, so a candidate who cannot say where gradients come from, where they are cleared, or why memory keeps climbing is exposed within a few questions. A good answer names the object involved, the state it carries, and the quiet failure that follows when that state is wrong. The hub follows the order a model is built in. [Tensors and operations](/topics/ai-pytorch-tensors) covers shapes, dtypes, broadcasting and the line between a view and a copy. [Autograd and gradients](/topics/ai-pytorch-autograd) explains how the graph is recorded and walked backwards. [nn.Module and layers](/topics/ai-pytorch-nn-module) is how parameters, buffers and submodules are owned and saved. [Training loops and optimizers](/topics/ai-pytorch-training-loops) puts those together into a loop with schedulers, mixed precision and checkpoints. [Data loading and pipelines](/topics/ai-pytorch-data-loading) keeps the GPU fed, and [TorchScript and deployment](/topics/ai-pytorch-deployment) gets the trained model out of the research script. Junior rounds check the mechanics: what a tensor shares, what `backward()` fills in, what order the loop runs in. Senior and principal rounds become debugging stories and serving choices, where a strong answer proves the cause before changing anything. Learn tensors and autograd first; every later section assumes you can predict a shape and say which tensors receive a gradient.
primer
### Eager execution is the design By default PyTorch runs each operation the moment Python reaches it, with no separate graph-building phase: the model is ordinary Python, so `print`, a debugger and an `if` on a tensor value all work. The same property drives the deployment questions: a model that is just Python must be captured before it can leave Python. ### A tensor is storage plus a description A tensor is a block of memory together with a shape, strides, a dtype and a device. Many operations return a new description over the same memory rather than new memory. Knowing which operations share and which allocate explains a family of bugs: an edit that appears somewhere unexpected, a contiguity error, memory that is never released. ### Autograd records, then replays in reverse When a tensor that requires gradients takes part in an operation, PyTorch notes the operation and what it needs to compute a derivative later. Calling `backward()` walks that record from the output to the leaves. Two consequences come up again and again: - **Gradients add up.** Nothing clears `.grad` unless your code asks, which is a feature for some techniques and a bug in a naive loop. - **Results keep their history alive.** Any tensor attached to the graph holds the graph, so what you keep around decides how much memory a training run uses. ### Modules own state, and that state has names An `nn.Module` is a container that registers what it holds: trainable parameters, non-trained buffers and child modules. Registration is what lets the optimizer find weights, lets `.to(device)` move everything, and lets `state_dict()` save it under predictable keys. Most module questions are really about what got registered and what did not. ### The loop is yours, and so are its bugs PyTorch provides optimizers, losses and schedulers but not the loop that calls them. Order, mode switches, precision and what goes into a checkpoint are decisions in your own code. Each line can be wrong without raising an error, which is why interviewers ask for one from memory. ### Throughput is a pipeline problem A fast GPU waiting on Python data loading is a common performance failure. The data layer overlaps loading with compute; tuning it starts with measuring which side is the bottleneck.
- Tensor
- An n-dimensional array with a dtype and a device. It is the type every PyTorch operation consumes and produces, and the object autograd tracks.
- Stride
- For each dimension, how many elements to skip in memory to move one step along it. Strides let views reinterpret memory without copying.
- View
- A tensor that shares another tensor's storage but describes it with a different shape, offset or strides. Writes through either one are visible in both.
- Broadcasting
- The rule that lets operations combine tensors of different shapes by treating size-one or missing dimensions as repeated, without copying data.
- Leaf tensor
- A tensor created directly by the user rather than produced by a tracked operation. Model parameters are leaves, and they are where gradients are stored.
- requires_grad
- A tensor flag that tells autograd to track operations involving that tensor so a gradient can be computed for it.
- nn.Parameter
- A tensor wrapper that, assigned as a module attribute, is registered as trainable state and returned by the module's parameters.
- Buffer
- Non-trainable tensor state registered on a module, such as running statistics, that moves with the module and is saved in its state_dict.
- state_dict
- A dictionary mapping names to the tensors a module or optimizer holds. It is the usual unit for saving and loading checkpoints.
- Mixed precision
- Running selected operations in a 16-bit floating-point type to save memory and time while keeping master weights in 32-bit.
- DataLoader
- The utility that draws samples from a Dataset, groups them into batches and can load them in parallel worker processes.
- TorchScript
- A statically typed subset of Python that PyTorch can compile or trace into a serializable program runnable without the Python interpreter.
- torch.compile
- A PyTorch 2 entry point that captures graphs from running Python code and generates optimized kernels, speeding up a model inside the same process.
Follow one training step. A `Dataset` returns single samples; the `DataLoader` batches them, often in worker processes, and the loop moves each batch to the device. The model, an `nn.Module` tree, runs its forward pass on that batch, and because its parameters require gradients, autograd records every operation along the way. The loss is one more tensor at the end of that record. `backward()` walks it in reverse and deposits a gradient on each parameter; the optimizer reads those gradients, updates the parameters, and keeps its own state such as momentum. The scheduler then adjusts the learning rate the optimizer will use next. Two switches cut across that path and are easy to confuse: ```python model.train() for x, y in loader: x, y = x.to(device, non_blocking=True), y.to(device) optimizer.zero_grad() loss = loss_fn(model(x), y) # graph recorded here loss.backward() # .grad filled on parameters optimizer.step() total += loss.item() # keep a number, not the graph model.eval() # changes layer behaviour with torch.no_grad(): # stops graph recording preds = model(val_x) ``` The mode switch tells layers such as dropout and normalization how to behave; the gradient context decides whether autograd records anything. Evaluation usually wants both, and neither implies the other. Deployment attaches at the end. A checkpoint is a set of `state_dict`s, which makes the model's attribute names part of its file format. Getting a model out of Python means capturing the graph that eager execution never wrote down, which is why the export tools differ mainly in how they capture it and what they refuse to guess.
- Tensors and Operations →
Shapes, dtypes, broadcasting and views: the vocabulary every error message and every later section is written in.
- Autograd and Gradients →
How gradients are recorded, accumulated and stopped, which explains most memory leaks and silent training bugs.
- nn.Module and Layers →
How a model owns and names its state, which decides what the optimizer updates and what a checkpoint saves.
- Training Loops and Optimizers →
Puts tensors, autograd and modules together into the loop interviewers ask you to write from memory.
- Data Loading and Pipelines →
Once the loop is correct, keeping the GPU fed is the next performance question.
- TorchScript and Deployment →
Export and serving choices make sense only after you know what a trained model and its checkpoint contain.
Assuming
model.eval()turns off gradient tracking: it changes how some layers behave, and evaluation withouttorch.no_grad()still records a graph and spends memory on it.Forgetting that gradients accumulate, then debugging a loss that diverges because every step applies the sum of all earlier gradients.
Appending the loss tensor itself to a history list, which keeps every iteration's graph alive and looks like a slow GPU memory leak.
Passing softmax output to
nn.CrossEntropyLoss, which expects raw scores; training continues without an error, only worse.Resuming from a checkpoint that saved only the model's weights and then blaming the data when the loss jumps; see what a resumed run omitted.
Tracing a model whose forward pass branches on tensor values and shipping the result without testing an input that takes the other branch.
This guide assumes the PyTorch 2.x line, where the questions are written. A few changes still shape what interviewers ask: - **2.0** introduced `torch.compile`, the graph-capture compiler that speeds up a model without changing how it is written. Questions about graph breaks and compile time come from this release onward. - **2.1** added `torch.export`, the whole-graph capture path that later releases built on for ahead-of-time compilation and on-device runtimes. - **2.6** changed `torch.load` to default to `weights_only=True`, so loading arbitrary pickled objects now has to be requested explicitly. Older tutorials that pickle whole model objects fail or warn under newer versions. TorchScript still works and still appears in production code and interviews, but new export work points at `torch.export` and the runtimes built on it. Mixed-precision helpers have also moved from device-specific namespaces to the device-generic `torch.amp` one. When an answer depends on which of these paths exists, name the version you are describing.
Interviewers expect you to place PyTorch among the other training frameworks. TensorFlow, usually through Keras, covers similar ground with a stronger tradition of graph-first deployment; JAX takes a functional approach, transforming pure functions for differentiation and compilation. The trade that separates them is how much the framework knows about your program in advance: PyTorch starts from eager Python and recovers a graph when you ask, while the others lean on compilation from the start. Around PyTorch sit layers you will be asked to choose among. Higher-level trainers such as PyTorch Lightning and the Hugging Face libraries write the training loop for you, which is why the loop questions here test whether you understand what they hide. For serving, ONNX turns a model into a framework-neutral graph for ONNX Runtime and similar engines, NVIDIA Triton serves models behind a multi-model inference server, and ExecuTorch targets phones and edge devices. [TorchScript and deployment](/topics/ai-pytorch-deployment) covers how to choose between them.
explore
- Q-00680In PyTorch, in what order do zero_grad, forward, backward and step go?level: juniorimportance: must knowfreq 88%
- Tensors and Operations6 questions
- Autograd and Gradients6 questions
- nn.Module and Layers6 questions
- Training Loops and Optimizers7 questions
- Data Loading and Pipelines6 questions
- TorchScript and Deployment6 questions
questions
page 2 of 2How do you capture a PyTorch model's intermediate activations without editing its forward()?
basics
~20 sRegister a forward hook on the submodule you want: handle = layer.register_forward_hook(fn), where fn receives (module, args, output). Detach what you store, and call handle.remove() afterwards or the hook keeps firing and holding tensors alive.
In PyTorch, why can keeping one small slice of a big tensor retain all its memory?
basics
~20 sBasic indexing and slicing return views that share the original tensor's storage buffer. That buffer is freed only when the last tensor referencing it is gone, so one saved row pins the entire allocation. Call .clone() to detach the slice onto its own storage.
Where does torch.nn.utils.clip_grad_norm_ go in a PyTorch loop, and what does it clip?
basics
~20 sCall it after loss.backward() and before optimizer.step(). It computes one global L2 norm across all the gradients you pass it and, if that norm exceeds max_norm, scales every gradient by the same factor so the combined norm equals max_norm.
How do you choose between ONNX Runtime, Triton, and ExecuTorch for a PyTorch model?
basics
~20 sLet the target decide. On-device means ExecuTorch; a heterogeneous CPU or accelerator fleet with simple pre-processing favours ONNX Runtime; a GPU service with Python-shaped pre- and post-processing favours a Triton PyTorch or Python backend. TorchServe is retired and should not anchor a new design.
Why does renaming a submodule attribute in an nn.Module break old checkpoints?
basics
~20 sstate_dict keys are built from the attribute path down the module tree, so self.fc produces fc.weight. Rename the attribute and every key under it changes, making a saved checkpoint's keys unrecognisable to the new class.
When do you write a custom torch.autograd.Function, and how?
basics
~20 sSubclass torch.autograd.Function with static forward and backward methods, save what backward needs via ctx.save_for_backward, and invoke it with .apply(). You need one only when autograd cannot derive the gradient itself: a non-differentiable step, a custom CUDA or C++ kernel, or a hand-written backward that is faster or more numerically stable.
Why do PyTorch DataLoader workers sometimes produce identical random augmentations?
basics
~20 sBecause a random generator created in the parent process is copied unchanged into every worker. PyTorch seeds each worker's torch, Python random and NumPy global generators from base_seed plus worker id, but an RNG object your Dataset holds, or a third-party library's state, is duplicated.
showing 31–37 of 37