PyTorch interview questions for model-training engineers
Strong answers trace the gradient objective and its denominator, the tensor’s shape and storage owner, the model state that moves or checkpoints, and the exact point where randomness or optimizer state must resume. They separate a PyTorch API guarantee from an application-level data policy and from a result that has actually been run.
For: Mid-level to senior machine-learning and model-training engineers
Guide scope and versions
Framework baseline: PyTorch 2.9, with versioned official documentation. This guide focuses on tensor and training-pipeline engineering, not model research or a particular deployment stack. The synthetic examples were executed with PyTorch 2.9.0+cpu on CPU; CUDA-specific behavior remains unverified.
Question 1 of 12
After two backward calls, why can a leaf gradient contain a sum while a saved activation has no .grad?
Backward computes derivatives through the recorded graph and accumulates them into leaf tensors that require gradients. A non-leaf intermediate normally does not retain its gradient in .grad. The graph is released after backward by default; a second backward needs a new forward graph unless retaining the old graph is actually required.
Each forward operation records edges when grad mode is on and at least one input participates in differentiation. A parameter is a leaf, so backward adds its derivative to parameter.grad rather than replacing an existing value. This is why a training loop must clear gradients at the intended update boundary. If an activation is needed for diagnostics, call retain_grad() on that non-leaf before backward; otherwise its derivative is an intermediate value used during propagation, not a persistent field.
The first backward generally frees saved intermediates from that graph. Reusing the same loss for a second backward can raise because required graph state was freed. retain_graph=True postpones that release and increases memory pressure; it does not fix accidentally retaining loss tensors across iterations. Usually run a new forward pass for each independent objective, or use autograd.grad when the caller needs returned gradients rather than accumulated .grad fields.
The executed assertions observe a leaf gradient of 3 after the first backward and 7 after the separate second graph. The intermediate is non-leaf and its .grad remains unset because retain_grad() was not called.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: When is retain_graph=True justified?
Only when a computation must intentionally backpropagate through the same saved forward graph more than once. For independent batches, perform separate forward passes; for selected derivatives, consider autograd.grad and account for its graph options.
How do you accumulate gradients over unequal microbatches without changing the sample-mean objective?
For an additive per-example loss, accumulate each microbatch loss sum divided by the total number of examples in the whole update window. The final partial window uses its actual example count. Averaging each microbatch mean equally gives the wrong objective when microbatch sizes differ.
Suppose a linear prediction is w*x, targets are 2*x, and the per-example loss is squared error. At w=0, the derivative for one sample is -4*x². For x values 1, 3, and 5, the sample-mean gradient is -(4*(1+9+25))/3 = -140/3. Splitting those examples into groups of two and one must produce the same weighted sum. Divide by the total sample count, not by the number of microbatches.
This equivalence assumes the objective is a sum of independent per-example losses and that the forward function is unchanged across the window. BatchNorm batch statistics, dropout randomness, contrastive losses across examples, and other batch-coupled operations can make microbatch gradients differ from one physical large-batch forward. Also decide whether padding/masks contribute to the denominator: for token losses, count valid tokens if that is the specified objective, not padded positions.
The executed example uses microbatches of sizes two and one, divides each summed squared error by the full count of three, and asserts the accumulated gradient is -140/3. Averaging the two batch means equally would optimize a different objective.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: Does this exactly reproduce a physical batch of three?
For a sum of independent per-example losses and a forward function whose behavior is unchanged by microbatch boundaries, yes, up to floating-point summation order. Batch-coupled layers or sampling can change the forward objective, so state those limits.
Why does model.eval() not disable gradients, and when can inference_mode break a later operation?
model.eval() changes modules that consult their training flag, such as Dropout and BatchNorm. It does not select a grad mode. no_grad() stops graph recording while allowing produced tensors in later grad-mode computations; inference_mode() removes more autograd bookkeeping, but tensors created there cannot generally enter later autograd-recorded work.
These are independent controls. A validation pass usually sets model.eval() and enters no_grad() or inference_mode() when its outputs are only consumed as metrics. A sensitivity or gradient-based validation calculation may need evaluation behavior from model.eval() while keeping grad mode enabled. Conversely, no_grad() alone does not stop Dropout or BatchNorm from using training behavior if the module remains in train mode. Restore the prior mode when a helper temporarily changes it.
Inference tensors are a poor fit for a cache later reused as a differentiable input. If later training needs an ordinary tensor, produce it outside inference mode or copy/convert it through an allowed path. Use no_grad() when tensors must cross back into autograd; it is a little less restrictive and still avoids recording that block.
Python with PyTorch 2.9 · Worked example
import torch
from torch import nn
model = nn.Sequential(nn.Dropout(p=0.9), nn.Linear(3, 2))
model.eval()
validation_batch = torch.tensor([[1.0, 2.0, 3.0], [2.0, 1.0, 0.0]])
with torch.inference_mode():
logits = model(validation_batch)
repeated_logits = model(validation_batch)
assert not logits.requires_grad
assert torch.equal(logits, repeated_logits)
model.eval()
input_batch = validation_batch.clone().requires_grad_(True)
logits = model(input_batch)
target_class = 1
score = logits[:, target_class].sum()
score.backward()
assert input_batch.grad is not None
assert input_batch.grad.shape == input_batch.shape
assert torch.isfinite(input_batch.grad).all()
The executed first pass uses evaluation behavior with inference-mode outputs that do not require gradients. The second pass keeps evaluation behavior but records a finite input gradient, which supports gradient-based attribution without re-enabling training-mode dropout.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: Which mode would you use to compute validation loss only?
Call model.eval() and use inference_mode() when predictions and loss are not reused by autograd. Use no_grad() if outputs must later participate in grad-recorded work. Restore train mode before the next training epoch.
Does detach() make a tensor copy that can safely be mutated?
No. detach() returns a tensor disconnected from autograd history, but it shares storage with the original tensor. An in-place write through either alias changes the same underlying values. Use detach().clone() when the new tensor must have independent storage.
Autograd history and storage ownership are separate properties. Detaching answers which operations participate in gradient computation; it does not allocate a new data buffer. Views, slices, and detached aliases can therefore affect one another through in-place writes. Some writes may also trigger autograd version checks if a value saved for backward was modified. A safe debugging snapshot should clone after detaching when it must remain unchanged.
A common failure is to cache detached model output and later normalize it in-place, unintentionally changing a tensor still used elsewhere. Another is to treat detach as an immutability boundary. The returned tensor can still be mutated. Document whether the caller receives an alias, a view, or an independent copy when designing tensor utilities.
The executed assertions show that a detached view shares storage with the base tensor, while detach().clone() creates an independent copy.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: What should a replay buffer store if it must freeze the current values?
Use an independent copy, commonly tensor.detach().clone(), and define device/dtype ownership. A detached alias is appropriate only when shared storage is intentional and mutation is controlled.
A regression loss runs without an error but is unexpectedly large. How can broadcasting create the wrong objective?
A prediction shaped [N,1] and target shaped [N] broadcast to [N,N], not [N]. The program compares every prediction to every target, creating pairwise residuals and a plausible scalar loss. Assert shapes at the loss boundary and choose the reduction denominator explicitly.
Broadcasting aligns trailing dimensions. For N=2, [2,1] aligns with [2] as [2,1] and [1,2], producing [2,2]. With predictions [[1],[2]] and targets [1,2], the residual matrix is [[0,-1],[1,0]]; its squared mean is 0.5 even though paired predictions match targets exactly and the intended loss is 0. This is a silent semantic bug, not a numerical-stability issue.
Normalize shape intentionally before subtracting: use squeeze on a known singleton output dimension, or reshape the target to match the model output contract. Avoid unconstrained squeeze() when batch size can be one because it may remove the batch dimension too. For classification, distinguish class-index targets from one-hot targets and use the loss API’s expected shape/dtype. Log shapes and reduction behavior during tests.
The executed tensors produce a (2, 2) residual and mean squared error 0.5 through broadcasting. Squeezing only the singleton output axis gives paired residuals of shape (2,) and loss 0.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: When should a target be reshaped instead of squeezing the prediction?
Follow the loss contract and preserve the model’s declared output shape. For per-example scalar regression, make both operands [N] or both [N,1]; for class-index classification, retain the documented [N] target shape and integer dtype. Assert the exact expected pair.
A tensor attribute stays on CPU and a learned list is absent from the optimizer. What was not registered?
Module parameters and buffers participate in module traversal. Assigning an nn.Parameter as a module attribute registers it as learnable state; register_buffer() registers non-parameter state that should move with the module and, when persistent, enter state_dict(). A plain tensor attribute or ordinary Python list of tensors is not automatically registered.
Registration determines more than serialization. Optimizers see parameters yielded by model.parameters(); Module.to() moves registered parameters and buffers; state_dict() contains parameters and persistent buffers. If a developer stores a tensor in a Python list or as a plain attribute, it can stay on its original device and be omitted from saved state. Use ParameterList/ModuleList for registered collections and register_buffer for constants or running state that belongs to the module.
A failure often appears only after moving the model: the registered weight is on CUDA while an unregistered mask remains on CPU, causing a device mismatch. Another appears on reload, when a plain running statistic silently resets. Verify named_parameters(), named_buffers(), state_dict() keys, and representative tensor devices rather than assuming any attribute under an nn.Module is managed.
Python with PyTorch 2.9 · Worked example
import torch
from torch import nn
class Scorer(nn.Module):
def __init__(self):
super().__init__()
self.weight = nn.Parameter(torch.ones(4))
self.register_buffer("running_scale", torch.ones(4))
self.mask = torch.ones(4)
model = Scorer().to(dtype=torch.float64)
assert "weight" in dict(model.named_parameters())
assert "running_scale" in model.state_dict()
assert "mask" not in model.state_dict()
assert model.weight.dtype == torch.float64
assert model.running_scale.dtype == torch.float64
assert model.mask.dtype == torch.float32
The executed membership and dtype checks show that the registered parameter and buffer appear in module state and convert to float64 with the module. The unregistered mask is absent from state_dict() and remains float32.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: Should a fixed normalization constant be a Parameter or buffer?
Use a buffer if it is module state that should follow device/dtype conversion but should not receive optimizer updates. Choose persistent=False only when it can be reconstructed and should not be checkpointed. A trainable value belongs in a registered Parameter.
How can a data pipeline duplicate samples or leak validation information without a model-code bug?
An IterableDataset is replicated across DataLoader worker processes, so each worker must shard its stream or samples can repeat. Separately, split examples by the real independence boundary before fitting preprocessing; validation/test data must not influence fitted statistics. Aggregate metrics by their actual sample or token weight, not by taking an unweighted mean of unequal batch means.
For a worker-sharded stream, get_worker_info() provides worker identity and count; each worker can take a disjoint stride of IDs. With map-style data, use a sampler and make the train/validation split explicit. Group related records by patient, user, document, or time before splitting when those relationships define independence. PyTorch’s loader does not decide that statistical boundary for the application; dataset governance must do so.
Suppose validation batches contain 100 and 10 examples. Averaging the two batch means gives each batch half the metric weight, while the sample-mean metric weights them 100/110 and 10/110. Accumulate loss sums and contributing counts (or use the metric’s defined weights). Fit normalization/imputation on training records only, then apply the fitted transform to held-out records.
Python with PyTorch 2.9 · Worked example
from torch.utils.data import DataLoader, IterableDataset, get_worker_info
class ShardedIds(IterableDataset):
def __init__(self, stop):
self.stop = stop
def __iter__(self):
info = get_worker_info()
worker_id = info.id if info is not None else 0
worker_count = info.num_workers if info is not None else 1
return iter(range(worker_id, self.stop, worker_count))
if __name__ == "__main__":
loader = DataLoader(ShardedIds(10), batch_size=4, num_workers=2)
batches = [batch.tolist() for batch in loader]
observed = [item for batch in batches for item in batch]
assert sorted(observed) == list(range(10))
assert len(observed) == len(set(observed))
metric_sum = sum(sum(batch) for batch in batches)
item_count = sum(len(batch) for batch in batches)
weighted_mean = metric_sum / item_count
mean_of_batch_means = sum(sum(batch) / len(batch) for batch in batches) / len(batches)
assert weighted_mean == 4.5
assert mean_of_batch_means != weighted_mean
The two-worker run checks that integer IDs 0 through 9 are returned exactly once. For uneven batches, the item-weighted metric is 4.5; the unweighted mean of batch means differs.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: When is averaging batch means correct?
Only when batches have equal weight under the metric or the aggregation explicitly weights each batch mean by its contribution. For token or masked objectives, accumulate the valid-token weight, not the padded tensor size. State the denominator in the metric definition.
What does setting a seed make reproducible, and what remains uncontrolled?
A seed fixes a pseudorandom sequence only relative to the generators, call order, algorithms, release, and platform in use. PyTorch does not promise identical results across releases or platforms. Deterministic-algorithm controls can reduce nondeterminism for supported operations, often with a performance cost or an error when no deterministic implementation is available.
A training run can draw randomness from Python, NumPy, PyTorch CPU/CUDA generators, DataLoader workers, samplers, augmentation libraries, and nondeterministic kernels. Seed each source deliberately and pass a seeded Generator to the loader/sampler where applicable. Worker initialization should derive independent Python/NumPy seeds from the worker’s PyTorch seed rather than giving every worker the same stream. Reproducibility is a system property, not one call to manual_seed().
Even with all generators seeded, exact equality can change with PyTorch version, hardware, driver, backend libraries, thread scheduling, or operation choice. deterministic algorithms help detect/avoid some nondeterministic operations but do not guarantee bitwise identity across every environment. Record environment and data/sampler ordering with a run; compare within a declared tolerance when exact bitwise repeatability is not the contract.
Python with PyTorch 2.9 · Worked example
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
class RandomizedRows(Dataset):
def __len__(self):
return 8
def __getitem__(self, index):
return index, random.random(), float(np.random.random())
seed = 812
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.use_deterministic_algorithms(True)
def seed_worker(_worker_id):
worker_seed = torch.initial_seed() % (2**32)
random.seed(worker_seed)
np.random.seed(worker_seed)
def collect_order_and_worker_randomness():
generator = torch.Generator().manual_seed(seed)
loader = DataLoader(
RandomizedRows(),
generator=generator,
worker_init_fn=seed_worker,
num_workers=2,
shuffle=True,
)
return [
(int(index), float(py_value), float(np_value))
for batch in loader
for index, py_value, np_value in zip(*batch)
]
if __name__ == "__main__":
first = collect_order_and_worker_randomness()
second = collect_order_and_worker_randomness()
assert first == second
assert sorted(row[0] for row in first) == list(range(8))
assert len({row[1:] for row in first}) > 1
The executed test repeats the same shuffled DataLoader with two workers and the same generator seed. It asserts identical index order and Python/NumPy worker values on this runtime, without claiming cross-release or cross-platform identity.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: How would you write a reproducibility claim for a benchmark?
Pin software, hardware, input order, seeds, and algorithm settings; rerun the defined workload and report observed variation. Do not claim universal reproducibility from one seed or one platform. Treat exactness as a measured tolerance contract.
Why does loading model weights alone not resume the same training trajectory?
Model state restores parameter and persistent-buffer values. Continuing the optimization also requires optimizer state (for momentum/Adam moments), scheduler and gradient-scaler state, progress position, and random/data-order state. Exact mid-epoch recovery may additionally depend on sampler cursor and worker/prefetch state, so a controlled checkpoint boundary is easier to reproduce.
An inference checkpoint can often be just model.state_dict(). A training checkpoint is a coordinated snapshot: model and optimizer must refer to the same update step; scheduler/scaler counters must match; the next sample order and random transforms must continue from the intended point. If the optimizer is rebuilt without its state, Adam’s moving moments restart and the next parameter update differs even when model weights are identical.
Prefer a boundary after a completed optimizer step and before fetching the next batch, then record epoch/global step and sampler or permutation position. Multi-worker prefetch complicates exact resume because items may already have been drawn but not consumed. Store RNG states for generators you use; record data version and preprocessing configuration. A checkpoint is only as complete as its declared resume contract. Python, NumPy, CPU/CUDA, sampler, and augmentation generators each need a defined restore path. A generic DataLoader does not promise arbitrary mid-prefetch cursor restoration; document that limit or checkpoint at a replayable boundary. At restore, reconstruct NumPy state from its primitive fields, then restore CPU/CUDA and loader-generator states before consuming data. Prefer a primitive/tensor-only representation compatible with weights_only loading; adding custom RNG objects can create an unsafe-global problem.
The executed fixture saves a trusted synthetic checkpoint before advancing either training branch, then loads it with weights_only=True. It compares restored weights, Adam step/moments, optimizer learning rate, scheduler epoch/rate, scaler and cursor state, restores Python/NumPy/Torch CPU/loader RNG state, and asserts that the same next update yields exactly matching weights and Adam state. The example covers CPU state only; it does not include CUDA RNG or prefetched worker state.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: Can this guarantee bitwise mid-epoch continuation with multiple workers?
Not by itself. You need sampler position, worker RNG and queued/prefetched sample state or a data pipeline designed for replay. A practical contract is often to checkpoint at an epoch or explicit data-shard boundary and state that exact in-flight worker replay is unsupported.
Why must scaled gradients be unscaled before clipping, and how does this interact with accumulation?
With float16 automatic mixed precision, GradScaler multiplies the loss so small gradients are less likely to underflow. The parameter gradients remain scaled through all microbatches in one effective batch. After the final backward, unscale once, clip the true gradient, then step and update the scaler.
Clipping a gradient multiplied by scale S against a threshold intended for the unscaled gradient imposes the wrong bound. For accumulation, unscale only after every contribution is added; otherwise scaled and unscaled terms mix and cannot be recovered. GradScaler also checks for non-finite gradients and can skip an optimizer step. Autocast should wrap forward and loss calculation, not backward.
If the last window has fewer examples, divide its loss sum by its actual residual-element count before scaling. This example uses mean-squared error and asserts equal prediction/target shapes, so the denominator is the number of scalar residuals across the full accumulation window. Keep the scale fixed across that window; call unscale once per optimizer before clipping. For bfloat16 or hardware/model combinations, scaling choices differ, so do not mechanically enable a scaler without matching dtype and device semantics.
The CPU fixture verifies that autocast produces float16 logits and GradScaler is enabled. It uses an explicit initial scale of 16 so the scaled gradients stay finite, checks the expected gradient after unscale, clips that gradient, and verifies the parameter update. A larger scale can overflow this CPU float16 path and cause GradScaler to skip the optimizer step. This proves the CPU path only, not CUDA behavior.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: What changes when the effective batch spans multiple optimizers?
Unscale each optimizer once after its assigned gradients have accumulated, clip each corresponding parameter set if needed, and call scaler.step for each optimizer. Call scaler.update once after all optimizer steps for that iteration so the scale advances from the combined non-finite checks; do not update the scale between optimizers.
A model compiles but does not speed up and recompiles for different batches. What should you inspect?
torch.compile traces Python frames into graphs. Unsupported or data-dependent Python behavior can cause graph breaks, which resume eager execution between compiled regions. Guard failures such as changing shapes or Python values can trigger recompilation. A successful compile is not proof of a speedup; measure steady-state work separately from startup compilation.
A call like tensor.item() used in a Python branch creates a value-dependent decision outside ordinary tensor graph flow. Changing shapes or control-flow guards can also trigger recompilation. The example inspects Dynamo graph_break_count and runs the default compiler on both branch outcomes. First locate the boundary, then decide whether to tensorize the operation, stabilize shapes, or intentionally leave a cold path eager.
Compilation has warmup and cache costs, so compare eager and compiled outputs for correctness, then benchmark after representative warmup with the same inputs and synchronization policy. A graph break generally loses optimization opportunity rather than changing model mathematics, but unsupported behavior and recompilation can still affect latency and memory. Do not promise a fixed speedup from the decorator alone.
The executed default torch.compile path reports a graph break at Tensor.item(), then returns the asserted positive- and negative-input results. This verifies the capture boundary and output behavior; it does not measure a speedup.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: Would fullgraph=True fix graph breaks?
It turns a graph break into an error because the whole function must be captured. It is useful as a diagnostic or strict requirement, not an automatic rewrite of unsupported Python behavior. Test representative shapes to expose guard-driven recompilation.
Does weights_only=True make an arbitrary checkpoint safe to load?
It restricts the unpickler to tensors, primitive types, and selected allowlisted globals, reducing arbitrary-code risk compared with unrestricted pickle loading. It is not a sandbox and does not make an untrusted artifact harmless. Prefer saving a state_dict and load only artifacts whose origin and expected contents are known.
Starting in PyTorch 2.6, torch.load defaults to weights_only=True when pickle_module is not supplied; PyTorch 2.9 keeps that versioned behavior. The restricted loader can still reject custom classes, and allowlisting a global permits that class/function to participate in unpickling. The official documentation warns that switching to weights_only=False can result in arbitrary code execution and should only be done for a trusted source.
Treat checkpoints as structured inputs: verify provenance, expected keys/shapes/dtypes and size constraints, map tensors to a controlled device, and avoid custom globals unless their code and artifact are trusted. weights_only limits supported reconstruction behavior; it does not isolate parser/resource use, validate model semantics, or provide a process security boundary. Do not conflate this with training resume: a model-only state_dict lacks optimizer and data progress.
Python with PyTorch 2.9 · Worked example
import tempfile
from pathlib import Path
import torch
from torch import nn
model = nn.Linear(3, 2)
with torch.no_grad():
model.weight.copy_(torch.arange(6, dtype=torch.float32).reshape(2, 3))
model.bias.copy_(torch.tensor([0.25, -0.5]))
expected = model(torch.tensor([[1.0, 2.0, 3.0]]))
state = model.state_dict()
with tempfile.TemporaryDirectory() as directory:
checkpoint_path = Path(directory) / "trusted-state.pt"
torch.save(state, checkpoint_path)
fresh_model = nn.Linear(3, 2)
loaded_state = torch.load(
checkpoint_path,
map_location="cpu",
weights_only=True,
)
fresh_model.load_state_dict(loaded_state)
actual = fresh_model(torch.tensor([[1.0, 2.0, 3.0]]))
assert torch.equal(actual, expected)
malformed = dict(loaded_state)
malformed["weight"] = torch.zeros(4, 3)
try:
fresh_model.load_state_dict(malformed)
except RuntimeError as error:
assert "size mismatch" in str(error)
else:
raise AssertionError("incompatible state shape was accepted")
The executed fixture writes a fresh synthetic state-dict artifact, loads it with map_location="cpu" and weights_only=True, and verifies the output. It also asserts that a deliberately mismatched weight shape raises RuntimeError. Restricted deserialization reduces the accepted object surface but is not a sandbox.
Executed with PyTorch 2.9.0+cpu on CPU.
Follow-up: What if a trusted training checkpoint contains an optimizer and custom scheduler class?
Prefer serializing state dictionaries and simple metadata that the restricted loader supports. If a custom object is required, establish artifact provenance and inspect the class before allowlisting it. Only use unrestricted loading in a controlled trusted boundary, never as a general fix for arbitrary files.
These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged PyTorch, rather than every job in the broader technology family.