Debugging and Testing ML Systems Questions
Finding, diagnosing, and fixing problems in ML code, data, and models, and building tests that catch these problems before they reach users. Covers common ML pitfalls (data leakage, shape mismatches, silent training bugs, mis-specified loss or metrics), root-cause analysis of model regressions and production incidents (accuracy drops, calibration drift, intermittent or hard-to-reproduce failures), distributed-training-specific failures (multi-GPU divergence, intermittent OOM, precision-related instability), and the diagnostic tooling that supports it (reproducibility artifacts, structured logging, instrumentation). Also covers testing ML systems directly: unit tests for data and feature pipelines, validation checks for datasets and features, test oracles and acceptance criteria for probabilistic or non-deterministic model outputs, and integration and regression tests that catch model or pipeline regressions before deployment. Emphasizes the engineering rigor that keeps ML systems correct and maintainable.
A large model-training run fails with a GPU out-of-memory error when you increase the batch size. List the practical mitigation strategies available to you, and describe the trade-off each one makes (extra compute time, implementation complexity, or a change in effective batch-size semantics).
Sample Answer
Direct answer. When a larger batch size pushes training past available GPU memory, the available fixes trade off differently between compute time, implementation complexity, and whether they change the actual math of what "batch size" means, so the right choice depends on which of those you can afford to spend.
The mitigation menu.
- Gradient accumulation: run several smaller micro-batches, summing their gradients before a single optimizer step, simulating a larger effective batch size without ever holding the full batch in memory at once. Trade-off: nearly free in implementation complexity and mathematically equivalent to true large-batch training for most loss functions, but costs extra wall-clock time since you're doing more forward/backward passes for the same effective batch. The exception is the batch-size-semantics one, and it is worth knowing by name: any layer that computes statistics over the batch, batch normalization above all, sees only the micro-batch, not the full effective batch, so a network containing batch normalization is NOT equivalent under accumulation and needs synchronized batch normalization across micro-batches or a normalization layer that does not depend on the batch at all.
- Mixed precision: store activations (the intermediate outputs each layer produces during the forward pass, which are kept in memory because the backward pass needs them, and which usually dominate memory during training) and weights in fp16 or bf16 (bf16 being a 16-bit format with fp32's exponent range but fewer mantissa bits, so it trades precision for far less overflow risk) instead of fp32, roughly halving memory footprint. Trade-off: often a "free" win in both memory and speed on modern hardware, but introduces its own numerical-stability considerations (dynamic loss scaling, meaning the loss is multiplied by a large factor before backward and the gradients divided by it afterwards, so that small gradient values do not vanish to zero in fp16, with the factor adjusted automatically when it causes an overflow; plus watching for NaNs from fp16 underflow and overflow), so it is not entirely free of engineering cost.
- Model or pipeline parallelism: split the model itself (not just the data) across multiple devices, so no single device needs to hold the full model or full activations. Trade-off: the most memory-scalable option but the most complex to implement correctly, and introduces communication overhead between devices.
- Activation checkpointing: don't store intermediate activations from the forward pass, recompute them during the backward pass instead. Trade-off: significantly reduces memory (often the single biggest lever for very deep networks) at the direct cost of extra compute, since the forward pass effectively runs twice for the checkpointed segments.
- Reducing sequence length: for sequence models, truncating or bucketing to a shorter maximum length directly reduces the memory footprint of attention and activations. Trade-off: free in implementation cost, but changes what the model actually sees, potentially losing information for the fraction of examples whose true length exceeds the new cap.
- Reducing the batch size itself, with the learning rate re-tuned to match: the option that is easy to forget precisely because it looks like giving up. Trade-off: free in both compute and implementation complexity, and the one option on this list whose cost lands squarely on effective batch-size semantics. A smaller batch means noisier gradient estimates and a different effective noise scale, so the learning rate and schedule usually need re-tuning (often downward), and the run's convergence path, and sometimes its final quality, genuinely changes rather than merely being reorganized.
- Parameter sharding (splitting optimizer state and/or parameters themselves across devices, as in ZeRO-style approaches, ZeRO being a family of techniques that partitions optimizer state, gradients and eventually parameters across devices instead of replicating them on every one): substantially reduces per-device memory for the optimizer state specifically (which is often larger than the model weights themselves for adaptive optimizers, that is, optimizers such as Adam that keep one or two running statistics per parameter and therefore carry several times the model's own size in state). Trade-off: adds communication overhead to gather sharded parameters when needed, and is more complex to set up than gradient accumulation or mixed precision.
How to choose. The two to know cold are mixed precision and gradient accumulation: both are close to free in engineering cost and, batch-normalization layers aside, neither changes what the model learns. Activation checkpointing is the third to reach for, since it is a pure compute-for-memory trade with no semantic change at all. Only then reach for model or pipeline parallelism, sharding, reducing sequence length, or simply shrinking the batch, since each of those trades away something the first three do not: implementation complexity and communication overhead for parallelism and sharding, information in the input for a shorter sequence, and effective batch-size semantics for a smaller batch with a re-tuned learning rate.
In a multi-node distributed training job, one node intermittently throws a CUDA out-of-memory error, or the job produces diverging results across otherwise-identical nodes. Outline a thorough debugging plan: what logs and traces to collect (NCCL, CUDA, system logs), how to distinguish a genuine memory leak or fragmentation from a legitimate peak-allocation spike, how to check that batch sizes and any model sharding are actually consistent across ranks, and how you would isolate WHICH rank is producing the anomaly (e.g. a NaN) when the job spans many GPUs. Give one short-term mitigation to keep the job running while you investigate.
Sample Answer
Direct answer. An intermittent multi-GPU failure (one node's CUDA OOM, or results diverging across otherwise-identical nodes) needs evidence gathered from every rank, not just the one that visibly failed, because the actual fault often originates on a DIFFERENT rank than the one that shows the symptom.
Debugging plan.
- Collect NCCL, CUDA, and system logs from every rank, not just the failing one, and turn them on BEFORE the run, since none of this can be recovered retroactively. A rank that silently produces a NaN, for instance, often only shows up as an OOM or a hang on a DIFFERENT rank once the collective operation (all-reduce) tries to synchronize with it. The three layers each need their own switch.
- NCCL / collectives:
NCCL_DEBUG=INFO(plusNCCL_DEBUG_SUBSYS=ALLwhen you need the ring topology) shows which ranks joined which communicator and where a collective stalled. Pair it withTORCH_NCCL_ASYNC_ERROR_HANDLING=1so a rank that dies tears the job down with an error instead of leaving every other rank blocked forever in the all-reduce, andTORCH_DISTRIBUTED_DEBUG=DETAILto get shape and dtype mismatches across ranks reported as errors rather than as silent corruption. - CUDA: on a REPRO run (not the production one, because it serializes kernel launches and changes timing), set
CUDA_LAUNCH_BLOCKING=1so the traceback points at the kernel that actually failed rather than at whatever later call happened to synchronize. For the OOM specifically, wrap the step in a handler that dumpstorch.cuda.memory_summary()at the moment of failure, and for a repeat offender turn on the allocator trace withtorch.cuda.memory._record_memory_history()and dump it withtorch.cuda.memory._dump_snapshot(), which gives you the call sites holding every live block instead of a single total. - System: check the kernel log on the suspect node (
dmesg -T) for Xid errors and for the host OOM killer, andnvidia-smi -q -d ECC,TEMPERATURE,POWERfor uncorrectable ECC counts, retired pages and thermal or power throttling. This layer is the one people skip and it is the one that answers the question actually being asked, which is why THIS node. A repeating Xid or a rising uncorrectable-ECC count on exactly one node turns a week of software debugging into a node replacement, and a host-side OOM kill explains a node dying with no GPU memory problem at all.
- NCCL / collectives:
- Separate the three memory failure shapes: a genuine leak, fragmentation, and a legitimate peak-allocation spike. They look identical at the moment of the OOM and completely different across many steps, so log TWO numbers per step, not one: memory ALLOCATED (the bytes currently held by live tensors) and memory RESERVED (the bytes the caching allocator is holding from the driver, including free-but-cached blocks). In PyTorch those are
torch.cuda.memory_allocated()andtorch.cuda.memory_reserved(). On a 16 GiB device the three shapes read like this:
step 1 50 100 150 200
LEAK alloc 8.1 8.4 8.7 9.0 9.3 (GiB, monotonic climb)
resv 8.6 8.9 9.2 9.5 9.8
SPIKE alloc 6.2 9.8 6.2 9.8 6.2 (sawtooth, returns to baseline)
resv 9.9 9.9 9.9 9.9 9.9
FRAGMENT alloc 6.0 6.0 6.1 6.0 6.0 (flat, far below capacity)
resv 9.5 10.2 10.9 11.4 11.8 (climbs away from alloc)
- Leak: allocated climbs monotonically across steps and never returns to baseline. Something is retaining references (a loss tensor accumulated into a Python list without
.detach()or.item(), a growing cache, a hook holding activations). Fix the retention. Raising the memory ceiling only buys steps. - Spike: allocated is a sawtooth that returns to the same baseline every step, with the peak driven by a particularly large batch or an activation-checkpointing boundary. Reserved sits flat at the high-water mark. This is normal behavior against an unlucky ceiling, and reducing batch size or enabling activation checkpointing genuinely fixes it.
- Fragmentation: allocated stays flat and well below device capacity while reserved climbs away from it, and the OOM message itself gives it away, reading something like "tried to allocate 2.00 GiB, 3.50 GiB free": there IS enough free memory in total, just not in one contiguous block. The other tell is that failure depends on allocation ORDER rather than step count, so it can fire at step 12 on one run and step 400 on the next, and it is strongly associated with varying tensor shapes (variable sequence lengths, ragged batches) that make each allocation a slightly different size. The fixes are different in kind from the other two: set
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True(or tunemax_split_size_mb) so the allocator stops carving unusable slivers, calltorch.cuda.empty_cache()at a safe step boundary to hand cached blocks back to the driver, bucket or pad variable-length inputs so allocation sizes repeat instead of drifting, and pre-allocate the large buffers once at start-up. Note what is NOT on that list: reducing batch size, which is the standard reflex and does not reliably help here, because the problem was never total capacity.
Confusing any two of the three leads to the wrong fix, and the fragmentation case is the one where the wrong fix is most tempting, since the allocator is reporting plenty of free memory while the allocation still fails.
3. Validate that batch size and sharding are actually consistent across ranks. A configuration bug (one node launched with a stale config, or an uneven data-sharding split) can silently give one rank a larger effective batch than the others; log the actual batch size and shard boundaries each rank believes it has, and diff them across ranks rather than assuming the launch config was applied uniformly everywhere.
4. Isolate WHICH rank produces an anomaly (for example a NaN) in a multi-GPU job: add a lightweight per-rank check right after the forward pass (before the collective all-reduce) that logs a boolean "this rank saw a NaN" flag, tagged with the rank ID, and aggregate these flags centrally. This turns "the job produced a NaN somewhere" into "rank 3 produced the NaN, ranks 0/1/2 were clean," which narrows the investigation from the whole cluster to one node's data shard, environment, or hardware.
Short-term mitigation to keep the job running while investigating. Reduce the per-rank batch size (or enable gradient accumulation to compensate) to lower peak memory pressure and buy headroom while you investigate the OOM's root cause, and enable periodic checkpointing (if not already in place) so an eventual failure doesn't lose the whole run's progress. This is explicitly a stopgap, not a fix: if the true cause is a genuine leak or a sharding bug, reducing batch size only delays the eventual failure, and if the cause is fragmentation it may not delay it at all, since a smaller batch changes allocation sizes without making the free memory any more contiguous. In that case the cheapest stopgap is instead the allocator setting plus a periodic empty_cache() at a step boundary.
After migrating model training from on-premises hardware to cloud GPUs, validation AUC drops by several points compared to the on-prem results, with no intentional code change. Propose a root-cause investigation plan covering the full environment difference between the two setups, and describe concrete steps to reproduce and isolate the regression to one specific difference.
Sample Answer
Direct answer
Treat "cloud versus on-prem" as a bucket of many individually testable differences, not one atomic cause, and isolate it the same way you would isolate any multi-variable regression: get a coarse yes/no answer first by running training in the new cloud environment with every candidate axis pinned back to the on-prem configuration, then flip the axes back to their cloud defaults one at a time to find which specific one actually explains the drop. Guessing which difference is responsible without this elimination step is the most common way this kind of investigation stalls.
Structured elaboration
Enumerate the full environment-difference checklist before touching anything. Six independent axes commonly differ between an on-prem box and a cloud GPU instance, and any or all of them can move at once during a migration: (1) GPU architecture, driver version, CUDA (Compute Unified Device Architecture, the platform that lets code run on an NVIDIA GPU) toolkit version, and cuDNN (NVIDIA's library of deep-learning primitives) version; (2) default numeric-precision paths, notably TF32, a reduced-precision matrix-multiply mode enabled by default on certain newer NVIDIA tensor cores, which can silently activate on new cloud hardware without a single line of code changing; (3) non-determinism knobs such as convolution-algorithm auto-tuning, which can select a different algorithm on different hardware even with the same seed; (4) data loading and sharding, where a different number of worker processes or a different node topology can change the effective order or composition of batches even when the top-level seed is identical; (5) framework and dependency versions, where a newer library version can silently change a default; (6) hyperparameters that look identical on paper but are actually environment-conditional, most commonly a batch size that auto-scales to available GPU memory, which changes the effective gradient statistics even when every explicit config value was copied over unchanged.
Reproduce first, before isolating. Pin an identical data snapshot and an identical explicit seed for both the on-prem and cloud runs, and capture a full environment manifest for each (driver, CUDA, cuDNN, framework, and every relevant library version, plus the actual GPU model), so "the same experiment" is a verifiable claim rather than an assumption. Confirm the regression reproduces consistently across at least two runs on the cloud side before spending effort isolating it, since a one-off flaky run is a different, easier problem than a persistent regression.
Isolate to one specific difference with a coarse-then-fine bisection. First, run training in the cloud environment with as many axes as feasible pinned back to the on-prem configuration at once: disable TF32 and any reduced-precision fast paths, force deterministic algorithm selection, match the data-loader worker count and sharding, pin the exact same library versions via the same container image, and pin the same batch size rather than letting it auto-scale. If that maximally-pinned cloud run recovers the on-prem AUC, the regression is confirmed to live somewhere in this checklist, not in a fundamentally different cause (a genuine data problem, a code bug unrelated to environment). Then flip exactly one axis at a time back to its cloud default, re-run, and re-measure, until the AUC drop reappears; the axis whose reintroduction reproduces the drop is the isolated cause. This one-at-a-time step is what "isolating to one specific difference" actually requires; stopping at "the coarse pinned run fixed it" only proves the cause is somewhere in the checklist, not which item.
Worked example
An actually-executed illustration of the precision axis specifically, since it is the one candidate that can be demonstrated without needing GPU hardware: computing the same matrix multiplication in float64 (double precision) versus float32 (single precision, the level of precision a reduced-precision tensor-core path would push even further below) on a fixed, seeded 2048x2048 random matrix pair.
import numpy as np
rng = np.random.default_rng(seed=94)
n = 2048
A64 = rng.standard_normal((n, n)).astype(np.float64)
B64 = rng.standard_normal((n, n)).astype(np.float64)
A32, B32 = A64.astype(np.float32), B64.astype(np.float32)
C64 = A64 @ B64
C32 = (A32 @ B32).astype(np.float64)
abs_diff = np.abs(C64 - C32)
print("max abs diff:", abs_diff.max())
print("mean abs diff:", abs_diff.mean())
print("logit_sum (float64):", C64.sum())
print("logit_sum (float32 compute):", C32.sum())
print("relative diff in summed scalar:", abs(C64.sum() - C32.sum()) / abs(C64.sum()))
Actual output:
max abs diff: 0.0004606311491102133
mean abs diff: 2.577116595525687e-05
logit_sum (float64): -5735.364531135827
logit_sum (float32 compute): -5735.349474763556
relative diff in summed scalar: 2.6251813967851895e-06
This confirms precision alone is a genuine, measurable, isolatable difference (a per-element difference and a summed-scalar relative difference of about 2.6 parts per million here), and it is exactly the kind of candidate the bisection method above would rule in or out by forcing both environments onto the same numeric path and re-measuring the actual AUC. It is not, on its own, evidence that precision explains an AUC drop of several points: a few-parts-per-million difference in a single matrix multiply is a plausible contributor once compounded across millions of operations in a deep network, but it is a small effect relative to what a several-point AUC swing usually needs, and the checklist's other candidates (a changed effective batch size, a dataloader silently sharding data differently, a disabled or reordered augmentation step) are individually far more likely to produce a swing that size on their own. The value of this worked example is demonstrating the elimination technique on a candidate that can actually be measured here, not asserting which of the six checklist items is the real cause on this specific migration; that answer only comes from running the same one-axis-at-a-time process against the real training job.
Trade-offs and pitfalls
- Stopping at the coarse pinned-run result is a common shortfall. Confirming that pinning everything back to on-prem fixes the regression proves the cause lives in the checklist; it does not by itself say which item, and a team under time pressure sometimes ships that partial answer as if it were the root cause.
- Assuming precision is the culprit because it is the easiest difference to demonstrate is a trap. The worked example above intentionally shows this: the effect is real and measurable, but its magnitude alone should not be mistaken for an explanation of a large metric swing without actually testing it against the real training job's AUC.
- An auto-scaling batch size is one of the most underestimated candidates on this checklist. It looks like "the same hyperparameters" in a config file while silently producing different effective gradient noise and different optimization dynamics purely because the new GPU has more or less memory than the old one; it deserves to be pinned explicitly, not left to infer from available memory.
- Treating "cloud versus on-prem is inherently unreproducible" as an excuse to stop investigating is the worst outcome here. Every one of the six checklist items is individually pinnable and individually testable; the investigation is tedious, not impossible, and giving up on isolation after the first confirming coarse test leaves the actual fix undiscovered.
A large transformer model's production performance has degraded, and you suspect the cause lives in a specific internal component (for example a particular attention head or an embedding layer) rather than the model as a whole. Propose a method to attribute the regression to internal components: component ablations, per-head masking, or representational-similarity analysis. Describe the instrumentation you would need to run these experiments safely against production traffic, and how you would validate that a component is actually causally responsible before changing the deployed model.
Sample Answer
Direct answer. Attributing a regression to a specific internal component (a particular attention head, an embedding layer) means designing an experiment where you can isolate that component's contribution WHILE the rest of the model stays fixed, since a naive comparison of the whole model's outputs before and after a change tells you THAT something is different, not WHICH part.
Methods.
- Component ablations, run differentially against a known-good checkpoint. Systematically zero out, mask, or bypass one component at a time (one attention head, one layer's contribution) and measure the change in a relevant downstream metric. Read on a single model, this measures IMPORTANCE: a component whose ablation barely changes the metric wasn't doing much useful work in the current regime; a component whose ablation changes the metric a lot is doing a lot of the model's work, for better or worse. Importance alone does not attribute a regression, because an important component was important before the regression too. So run the identical sweep TWICE, once on the last known-good checkpoint and once on the regressed model, and rank components by the CHANGE in their ablation effect between the two. A component whose ablation effect is unchanged is not the culprit no matter how large that effect is; a component whose ablation effect moved is the only pattern that could not have been true before the regression.
- Per-head masking, specific to attention-based architectures: mask individual attention heads (or small groups) and measure the effect, this is finer-grained than ablating a whole layer and can localize a regression to a SPECIFIC head rather than "somewhere in layer 7." The localization mechanism is the same differential: mask head by head in BOTH checkpoints and look for the head whose masking cost jumped while its siblings' masking costs held steady. Scope it deliberately, since the cost is visible: a model with 32 layers of 16 heads is 512 masked evaluation runs per checkpoint, so use layer-level ablation to narrow to a few suspect layers first rather than sweeping every head blind.
- Representational similarity analysis: compare the internal representations (activations) a component produces now against a known-good historical checkpoint's representations for the SAME inputs, using a similarity measure like CKA (centered kernel alignment). CKA runs from 0 to 1, where 1 means the two sets of representations carry essentially the same structure and lower values mean they diverged. There is no universal cutoff worth memorizing; read it relative to siblings and to your own historical baseline, so if most components sit at 0.95 or above against the known-good checkpoint and one sits at 0.6, that one is the outlier whatever an absolute threshold would have said. A component whose representations have drifted significantly from the known-good version, while sibling components stayed stable, is a strong localization signal even before you've established WHY it drifted.
Worked example, so "changes the metric a lot" has a number attached. Suppose the downstream metric is exact-match accuracy, the last known-good checkpoint scores 0.84 on the evaluation slice, and the regressed model scores 0.76. Layer-level ablation narrows the search to layer 7, so you run per-head masking across layer 7's heads on both checkpoints and tabulate how much each masking costs:
| Head | Metric drop when masked, known-good | Metric drop when masked, regressed | Differential |
|---|---|---|---|
| 7-1 | 0.005 | 0.008 | +0.003 |
| 7-3 | 0.020 | 0.110 | +0.090 |
| 7-5 | 0.009 | 0.011 | +0.002 |
Head 7-3 is the localization: its masking cost went from 0.020 to 0.110, a differential of +0.090, roughly thirty times its siblings' +0.003 and +0.002 and the same order as the 0.08 total regression itself. Notice what a single-checkpoint sweep would have concluded: 7-3 has the largest ablation effect in BOTH checkpoints, so a sweep run only on the regressed model would have flagged it as merely the most important head in the layer, indistinguishable from a head that was always that important. The representational check corroborates the same head: CKA between the two checkpoints' activations for 7-3 on identical inputs comes back around 0.61, while 7-1 and 7-5 sit at 0.97 and 0.96, so the head whose ablation effect moved is also the head whose representations moved.
Instrumentation needed to run these safely in production. These experiments should run against SHADOW or replayed traffic, never live user-facing traffic, since ablating a component (even temporarily, for measurement purposes) will degrade quality for whatever fraction of traffic sees it. Instrument the model to support a lightweight ablation/masking flag per component that can be toggled per-request in a shadow path, without needing a full redeploy for every experiment, and log enough per-component activation statistics on a sample of shadow traffic to make the representational-similarity comparison possible without re-running the entire historical traffic volume.
Validating the causal role before changing the deployed model. Confirm the finding replicates across a genuinely different input distribution (not just the same slice of traffic that first surfaced the regression), a component that "explains" the regression only on one narrow input slice may be correlated rather than causal. Then run a targeted, controlled fix (retraining or adjusting just the implicated component, or a targeted intervention like re-initializing just that component's weights and fine-tuning) and confirm the downstream metric recovers specifically when that fix is applied and not when an equivalent change is made to a DIFFERENT, non-implicated component, a negative control that guards against the fix "working" for an unrelated reason (like simply retraining anything tends to help a little).
Do a code walkthrough of a model-training loop with a colleague. Explain where common pitfalls occur in a loop like this one, and for each one you identify, name one concrete code-level change or guard that would prevent it. Keep every answer tied to an actionable code change, not just a description of the pitfall.
Sample Answer
Direct answer
Below is a training loop with five classic pitfalls planted in it, the kind of loop that runs without a single error or exception, produces a plausible-looking loss number, and is still wrong. Each pitfall gets a one-line diagnosis and a concrete, one-line code-level fix, because "this could cause problems" is not an actionable review comment, a specific guard is. The theme underneath all five: PyTorch (and most frameworks) will silently do the mathematically-defined-but-unintended thing rather than raise an error, so a code walkthrough has to actively hunt for these instead of waiting for a crash to point at them.
Structured elaboration
The loop under review:
model = Net()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
for epoch in range(epochs):
for x, y in train_loader:
out = model(x)
loss = mse_loss(out, y) # y is shape (B,), out is shape (B, 1)
loss.backward() # no opt.zero_grad() before this
opt.step()
val_loss = mse_loss(model(x_train), y_train) # "validation" reuses the training batch
print(f"epoch {epoch}: val_loss={val_loss.item()}")
Pitfall 1: target shape mismatch silently broadcasts instead of erroring. out has shape (B, 1) and y has shape (B,). MSELoss does not check that the shapes match; it broadcasts them to an (B, B) pairwise matrix before averaging, computing a value that looks like a loss but is not the mean squared error between predictions and targets. PyTorch actually emits a UserWarning about this ("Using a target size that is different to the input size... This will likely lead to incorrect results due to broadcasting"), but a warning does not stop training, and most CI (continuous integration, the automated build-and-test pipeline) logs do not fail a build on a warning.
Fix: loss = mse_loss(out, y.view(-1, 1)), or reshape at the dataset/collate level so shapes agree before they ever reach the loss.
Pitfall 2: missing optimizer.zero_grad() accumulates gradients across steps. PyTorch accumulates gradients into .grad by default; each backward() call adds to whatever was already there instead of replacing it, unless you explicitly clear it first. Without zero_grad(), every step's update direction is a running sum of every prior step's gradient, not that step's own gradient, so the effective step size grows with training and the optimizer stops doing what its learning rate schedule assumes it is doing.
Fix: call opt.zero_grad() as the first line inside the batch loop, before the forward pass.
Pitfall 3: forgetting model.eval() before validation leaves Dropout and BatchNorm stochastic. Layers like Dropout and BatchNorm behave differently in train mode versus eval mode; in train mode Dropout is still randomly zeroing units on every forward pass. A "validation loss" computed without switching modes is measuring a mix of the model's real behavior and dropout noise, which means the same input produces a different loss on every call, and the metric is not reproducible even holding the model fixed.
Fix: wrap validation in model.eval() before the forward pass and model.train() again before resuming training, ideally inside a with torch.no_grad(): block to also skip building the autograd graph.
Pitfall 4: no random seed makes "identical" runs diverge. Weight initialization and data shuffling both draw from the global random state. Without pinning torch.manual_seed(...) (and the data-generation seed) at the start of the script, two runs with the exact same hyperparameters produce different final losses, which makes it impossible to tell a genuine regression from ordinary run-to-run noise when comparing two training runs.
Fix: call torch.manual_seed(seed) once at the top of the script, before model construction, and seed the data pipeline's random state separately and explicitly.
Pitfall 5: "validation" is computed on the training batch, not a held-out set. The loop above reuses x_train, y_train, the same tensors the model was just trained on, and calls the result val_loss. This is not a validation metric at all; it is a second read of the training loss, and it will always look better than true generalization performance, which quietly upgrades an overfitting model to "looks fine" in every printed log.
Fix: maintain a genuinely disjoint held-out x_val, y_val split created once before training starts, and never let training code touch it.
Worked example
Each pitfall is reproduced in isolation below, buggy version next to fixed version. All five snippets share this preamble and each one re-seeds what it needs, so they can be run separately or concatenated into one file and they give the same numbers either way:
import torch, torch.nn as nn
mse = nn.MSELoss()
# Pitfall 1: shape mismatch
torch.manual_seed(0)
pred = torch.randn(8, 1)
target = torch.randn(8)
print(f"buggy (broadcast) loss: {mse(pred, target).item():.6f}")
print(f"fixed loss (target viewed as (B, 1)): {mse(pred, target.view(-1, 1)).item():.6f}")
Output (the UserWarning about broadcasting goes to stderr, not shown here):
buggy (broadcast) loss: 1.850730
fixed loss (target viewed as (B, 1)): 2.094649
The two numbers differ by 0.24 and neither call raised an error; only the UserWarning distinguishes them, and it is easy to miss in a noisy training log.
# Pitfall 2: missing zero_grad, tracked via gradient norm across 4 steps
# (same seed, same data, same model init in both loops)
torch.manual_seed(0)
X, y = torch.randn(16, 4), torch.randn(16, 1)
def grad_norms(use_zero_grad):
torch.manual_seed(1) # identical initialization in both runs
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
opt = torch.optim.SGD(model.parameters(), lr=0.1)
norms = []
for _ in range(4):
if use_zero_grad:
opt.zero_grad()
mse(model(X), y).backward()
total = torch.sqrt(sum((p.grad ** 2).sum() for p in model.parameters()))
norms.append(f"{total.item():.3f}")
opt.step()
return norms
print("grad norm per step WITHOUT zero_grad():", grad_norms(False))
print("grad norm per step WITH zero_grad():", grad_norms(True))
Output:
grad norm per step WITHOUT zero_grad(): ['0.864', '1.460', '1.716', '1.860']
grad norm per step WITH zero_grad(): ['0.864', '0.611', '0.502', '0.462']
Step 0 agrees exactly (0.864) because nothing has accumulated yet, which is the control that proves the two runs really do share an initialization. From step 1 on they separate: without zero_grad() the reported gradient norm climbs (1.460, 1.716, 1.860) because each backward() adds to the previous step's residue, while the fixed version reports the current batch's actual gradient, which shrinks as it converges (0.611, 0.502, 0.462).
# Pitfall 3: train mode vs eval mode, same input, two forward passes
torch.manual_seed(0)
net = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Dropout(0.5), nn.Linear(16, 1))
x = torch.randn(1, 4)
net.train()
print("same output on identical input, model.train() (BUGGY):", torch.equal(net(x), net(x)))
net.eval()
print("same output on identical input, model.eval() (FIXED):", torch.equal(net(x), net(x)))
Output:
same output on identical input, model.train() (BUGGY): False
same output on identical input, model.eval() (FIXED): True
# Pitfall 4: seeded vs unseeded runs, 3 SGD steps, same hyperparameters
def three_steps(seed=None):
if seed is not None:
torch.manual_seed(seed)
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
X, y = torch.randn(16, 4), torch.randn(16, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
for _ in range(3):
opt.zero_grad()
loss = mse(model(X), y)
loss.backward()
opt.step()
return loss.item()
a, b = three_steps(), three_steps()
print(f"no seed: equal={a == b} (both losses differ on every run, which is the point)")
a, b = three_steps(42), three_steps(42)
print(f"seed=42: run A loss={a:.6f} run B loss={b:.6f} equal={a == b}")
Output:
no seed: equal=False (both losses differ on every run, which is the point)
seed=42: run A loss=0.317924 run B loss=0.317924 equal=True
The unseeded pair's actual loss VALUES are deliberately not printed, because they are different on every run and pinning them in a document would be exactly the kind of unreproducible number this pitfall is about. The only stable fact there is equal=False.
# Pitfall 5: 300 held-out rows never seen during 300 epochs of training on 40 rows,
# versus those same 40 training rows relabeled as "validation"
torch.manual_seed(0)
w = torch.randn(4, 1) # the teacher function
X_tr, X_val = torch.randn(40, 4), torch.randn(300, 4)
y_tr = X_tr @ w + 0.1 * torch.randn(40, 1)
y_val = X_val @ w + 0.1 * torch.randn(300, 1)
model = nn.Sequential(nn.Linear(4, 32), nn.ReLU(), nn.Linear(32, 1))
opt = torch.optim.Adam(model.parameters(), lr=0.01)
for _ in range(300):
opt.zero_grad()
mse(model(X_tr), y_tr).backward()
opt.step()
model.eval()
with torch.no_grad():
leaky, true_val = mse(model(X_tr), y_tr).item(), mse(model(X_val), y_val).item()
print(f"'validation' loss measured on the TRAINING set (leaky): {leaky:.6f}")
print(f"true validation loss on a genuinely held-out set: {true_val:.6f}")
print(f"the held-out loss is {true_val / leaky:.0f}x the leaky number")
Output:
'validation' loss measured on the TRAINING set (leaky): 0.001805
true validation loss on a genuinely held-out set: 0.074003
the held-out loss is 41x the leaky number
The leaky number understates the model's real generalization error by a factor of 41 here (0.0018 against 0.0740). The exact multiple depends on how over-parameterized the model is relative to the training set, 32 hidden units against 40 rows in this case, so treat 41x as an illustration of the direction and rough magnitude rather than a figure to quote. A reviewer trusting the printed "val_loss" would believe the model generalizes far better than it does.
Complexity and edge cases for each guard. None of the five fixes changes the loop's asymptotic time or space complexity, each fix is a constant amount of extra work per step (a shape check, a mode toggle, a seed call, an extra held-out forward pass) or per run (an up-front seed call), so there is no complexity trade-off standing in the way of applying all five. The edge cases each fix specifically has to keep handling: Pitfall 1's fix must still work when a batch's target legitimately has a trailing singleton dimension already (view(-1, 1) on an already-correctly-shaped tensor is a no-op, not an error); Pitfall 2's fix must still zero gradients correctly on the very first step, before any gradient has ever been computed (calling zero_grad() on a fresh optimizer is safe and a no-op, not an error, which is what makes it safe to call unconditionally every step); Pitfall 5's fix must keep the held-out split fixed across every epoch, not re-split randomly on each epoch, or "held-out" stops meaning anything after the first epoch.
Trade-offs and pitfalls
- A shape mismatch like Pitfall 1 is the most dangerous of the five precisely because it never crashes. Missing
zero_grad()and stale eval mode both eventually show up as a training curve that looks wrong; a silently-broadcast loss can still produce a plausible-looking, monotonically decreasing curve while optimizing the wrong quantity the entire time. - Fixing Pitfall 2 changes the effective learning rate, since the un-fixed version was implicitly taking larger steps as gradients accumulated. After adding
zero_grad(), expect to re-tune the learning rate; do not treat a lower post-fix loss curve at the same nominal learning rate as proof the fix "improved" training on its own. - Catching Pitfall 3 in code review requires actually reading whether eval/no_grad wraps the validation call, not just checking that a validation loop exists. A validation loop that exists but never toggles mode still runs and prints a number every epoch, which is exactly what makes it easy to miss on a skim.
- A held-out split fixes Pitfall 5 only if the split happens once, up front, and nothing in the pipeline (including preprocessing steps like normalization) is fit on the validation portion. Fitting a scaler on the full dataset before splitting is a subtler version of the same leakage, the val loss still ends up optimistic, just less dramatically.
Unlock Full Question Bank
Get access to all 39 Debugging and Testing ML Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.