skip to content

Training Dynamics and Debugging

You will learn the debugging playbook for training runs: pick initialization correctly, read a loss curve, overfit a single batch first, and diagnose NaNs, dead ReLUs, and silent data bugs. 'Your loss is not decreasing — walk me through it' is a staple senior DL interview scenario.

on this pageshow

explore

questions

page 1 of 2

Training loss oscillates with an identical pattern in every epoch — what data-loading bug does that suggest?

level: juniorimportance: must knowfreq 70%

answer

  1. the same wiggle in every epoch
  2. periodic, not random
  3. what order does the file sit in?
  4. print one batch's label histogram
  5. reshuffle indices before each epoch

basics

~20 s

The batches are being read in the stored file order without shuffling. If that order is sorted by class, every batch holds one class, the loss swings as the class changes, and the same swings repeat each epoch.

solid answer

~50 s

A loss curve whose wiggles line up epoch after epoch says the sample order is fixed and correlated with the label. The classic cause is reading a catalogue in the shard order it was written — say a 40-class product-photo set stored class by class — with shuffling off, so each batch contains a single class. The model drives the batch loss down by predicting whatever class it is currently fed, then pays for it the moment the class changes; those spikes recur at the same iteration index every epoch because the order never changes. Each minibatch gradient is then a strongly biased estimate rather than a noisy estimate of the full-data gradient. Fix it by reshuffling the sample indices before every epoch, then confirm that the label histogram of one batch resembles the overall class distribution.

go deeper

for a junior

Know that training batches must be shuffled and that shuffling is repeated each epoch. Be ready to say what a single-class batch does to a gradient step and to name the one-minute check: print the labels in one batch.

for a middle

Explain why unbiasedness of the minibatch gradient depends on random sampling, and why momentum amplifies the damage when consecutive batches share a label. Be able to read epoch-length periodicity in a loss curve as evidence about ordering.

for a senior

Show the diagnosis path on a real pipeline: overlay two epochs' loss curves, count distinct labels per batch, and check whether a streaming shuffle buffer is actually larger than the class run length in the files.

for a principal

Own the guardrail rather than the incident. Argue for a startup assertion on batch label diversity, for how datasets get written so that block structure cannot silently reappear, and for what such a check costs when the run is legitimately single-class.

## The symptom You plot training loss against iteration and see structure, not noise: a repeating pattern of dips and spikes whose shape is the *same* in epoch 2 as in epoch 1, aligned to the same iteration offsets. Validation is poor and the model's predictions look skewed toward a handful of classes. Nothing has errored; the run is green. That exact periodicity is the tell. Ordinary minibatch noise is aperiodic — it does not reproduce itself. A pattern with period equal to one epoch can only come from something that repeats with period one epoch, and the only thing that does is **the order in which samples are visited**. ## Why order matters at all Stochastic gradient descent rests on one assumption: the gradient computed on a minibatch is an *unbiased* estimate of the gradient on the full training set, differing from it only by noise. That holds when the batch is a random sample of the data. It does not hold when the batch is a contiguous slice of an ordered file. Concretely, take a 40-class product-photo catalogue written class by class — all of class 0, then all of class 1, and so on — and read it in stored order with shuffling disabled. With a batch size well below the size of one class block, nearly every batch contains a single label. The cheapest way to reduce the loss on such a batch is to collapse the output distribution onto that one class. The next few batches reward the same collapse. When the block boundary arrives, the model is confidently wrong on every sample at once and the loss spikes; it then chases the new class. Momentum makes this worse, because accumulated velocity keeps pushing toward the previous class for several steps after the class has changed. Any statistic computed per batch is likewise estimated on a single class rather than on a representative mix. Because the visiting order is identical on the next pass, the entire pattern replays: same dips, same spikes, same iterations. Late in training there is also a recency effect — whichever class was seen last has the strongest claim on the final weights. ## Confirming it in a minute 1. Pull one batch straight out of the loader and print the histogram of its labels. If the batch holds one or two distinct labels while the dataset has forty, you are done. 2. Count distinct labels per batch across the first twenty batches. A properly shuffled loader gives roughly the number you would expect from sampling the class distribution. 3. Overlay the loss-versus-iteration curves of two consecutive epochs. If the spikes superimpose, the order is fixed. ## The fix Reshuffle the sample indices **before every epoch**, not once at load time. A single shuffle removes the class correlation but freezes the batch partition, so the same groups of samples ride together forever and the gradient noise stops being independent across passes; reshuffling is cheap and strictly better. When the data is streamed from shards too large to hold in memory, a permutation of the whole index set is not available. The working recipe is two-level: randomize the order of shards, interleave reads from several shards at once, and draw training samples through a shuffle buffer. The buffer only helps if it is **large relative to the run length of a single class** — a buffer of 1,000 samples cannot break up blocks of 10,000 identical labels. Sizing the buffer without checking the block structure of the files is the most common way this bug survives a supposed fix. ## Boundaries and exceptions Shuffling applies to *training* order. Evaluation order is irrelevant when the metric is an average over the whole set, so there is nothing to fix there. Sequence data is the case people cite as an exception, and it is usually a misunderstanding: you still shuffle the *sequences*, you simply do not shuffle timesteps within a sequence. Order is meaningful along the time axis, not along the sample axis. Finally, distinguish this from a genuinely noisy loss. A learning rate that is too large produces large, erratic swings that do **not** align across epochs, and it usually degrades from the start rather than showing clean structure. If someone reaches for the learning rate on seeing an epoch-periodic pattern, they are treating a data-ordering bug with a model-side knob, and the pattern will still be there afterwards.

  • Is shuffling once when the dataset is loaded enough, or must it be redone every epoch?
    Once is not enough. A single shuffle breaks the class correlation but freezes the batch partition, so the same samples travel together on every pass and the gradient noise repeats instead of being independent across epochs. Reshuffling the index order before each epoch costs almost nothing and gives fresh batch compositions, which is why it is the default expectation.
  • You stream from shards too large to fit in memory. How do you shuffle then?
    Two levels: randomize the order of shards, interleave reads from several shards at once, and draw samples through a shuffle buffer. The buffer must be large compared with the run length of a single class — a buffer of a thousand samples cannot break up blocks of ten thousand identical labels, so check the block structure of the files before trusting the buffer size.
  • Which is more suspicious — a loss that oscillates with epoch-length periodicity, or one that is noisy with no periodicity?
    The periodic one. Aperiodic noise is expected from minibatch sampling, and if it is severe it usually points to a learning rate that is too high or a batch that is too small. Periodicity locked to the epoch length can only come from a repeating visit order, which makes it a data-pipeline problem rather than an optimization one.

It is like revising from a stack of flashcards sorted by subject that nobody ever cuts: you look brilliant inside each block and go blank at every boundary, and the same blank spots come back on the next pass.

saying these in an interview costs you the question

  • Blames the learning rate for a strictly epoch-periodic loss pattern
  • Thinks one shuffle at load time covers every epoch
  • Says shuffling matters for the validation set too
  • Never inspects the label histogram of an actual batch
  • Assumes any oscillating loss means the batch size is too small

context

open as a page

How do you tell a too-high learning rate from a too-low one by the shape of the training loss curve?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A learning rate that is too high drops the loss fast, then leaves it oscillating inside a band or diverging; one that is too low gives a smooth, near-linear descent still falling at the last epoch.

open as a page

Why does initializing every weight in a network's hidden layers to zero break training?

level: juniorimportance: must knowfreq 74%

basics

~20 s

All units in a layer then compute the same output and receive the same gradient, so they update identically and stay duplicates forever. The layer has the power of a single unit. Random asymmetric values break that tie.

open as a page

How does Grad-CAM turn a convolutional network's feature maps into a class-specific heatmap?

level: middleimportance: must knowfreq 58%

basics

~20 s

Grad-CAM averages the gradients of one class score over each feature map of a chosen convolutional layer to get per-channel weights, sums the feature maps with those weights, and applies ReLU. The coarse result is upsampled onto the image.

open as a page

Which per-layer statistics reveal dead or saturated units in a neural network's training run?

level: middleimportance: must knowfreq 58%

basics

~20 s

Per layer, log the fraction of units that output zero for every example in a fixed probe batch, plus the fraction of tanh or sigmoid outputs past 0.99 in magnitude. Both are per-unit across the batch, not per example.

open as a page

What is double descent, and why does test error peak at the interpolation threshold?

level: middleimportance: must knowfreq 45%

basics

~20 s

Double descent is the pattern where test error falls, then rises to a peak at the interpolation threshold - the capacity at which a model can just barely fit every training label - and then falls again as capacity grows further.

open as a page

What is a flat minimum in a neural network's loss landscape, and why is it tied to generalization?

level: middleimportance: must knowfreq 52%

basics

~20 s

A flat minimum is a weight setting where training loss barely rises when the weights are perturbed. Test loss behaves like a slightly shifted training loss, so flat solutions stay low under that shift while sharp ones spike.

open as a page

How do you run a learning-rate range test to pick a first rate for a new model?

level: middleimportance: must knowfreq 52%

basics

~20 s

Run one short pass, multiplying the learning rate each step from tiny to divergent, and plot smoothed loss against rate on a log axis. Start the real run about a factor of ten below where the loss bottoms out.

open as a page

Why do you try to overfit a single small batch before launching a full training run?

level: middleimportance: must knowfreq 62%

basics

~20 s

Memorizing one fixed batch needs no generalization, so if the loss will not fall to near zero on eight examples the fault sits in the training machinery — gradient flow, step size, loss wiring — not in the dataset.

open as a page

A training run pins its initialization seed but still varies run to run - what else is random?

level: middleimportance: must knowfreq 66%

basics

~20 s

Initialization is only one of three random streams. The epoch shuffle that sets data order and the per-step stochastic operations - augmentation parameters, dropout masks, random masking - draw too, and parallel loading workers hold their own generators.

open as a page

Why does He initialization use a weight variance of 2/fan_in for ReLU layers?

level: middleimportance: must knowfreq 62%

basics

~10 s

ReLU zeros about half of a symmetric, zero-mean pre-activation distribution, halving the signal's second moment at every layer. Doubling the weight variance from 1/fan_in to 2/fan_in cancels that halving, so activation scale survives depth.

open as a page

A run trains cleanly but validation is far below expectation — how do you decide: data bug or model bug?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Work outward from the cheapest check. Score the same checkpoint twice to test whether the evaluation path is deterministic, then score training data through that same path, then inspect a fully transformed batch. Only after those come model-side knobs.

open as a page

NaN loss appears at step 12,001 of a previously healthy run — how do you find the cause?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Make it reproducible first: checkpoint the batch, the weights and the random state from the last good step and replay them. Then bisect forward — inputs, per-layer activations, loss, gradients — to the first value that is not finite.

open as a page

Five seeds of a ranking model span 0.6 AUC points - how do you judge a claimed +0.3 gain?

level: seniorimportance: must knowfreq 56%

basics

~20 s

A single run cannot resolve an effect half the size of the seed spread. Rerun both the baseline and the candidate over the same list of seeds, look at the per-seed differences, and report that distribution rather than the best run.

open as a page

What cross-entropy loss should a freshly initialized 1000-class classifier report on its first batch?

level: juniorimportance: should knowfreq 48%

basics

~20 s

About 6.9, which is ln(1000). An untrained head spreads probability roughly uniformly, so the correct class receives about 1/1000 and the loss is -ln(1/1000). A much larger reading means the initial outputs are far from zero.

open as a page

Why does a raw input-gradient saliency map for an image classifier look like speckle noise?

level: middleimportance: should knowfreq 44%

basics

~20 s

The gradient of a class score with respect to the pixels is a purely local slope of a jagged, piecewise-linear function, so it flickers pixel to pixel. Averaging over many noise-perturbed copies of the input makes it readable.

open as a page

A training loss decreases smoothly yet the model is useless — how do you check target-to-input alignment?

level: middleimportance: should knowfreq 44%

basics

~20 s

A falling loss only proves something is being minimized, not that it is the right thing. Assert exact shapes so no mismatch is silently broadcast, and decode a few loaded input-target pairs back to their source records.

open as a page

Which zero-denominator bugs make a loss return NaN on only some batches?

level: middleimportance: should knowfreq 50%

basics

~20 s

Denominators the data decides: a mean over a mask that is empty for that batch, a normalization by a channel of zero variance, an average over an element with no neighbours. Each is zero over zero, which gives NaN.

open as a page

Why can a network's validation loss sit below its training loss during the first few epochs?

level: middleimportance: should knowfreq 58%

basics

~20 s

Validation loss below training loss is usually a measurement artifact: training loss is measured on a network handicapped by dropout and augmentation and averaged across the epoch, while validation is measured at the epoch's end on the full network.

open as a page

Why can integrated gradients rank a prediction's pixels differently under a black baseline than a blurred one?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Integrated gradients explains a prediction relative to a chosen baseline input, so the baseline defines the counterfactual. An all-black baseline gives zero credit to already-black pixels; a blurred baseline keeps low-frequency content, so only the added detail earns attribution.

open as a page

Per-layer gradient norms logged every 50 steps put layer 1 four orders below layer 12 — what do you check?

level: seniorimportance: should knowfreq 46%

basics

~20 s

First make the comparison fair: raw norms grow with parameter count, so switch to a per-parameter root-mean-square or the update-to-weight ratio. Then check whether layer 1's weights actually move, and read the activation statistics in between.

open as a page

Why can a network's test error worsen for dozens of epochs and then improve for hundreds more?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Epoch-wise double descent lets a fixed-size network's test error fall, rise while it memorizes the hardest and most mislabelled training examples, and then fall again over a much longer training budget.

open as a page

Growing the training batch from 256 to 8192 keeps the final training loss but costs two points of test accuracy — why?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Equal training loss does not mean an equal solution. The large-batch run usually settles in a narrower basin whose loss climbs fast under small weight perturbations, and a narrow basin transfers worse to held-out data.

open as a page

How does sharpness-aware minimization change the training objective, and what does it cost per step?

level: seniorimportance: should knowfreq 35%

basics

~20 s

It minimizes the worst training loss inside a small ball around the weights rather than the loss at the weights. Each update needs a gradient at a perturbed point, so it costs about two passes per step.

open as a page

Why must you re-run a learning-rate range test after the batch size or initialization changes?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The curve describes a configuration, not an architecture. A larger batch averages away gradient noise, so the divergence knee moves up; a pretrained encoder sits near a good solution, so rates that were fine from scratch wreck its features.

open as a page

Why does a one-batch overfit test floor at 0.4 loss when random cropping and colour jitter stay on?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Augmentation means the batch is not fixed: each step shows a differently cropped and colour-shifted image, so the model fits a distribution instead of memorizing points. Switch augmentation off first, then the other noise sources.

open as a page

Your training loss sits flat at the majority-class prior for 20 epochs — what do you check?

level: seniorimportance: should knowfreq 44%

basics

~20 s

Check whether the plateau equals the entropy of the class base rate - that means the model emits the prior for every input. Then confirm outputs are constant, and inspect output-bias initialization, saturated units and step size before killing the run.

open as a page

A pneumonia classifier's Grad-CAM maps highlight a scanner watermark, yet held-out accuracy is high — do you ship it?

level: principalimportance: should knowfreq 28%

basics

~20 s

No. A map pointing at an acquisition artefact suggests the model learned which machine took the image, and a held-out split from the same sources validates that shortcut rather than exposing it. Confirm by masking, then fix the split.

open as a page

With a fixed training budget for a bake-off of eight variants, how do you split runs between variants and seeds?

level: principalimportance: should knowfreq 35%

basics

~20 s

Screen broadly, confirm narrowly. Give every variant one short run to eliminate clear losers, then promote two or three survivors to a paired multi-seed confirmation. Never ship on the screening ranking - a one-seed leaderboard reorders when rerun.

open as a page

An attribution map barely changes after a trained network's top layers are randomly reinitialised — what does that mean?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

The map does not depend on what the model learned, so it cannot be explaining that model's decision — it is acting as an edge or contrast detector on the input. A map that fails this sanity check is not evidence.

open as a page

showing 1–30 of 38