Skip to content
Tech Interview Prep
Technical interview guide

Neural Network Fundamentals

Forward pass, backpropagation, and the activation functions that make deep networks work.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Google ML Crash Course neural-network guidance, TensorFlow Keras guides, and PyTorch stable reproducibility guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain how a feed-forward neural network makes a prediction.

Answer

The 90-second answer

A feed-forward network is a fixed sequence of layers, and a prediction is one forward pass through them with the weights frozen. Each layer computes an affine map of its input, z = Wx + b, then applies a fixed nonlinearity, and hands the result to the next layer. The final layer emits raw scores (logits) or a scalar, and a task-specific head turns those into a class, a probability, or a value. Nothing is learned at inference; the only state that changes is activation buffers.

The mechanism, with numbers

Take a 2-2-1 MLP: two inputs, two ReLU hidden units, one sigmoid output. PyTorch 2.x nn.Linear stores weight shaped (out_features, in_features) and computes x @ weight.T + bias.

Input x = [1.0, 2.0].

Layer 1: W1 = [[0.5, -0.3], [0.2, 0.8]], b1 = [0.2, -0.2]

unitz = w·x + bReLU(z)
h10.5·1.0 + (-0.3)·2.0 + 0.2 = 0.10.1
h20.2·1.0 + 0.8·2.0 + (-0.2) = 1.61.6

Layer 2: W2 = [0.7, -0.5], b2 = 0.05

z = 0.7·0.1 + (-0.5)·1.6 + 0.05 = 0.07 - 0.8 + 0.05 = -0.68

p = sigmoid(-0.68) = 1/(1 + e^0.68) ≈ 0.336

So the prediction is class 1 at p ≈ 0.336, class 0 at 0.664. Parameter count: (2·2 + 2) + (2·1 + 1) = 9.

Why the nonlinearity matters: without it, stacking affine maps collapses to a single affine map, W2(W1x + b1) + b2 = (W2W1)x + (W2b1 + b2), so a 10-layer net would be exactly as expressive as a linear model. ReLU is the default because its gradient is 1 for positive inputs, which keeps gradients from vanishing with depth; sigmoid and tanh saturate and their gradients approach 0.

Alternatives and when to pick them

  • Activation: ReLU is cheap and the default; GELU is standard in transformers; tanh still appears in small control and RL nets where a bounded output helps.
  • Normalization: BatchNorm normalizes across the batch and needs running statistics at serving time; LayerNorm normalizes per example and behaves identically in train and eval, which is why transformers use it.
  • Depth vs width: for tabular data, 2-3 hidden layers of 64-256 units usually match much deeper nets; for images, convolutions share weights across positions and beat a dense net on parameter count.
  • When not to use an FFN: small tabular datasets (gradient-boosted trees usually win), sequences where you need position sharing (use a conv or attention), or anything needing calibrated uncertainty.

Failure modes

  • Shape mismatch: matmul raises at build time. Cheap, caught in seconds.
  • Train/serve skew: dropout left enabled, or BatchNorm using batch statistics instead of running stats. Detection: run a fixed input batch through the model in .eval() and through the serving path and diff the logits; a nonzero diff means the graphs differ.
  • Dead ReLU: a unit whose pre-activation is negative for every input has zero gradient forever. Detection: log the fraction of zeros per layer over a few thousand samples; a layer above ~50% zeros is suspect.
  • Saturation: sigmoid/tanh outputs piling at 0 or 1 give near-zero gradients. Detection: activation histograms.
  • Numerics: fp16 matmuls overflow past ~65504; loss scaling or bf16 avoids it.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

Why do neural networks need activation functions?

Answer

The 90-second answer. Stacked affine layers are still affine: W2(W1x + b1) + b2 = (W2W1)x + (W2b1 + b2). A 50-layer MLP with no activation between layers has exactly the representational power of a single linear layer, so depth buys nothing. An activation applied elementwise between layers is what breaks that collapse: it is the only source of nonlinearity in a standard feed-forward network, and it is what lets later layers compose curved decision boundaries out of earlier ones. ReLU is the usual default for hidden layers: cheap, and its gradient does not vanish for positive inputs. It is not free, units can die, and the output-layer choice (sigmoid, softmax) is about probability semantics, not about adding capacity.

The collapse, with numbers. Take W1 = [[1,2],[3,4]], b1 = 0, W2 = [1,1], b2 = 0. Two layers compute W2(W1x) = [4,6]x. A single layer with W' = [4,6] computes the same function for every x. No amount of depth escapes this without a nonlinearity in between.

What the common choices trade.

activationrangegradient behaviourtypical use
sigmoid(0,1)≤ 0.25, saturates at both endsoutput layer for binary probability; rarely hidden
tanh(−1,1)≤ 1, saturates at both ends, zero-centredhidden layers in small or recurrent nets
ReLU[0,∞)1 for x>0, exactly 0 for x<0default hidden activation
Leaky ReLU(−∞,∞)1 for x>0, 0.01 for x<0 (PyTorch default)drop-in when ReLU units die
GELU≈(−0.17,∞)smooth, non-monotonic near 0transformer blocks

Failure mode: dying ReLU. A unit whose pre-activation is negative for every input in the training distribution outputs 0 and receives gradient exactly 0, so it never recovers. It is permanently removed from the model's capacity. A large learning-rate step or badly scaled inputs can push a whole block's pre-activations negative at once, and you lose that fraction of the layer for the rest of training.

Python
import torch, torch.nn as nn

lin = nn.Linear(2, 3)
with torch.no_grad():
    lin.weight.copy_(torch.tensor([[1., 0.], [0., 1.], [-1., -1.]]))
    lin.bias.copy_(torch.tensor([0., 0., -5.]))

x = torch.tensor([[1., 2.], [3., 4.]])
pre = lin(x)            # [[1, 2, -8], [3, 4, -12]]
post = torch.relu(pre)  # [[1, 2,  0], [3, 4,   0]]
print((post == 0).all(dim=0))  # tensor([False, False, True])

Row [1,2] gives 1*1+0*2+0 = 1, 0*1+1*2+0 = 2, -1*1-1*2-5 = -8. Row [3,4] gives 3, 4, -3-4-5 = -12. Unit 3 is zero on every row, so its gradient is zero and it will not move.

  • Detect it: count units where the post-activation is zero for every row of the batch. (post == 0).all(dim=0). In a healthy layer with roughly zero-mean pre-activations, about half the units are zero for any given input; a unit that is zero across many batches is dead. Track the fraction over training, not once.
  • Cost: the effective width shrinks. If 30% of a 512-unit layer is dead, you are training a 358-unit layer and paying for 512.
  • Fix: Leaky ReLU or ELU (nonzero negative slope keeps gradient flowing), GELU, He/Kaiming initialisation matched to ReLU, a lower learning rate, or batch norm before the activation to keep pre-activations centred.

Failure mode: saturation. Sigmoid and tanh have gradients approaching 0 as |x| grows; a deep stack multiplies many small numbers together and the early layers stop learning. That vanishing-gradient problem is why ReLU-family activations displaced sigmoid in hidden layers.

What activations do not do. They do not calibrate outputs. Softmax produces numbers that sum to 1, not probabilities you can threshold on; a network trained with cross-entropy is typically overconfident and needs temperature or Platt scaling to be calibrated. They also do not remove the need for normalisation, residual connections, or a sane learning rate.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-3

Compare sigmoid, tanh, and ReLU.

Answer

Core answer. All three are elementwise nonlinearities; what separates them in practice is the shape of their derivative. Sigmoid maps to (0,1) with a derivative that peaks at 0.25. Tanh maps to (-1,1), is zero-centered, and its derivative peaks at 1.0. ReLU is max(0,x): derivative exactly 1 for x>0, exactly 0 for x<0. The default for hidden layers in feedforward nets and CNNs is ReLU or a variant; sigmoid and tanh survive where you need bounded or gating semantics: LSTM gates, binary output heads.

Why saturation matters: the arithmetic. Backprop multiplies one Jacobian per layer. A sigmoid layer contributes at most 0.25, so ten stacked sigmoid layers give 0.25^10 ≈ 9.5e-7: the loss gradient is essentially gone before it reaches layer 1. Tanh peaks at 1.0, but typical pre-activations sit near |x|≈1, where 1-tanh²(x) ≈ 0.42, so ten layers give ≈ 0.42^10 ≈ 1.7e-4. ReLU passes derivative 1 through every active unit, so the activation itself contributes no decay: only the weight matrices scale the gradient.

Zero-centering. Sigmoid outputs are all positive, so ∂L/∂w_ij across a whole row shares the sign of ∂L/∂z_j. Every weight in that row moves the same direction each step, and the optimizer zig-zags toward the optimum instead of heading straight at it. Tanh's mean is ~0, so signs vary and updates are better conditioned. ReLU is also not zero-centered (outputs ≥ 0), but its derivative is 1, so the effect is milder than sigmoid's.

Failure modes and how to detect them.

  • Dying ReLU: a unit whose pre-activation is negative for every input in the data distribution gets gradient 0 forever and never recovers. Detect by logging the fraction of units with zero activation per layer per batch; a layer drifting past ~50% dead is the signal. Fix with Leaky ReLU (max(0.01x, x)) or GELU (x·Φ(x)): both keep a nonzero negative-side gradient.
  • Sigmoid/tanh saturation: histogram pre-activations; mass beyond |x|>4 means gradients are near zero. Fix with normalization (BatchNorm/LayerNorm) or by switching to the ReLU family.
  • Exploding gradients: ReLU's unbounded positive side puts no cap on activations. Clip by global norm.
rangederivativezero-centeredmain failure
sigmoid(0,1)σ(1-σ), max 0.25novanishing grad, zig-zag
tanh(-1,1)1-tanh², max 1.0yesvanishing grad at extremes
ReLU[0,∞)1 or 0nodying units

Picking. Hidden layers of MLPs and CNNs: ReLU with He initialization. Transformers: GELU (BERT, GPT-2/3). RNN/LSTM internals: tanh for the cell state, sigmoid for the gates. Gates need (0,1) to act as a multiplicative switch. Output layer: sigmoid for independent binary labels, softmax for mutually exclusive classes, linear for regression. Avoid sigmoid/tanh in deep plain stacks without normalization.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-5

Explain backpropagation.

Answer

The 90-second answer. Backpropagation is reverse-mode automatic differentiation applied to a scalar loss. The forward pass records each operation and the intermediate values it produced; the backward pass walks that record in reverse, and at every op multiplies the gradient flowing in by that op's local derivative. The reason it is the default for neural nets: the loss is one scalar, so a single backward pass yields the gradient with respect to every parameter at once, at roughly the cost of one extra forward pass. Independent of how many parameters you have. It is not an optimizer and not a guarantee of a good minimum; it is a way to compute ∂L/∂θ exactly and cheaply.

A worked trace. One input x = 1.0, one ReLU hidden unit, one linear output, squared loss, target y = 3.0:

stepforwardvalue
z1w1·x, w1=0.50.5
hrelu(z1)0.5
ŷw2·h, w2=2.01.0
L(ŷ−y)²4.0

Backward, starting from ∂L/∂L = 1:

  • ∂L/∂ŷ = 2(ŷ−y) = 2(1−3) = −4
  • ∂L/∂w2 = ∂L/∂ŷ · h = −4 · 0.5 = −2
  • ∂L/∂h = ∂L/∂ŷ · w2 = −4 · 2 = −8
  • relu passes the gradient through unchanged because z1 = 0.5 > 0, so ∂L/∂z1 = −8
  • ∂L/∂w1 = ∂L/∂z1 · x = −8 · 1 = −8

With SGD at lr = 0.1: w1 → 0.5 − 0.1(−8) = 1.3, w2 → 2.0 − 0.1(−2) = 2.2. Re-running the forward pass gives ŷ = 2.86 and L = 0.0196, down from 4.0. That is the whole loop.

The same thing in code (PyTorch 2.3):

Python
import torch
x  = torch.tensor([1.0])
w1 = torch.tensor([0.5], requires_grad=True)
w2 = torch.tensor([2.0], requires_grad=True)
h  = torch.relu(w1 * x)
y_hat = w2 * h
loss = (y_hat - 3.0) ** 2
loss.backward()
print(w1.grad, w2.grad)   # tensor([-8.]) tensor([-2.])

The printed gradients match the hand trace. requires_grad=True is what makes the forward ops record the graph; backward() is the reverse sweep.

Trade-offs. Reverse-mode is the right choice when outputs ≪ inputs: one scalar loss against millions of parameters. Forward-mode computes one column of the Jacobian per pass, so it costs one pass per input dimension; it wins when inputs ≪ outputs (a small-input function with a wide Jacobian). Second-order methods: Newton needs the full Hessian, O(N²) memory, so it is impractical past a few thousand parameters; L-BFGS approximates it with a low-rank history and is common for small models; Hessian-free methods use conjugate gradient with Hessian-vector products obtained by a second backward pass, and pay for it in iterations. For a large network, plain first-order SGD/Adam with reverse-mode gradients is the default, and the alternatives are chosen only when the parameter count is small or curvature is genuinely the bottleneck.

Failure modes and how you catch them.

  • Vanishing gradients. Sigmoid's derivative peaks at 0.25, so a 10-layer sigmoid stack multiplies the gradient by ≤ 0.25¹⁰ ≈ 1e-6. Detect by logging per-layer gradient norms each step; if they shrink geometrically with depth, switch to ReLU/GELU or add residual connections.
  • Exploding gradients. The product of local derivatives grows past 1 and blows up, typically in RNNs. Detect with the same norm log; fix with global-norm clipping (clip_grad_norm_).
  • Dead ReLU. A unit whose pre-activation is negative has derivative exactly 0, so it receives no gradient and stays dead. Detect by counting units with zero activation across a batch.
  • Silent NaNs. log(0) or sqrt of a negative in a custom op poisons the whole backward pass. Run torch.autograd.gradcheck against finite differences on a small input, and enable torch.autograd.set_detect_anomaly(True) to get the op that produced the NaN.

Backprop gives you the gradient; whether that gradient points somewhere useful is a separate question about the loss surface and the optimizer.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4

How do you choose an output layer and loss?

Answer

Core answer (first 90 seconds). Two questions decide it: what does the target mean, and what does a wrong prediction cost? Target semantics pick the head; decision cost picks the loss.

  • Binary, one decision. One logit, BCEWithLogitsLoss. Two logits + softmax is over-parameterized: softmax over 2 classes is invariant to a constant shift, so the pair is redundant, and you lose the fused stability.
  • Exclusive multiclass. C logits, CrossEntropyLoss. It fuses log_softmax + NLLLoss, so the max-subtraction happens inside and you never materialize exp(large_logit).
  • Multilabel. C independent logits, BCEWithLogitsLoss per label. No softmax: labels aren't mutually exclusive, so probabilities must not be forced to sum to 1.
  • Regression. Match the loss to the noise model: MSE ↔ Gaussian, MAE ↔ Laplace, Huber for heavy tails, pinball for a quantile.

Why the pairings behave as they do. Softmax CE's gradient w.r.t. each logit is p − y. Trace it: logits [2.0, 1.0, 0.1], target class 0. exp gives [7.389, 2.718, 1.105], sum 11.212, so p = [0.659, 0.242, 0.099]. Loss −log(0.659) = 0.417. Gradient p − y = [−0.341, 0.242, 0.099], which sums to 0: only the relative logits matter, which is why a constant shift is free.

That gradient is the whole story for imbalance. At 99:1, a batch of 100 with 99 majority examples at p = [0.5, 0.5] gives a majority-logit gradient of (99·(0.5−1) + 1·(0.5−0))/100 = −0.49 and a minority-logit gradient of +0.49. The model is pushed toward the prior [0.01, 0.99] and minority recall goes to 0. Fix with class weights w_c = N/(2·N_c) (a heuristic: it rescales the effective loss, so retune the LR) or focal loss (gamma=2 down-weights easy examples).

Pinball max(q·(y−ŷ), (q−1)·(y−ŷ)) is asymmetric: at q=0.9 under-prediction costs 0.9 and over-prediction 0.1, so its minimizer is the conditional 0.9-quantile, not the mean. MSE's loss scales with the squared error, so an error of 100 is 10,000× the loss of an error of 1, but its gradient 2(ŷ−y) is only 100× larger. Huber (delta=1.0 in PyTorch) is quadratic below delta and linear above, capping that influence.

Stability, concretely. BCEWithLogitsLoss on logit 12, target 1 gives log(1+e^-12) ≈ 6.1e-6 with a live gradient. The naive log(sigmoid(x)) at logit 1000 saturates sigmoid to exactly 1.0 in float32, so log(1.0)=0 and the gradient (1−sigmoid)=0: the example stops learning. Always pass logits, never probabilities.

Python
# torch 2.x
head = nn.Linear(d, 1)                      # binary / per-label multilabel
loss = nn.BCEWithLogitsLoss(pos_weight=w)   # w = N_neg/N_pos for imbalance
# exclusive multiclass
head = nn.Linear(d, C)
loss = nn.CrossEntropyLoss(weight=w_c, ignore_index=-100)  # logits in, no softmax

Failure modes and detection.

FailureWhat breaksDetect
Softmax CE on 99:1minority recall → 0per-class recall, confusion matrix
Label smoothing 0.1overconfidence drops but ECE risesreliability diagram / ECE
MSE on heavy tailsoutlier dominates gradientloss spikes, residual plot
Sigmoid+BCE for exclusive classesprobs don't sum to 1, all can read 0.9sum of per-class probs
Weights set too highminority overfit, precision collapseper-class precision

When not to. Don't use softmax when classes overlap: use independent sigmoids. Don't use pinball if you need a point estimate and the mean is the right summary. Don't use MSE when you need calibrated quantiles or the target is heavy-tailed. Don't apply label smoothing if downstream calibration matters. State the encoding, reduction (mean vs sum), weights, and mask handling explicitly, and test them: a masked sum reduction silently rescales the loss by the number of valid tokens.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Why does weight initialization matter?

Answer

The 90-second answer

Initialization fixes two things: symmetry and scale. If every weight in a layer holds the same value, every unit produces the same output and receives the same gradient, so they stay identical forever: the layer is one neuron copied n times. Random weights break that. Scale is the second: activation and gradient variance propagate multiplicatively through depth, so a per-layer factor ρ becomes ρ^L after L layers. You want ρ ≈ 1. Xavier/Glorot sets Var(w) = 2/(fan_in + fan_out) for tanh and sigmoid. He/Kaiming sets Var(w) = 2/fan_in for ReLU, because ReLU zeroes half the activations and halves the variance, so the weights need twice the variance to compensate. Biases are normally zero-initialized; that is safe because the random weights already broke symmetry.

The arithmetic

50-layer MLP, fan_in = 100, tanh, w ~ N(0, 0.01²). Each layer multiplies activation variance by ≈ fan_in · Var(w) = 100 · 1e-4 = 0.01, so the standard deviation shrinks ×0.1 per layer. After 50 layers that is 1e-50: below float32's smallest normal (~1.2e-38), so activations underflow to zero around layer 38, gradients vanish, and the loss sits at ln(10) ≈ 2.30 for a 10-class problem and never moves.

He init on the same net: Var(w) = 2/fan_in = 0.02, multiplier = 100 · 0.02 · 0.5 = 1. Signal preserved.

Too large is the mirror: Var(w) = 1 with fan_in = 100 gives a ×100 variance multiplier per layer, so 1e10 by layer 5 and NaN by layer 10.

Diagnostic

Python
import torch, torch.nn as nn

torch.manual_seed(0)
net = nn.Sequential(*[nn.Linear(100, 100), nn.Tanh()] * 50)
for m in net:
    if isinstance(m, nn.Linear):
        nn.init.normal_(m.weight, std=0.01)   # deliberately too small
        nn.init.zeros_(m.bias)

x = torch.randn(64, 100)
for i, m in enumerate(net):
    x = m(x)
    if isinstance(m, nn.Linear):
        print(f"layer {i//2:2d}  act_std={x.std():.3e}")

Trace: layer 0 input std 1.0; tanh is linear for small inputs, so each Linear+Tanh pair multiplies std by √(fan_in)·w_std = √100·0.01 = 0.1. Layer 1 prints ~1e-1, layer 2 ~1e-2, and from about layer 38 the value is 0.000e+00: float32 underflow. Swap in nn.init.kaiming_normal_(m.weight, nonlinearity='relu') with a ReLU and the printed std stays near 1.0 across all 50 layers.

Trade-offs

initVar(w)pick whenavoid
zeros0biases; the output projection of a residual branch, so the block starts as identityany layer with >1 unit and no other symmetry break
Xavier/Glorot2/(fan_in+fan_out)tanh, sigmoid, linearReLU stacks: 2× too small
He/Kaiming2/fan_inReLU, LeakyReLUsaturating activations
orthogonalpreserves normRNNs, very deep netsnot worth it as a default

PyTorch's nn.Linear default is kaiming_uniform_ with a=√5, i.e. U(−1/√fan_in, 1/√fan_in), variance 1/(3·fan_in): smaller than He's 2/fan_in. It works because most nets have normalization layers; if yours doesn't, set it explicitly.

Normalization (BatchNorm, LayerNorm) makes init less critical but not irrelevant: the first layer and the norm's own γ still set the scale. Transformers scale residual output projections by 1/√(2N) for N residual layers for the same reason.

Failure modes and how you catch them

  • Symmetric/dead: all rows of W identical, loss flat at ln(C) from step 0. Check torch.equal(W[0], W[1]) or std across units.
  • Vanishing: per-layer activation std ratio < 0.5 sustained across depth; loss flat at ln(C). One forward pass on a random batch at init prints it.
  • Exploding: NaN/Inf loss within ~10 steps, grad norm > 1e6. Log grad norm; torch.autograd.set_detect_anomaly(True) localizes it.
  • Cost: a 50-layer run that dies at step 0 burns the full GPU budget. The one-batch check above costs seconds.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Compare SGD, momentum, and adaptive optimizers.

Answer

Assumptions: mini-batch training, fixed architecture and data, fp32, and each optimizer's learning rate tuned on a validation split. Without that, the comparison is just default-vs-default and tells you nothing about the algorithms.

Core answer. SGD is the baseline update θ ← θ − η·g. Momentum adds a velocity that averages gradients over time. Adaptive methods divide each coordinate by a running estimate of its gradient magnitude, so the step is roughly η regardless of how large that coordinate's gradient is. In practice: SGD + momentum 0.9 is still the default for vision CNNs; Adam/AdamW for transformers and sparse or ill-conditioned problems.

Mechanism.

  • SGD: θ ← θ − η·g_t. The mini-batch noise acts as a regularizer, but a fixed η cannot both move fast early and settle late, so you need a decay schedule (step or cosine).
  • Momentum: v_t = μ·v_{t−1} + g_t; θ ← θ − η·v_t. With μ = 0.9 the velocity averages roughly the last 1/(1−μ) = 10 gradients, damping oscillation across a ravine and accelerating consistent directions. Nesterov momentum evaluates the gradient at the look-ahead point θ − η·μ·v.
  • Adam: m_t = β₁·m_{t−1} + (1−β₁)·g_t; v_t = β₂·v_{t−1} + (1−β₂)·g_t²; then θ ← θ − η·m̂_t/(√v̂_t + ε), where m̂ = m/(1−β₁ᵗ) and v̂ = v/(1−β₂ᵗ). Defaults: β₁ = 0.9, β₂ = 0.999, ε = 1e-8, lr = 1e-3. AdamW decouples weight decay (θ ← θ − η·m̂/(√v̂+ε) − η·λ·θ, default λ = 0.01) instead of folding it into the gradient, where it would be rescaled by 1/√v̂.

Bias correction, traced. Constant g = 0.1, β₁ = 0.9, β₂ = 0.999, η = 1e-3, ε = 1e-8, t = 1. m = 0.1·0.1 = 0.01, v = 0.001·0.01 = 1e-5. Corrected: m̂ = 0.01/0.1 = 0.1, v̂ = 1e-5/0.001 = 0.01, step = 1e-3·0.1/(0.1 + 1e-8) ≈ 1e-3 = η. Without correction, m/√v = 0.01/0.00316 = 3.16, so the first step is 3.16× too large: v underestimates the second moment early. That is the whole job of the correction.

state per paramkey hyperparamsper-coordinate steptypical use
SGD1 (grad)η, schedulenoCNNs, when test accuracy matters
Momentum2 (grad + v)μ = 0.9noCNNs, RNNs
Adam/AdamW3 (grad + m + v)β₁, β₂, ε, λyestransformers, sparse gradients

Memory, real figures. For 1B params in fp32: SGD holds params + grads = 8 GB; momentum adds one buffer = 12 GB; Adam adds two = 16 GB. That 2× over SGD is why large-model training often uses Adafactor or sharded Adam.

Trade-offs and when to use. Adam's step is ~η per coordinate, so it is fast on ill-conditioned or sparse gradients and needs little LR tuning. The cost is generalization: Wilson et al. (2017) found SGD + momentum reaches better test accuracy than tuned Adam on CIFAR-10/ImageNet ResNets. Adam can also fail to converge on some convex problems (Reddi et al., 2018): AMSGrad fixes the specific counterexample. Choose SGD + momentum when you can afford an LR schedule and want the best held-out accuracy; choose AdamW when gradients are sparse, scales differ wildly across coordinates, or you want fast convergence with minimal tuning.

Failure modes. SGD diverges to NaN if η exceeds ~2/λ_max of the loss Hessian. Adam in fp16 overflows v (g² exceeds 65504): use loss scaling or bf16. With ε too small and a near-zero v̂, the step blows up; ε = 1e-8 is the floor. β₂ = 0.999 lags ~1000 steps, so a distribution shift leaves v̂ stale and the effective LR wrong. Detect all of these by logging gradient norm, update norm, and loss per step, not just final loss.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How do you choose learning rate and schedule?

Answer

I start by clarifying the budget and the model. If I'm training a transformer from scratch, I default to AdamW with lr 1e-4, weight decay 0.01, 1-2% warmup, and cosine decay to zero. If I'm training a ResNet with SGD, I default to lr 0.1 per 256 batch, momentum 0.9, and step decay by 0.1 at epochs 30, 60, 90. Those are starting points, not answers. Then I tune.

The learning rate sets the step size along the negative gradient. For a quadratic loss with curvature L, gradient descent diverges if lr > 2/L. Deep nets have a range of curvatures, so a step that's stable in early layers can blow up later ones. Warmup helps because at initialization gradients are large and their variance is high, especially with Adam where the second-moment estimate is noisy. A few hundred steps of linear warmup let those estimates settle. Normalization changes the effective step size: BatchNorm smooths the loss landscape, so you can use a larger lr; LayerNorm in transformers doesn't, so warmup matters more.

To pick the lr, I run a range test: increase lr exponentially from 1e-6 to 1e-1 over 200-500 steps, plot loss. Pick the lr an order of magnitude below the minimum. For schedule, if total steps are known, cosine or linear decay to zero is safe. If not, use ReduceLROnPlateau with patience 2-3 epochs and factor 0.1. Step decay works if you have milestones from prior runs.

Trade-offs: cosine needs total steps; if you early-stop, lr won't reach zero, which can cost final accuracy. Step decay is simple but requires guessing milestones. Plateau adapts but can be noisy and slow. Warmup is almost mandatory for transformers; for fine-tuning, a short warmup or none is fine because weights are already in a good region.

Failure modes: loss NaN means lr too high or warmup too short. Reduce by 3-10x and clip gradients at 1.0. Oscillating loss means lr too high. Slow decrease means lr too low. Validation loss rising while training loss falls is overfitting, not lr. On resume, save optimizer and scheduler state; otherwise the schedule restarts and you get a loss spike.

Here's a table of defaults I've used:

ModelOptimizerlrSchedule
ResNet-50 ImageNetSGD momentum 0.90.1 per 256 batchstep decay 0.1 at 30/60/90
BERT-base pretrainAdamW1e-4linear warmup 10k, linear decay
Transformer fine-tuneAdamW2e-5linear warmup 500, linear decay

And a PyTorch snippet for warmup + cosine:

Python
import math
from torch.optim.lr_scheduler import LambdaLR
warmup, total = 500, 10000
lr_lambda = lambda step: step/warmup if step < warmup else 0.5*(1+math.cos(math.pi*(step-warmup)/(total-warmup)))
scheduler = LambdaLR(optimizer, lr_lambda)

Trace: at step 0, lr=0; at step 500, lr=1e-4; at step 10000, lr=0. If I resume at step 6000, I must load scheduler state or the lr jumps back to 1e-4.

Linear scaling: batch 256 -> lr 0.1; batch 1024 -> lr 0.4, with warmup to avoid early divergence.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How does batch size change optimization and generalization?

Answer

The 90-second answer. Assume we mean samples per optimizer step, not per device, and that the data budget and epoch count are fixed. Batch size changes three things: the variance of the gradient estimate, the number of updates per epoch (N/B), and how well batch statistics estimate population statistics. The first two drive optimization and generalization; the third is a batch-norm detail that bites hard.

Small batches give a noisy gradient, and that noise is not purely a nuisance: it is an implicit regularizer. Each step is a random draw around the true gradient, so the optimizer keeps getting kicked out of sharp, narrow minima and tends to settle in flatter regions that generalize better. Keskar et al. (2016) documented the large-batch generalization gap and tied it to minimum sharpness. Large batches average the noise away: a more accurate descent direction, but a more brittle solution unless you compensate.

The standard compensation is the linear scaling rule (Goyal et al., 2017): multiply the learning rate by B/256 when you multiply the batch by the same factor, and add warmup. Their ResNet-50 recipe is batch 8192, LR 3.2 = 0.1 × 8192/256, 5-epoch warmup, 90 epochs, one hour on 256 GPUs. Drop the warmup and the first steps at LR 3.2 diverge. For Adam-family optimizers the linear rule is usually replaced by square-root scaling, because the update is already normalized by the second moment.

Scaling stops paying off. McCandlish et al. (2018) define the gradient noise scale B_noise ≈ tr(Σ)/|G|²: the batch size at which gradient noise equals the gradient signal. Below it, doubling the batch roughly halves the steps to reach a target loss. Above it you buy almost nothing per step and burn memory. B_noise is measured empirically and grows during training as |G| shrinks.

Small batch (32)Large batch (4096)
Updates per epoch (N = 1,281,167)40,036313
Gradient noisehighlow
LR under linear rule (base 0.1 at 256)0.01251.6
Memory per steplowhigh
Typical failurenoisy, slow wall-clockunderfits at fixed epochs; sharp minima

Failure modes and how to detect them.

  • Batch norm at small batch. Per-batch mean and variance are noisy, and the running estimates (PyTorch momentum 0.1) lag behind. Train and eval diverge: training loss keeps falling while validation plateaus, and the gap narrows when you freeze the running stats. Fix with SyncBatchNorm across devices, or switch to GroupNorm/LayerNorm.
  • Large batch, no LR scaling. Each step moves too little relative to the reduced noise, so time-to-quality gets worse, not better. Detect by plotting loss against wall-clock, not steps.
  • Large batch, scaled LR, no warmup. Divergence in the first hundred steps. Detect by watching the loss in the first epoch.
  • Fixed epoch budget. Fewer updates per epoch means you may need more epochs, which changes the comparison you thought you were making. Compare steps-to-target-loss, not epochs.

If you keep the sampling semantics intact (group or time-based splits, no shuffling across a boundary) the batch size is a pure optimization knob, and the honest way to tune it is to measure B_noise and stop scaling once you cross it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Compare batch normalization and layer normalization.

Answer

The 90-second answer. Both layers re-center and re-scale activations, then apply a learned per-element affine (γ, β). The difference is which axes the mean and variance are taken over, and whether the layer carries state between calls.

BatchNorm takes statistics over the batch and spatial axes, per channel: for an (N, C, H, W) tensor it reduces over N·H·W for each of the C channels, and it keeps running_mean/running_var to use at eval time. LayerNorm takes statistics over the feature axes, per example: for an (N, C) tensor it reduces over C for each of the N rows, and keeps nothing.

That one difference decides most of the practical behavior. BatchNorm couples the examples in a batch, one sample's output depends on the others, so it needs a batch large enough for the statistics to mean anything (in practice ≥16–32 per device) and it behaves differently in train and eval. LayerNorm is per-example, so batch size 1 is fine and train/eval are identical. That is why transformers use LayerNorm, and why convnets trained with small per-GPU batches switch to SyncBN or GroupNorm.

Mechanism. The coupling is not just a forward-pass artifact. The gradient of the loss with respect to one example's pre-norm activation contains a term proportional to 1/N that sums over the whole batch, so the update for sample i depends on samples j ≠ i. The batch-to-batch variation in μ and σ also injects noise into every activation, which acts as a regularizer: the reason BN often lets you drop or reduce dropout in convnets. Santurkar et al. (NeurIPS 2018) showed the main optimization benefit is a smoother, better-conditioned loss landscape, not the internal-covariate-shift story from the original Ioffe & Szegedy paper.

LayerNorm's benefit is per-example scale invariance: multiplying the input by a scalar leaves the output unchanged, so the layer is insensitive to weight-scale drift. In transformers, pre-LN (normalize before the sublayer, as in GPT-2) keeps residual-branch variance from growing with depth, which is why pre-LN trains without the long warmup the original post-LN Transformer needed.

BatchNormLayerNorm
Axes reducedN, H, W per channelfeature dims per example
Staterunning_mean/var, PyTorch momentum=0.1none
Batch sizedegrades below ~16–32/deviceany, including 1
Train vs evaldifferent (batch stats vs running)identical
Costreduction over N·H·W per channel; saves stats for backwardreduction over C per token
Typical useResNet/ConvNeXt, detection with SyncBNtransformers, RNNs, per-token MLPs

Trace. Both layers default to eps=1e-5, affine=True.

Python
import torch, torch.nn as nn
x = torch.tensor([[1.0, 2.0, 3.0, 4.0]])   # N=1, C=4
bn = nn.BatchNorm1d(4)   # train mode
ln = nn.LayerNorm(4)
print(bn(x))
print(ln(x))

BN reduces over the batch axis, which has size 1, so per channel μ = x_c and σ² = 0. Then (x−μ)/√(0+1e-5) = 0, and with γ=1, β=0 the output is tensor([[0., 0., 0., 0.]]): the signal is gone. LN reduces over the 4 features: μ = 2.5, σ² = 1.25, so the output is tensor([[-1.3416, -0.4472, 0.4472, 1.3416]]). Same input, opposite outcome.

Failure modes.

  • BN, batch too small. Train-mode loss is noisy and running stats are estimated from few samples. Log running_var against the batch variance over the last 100 steps; if they diverge, eval-time normalization is wrong. Fix with SyncBN across devices, or GroupNorm.
  • BN, stale running stats. Fine-tuning on a new domain with a small batch leaves running_mean/var far from the new distribution, so eval accuracy drops while train accuracy looks fine. Evaluate the same checkpoint with model.eval() and with BN forced to batch stats; a gap of more than a point or two means the stats are stale. At momentum=0.1, running_mean reaches only 99% of a new mean after ~44 steps (0.9ⁿ = 0.01), so short fine-tunes never catch up.
  • BN, track_running_stats=False. Eval also uses batch stats, so batch size 1 at serving time produces the zero output above.
  • LN, wrong axis. Normalizing over the batch dimension instead of the feature dimension removes the per-example signal you want to keep, and it trains silently: loss falls, accuracy is worse. Assert normalized_shape matches the last dims of the tensor.
  • LN in convnets. Per-pixel LN over C only is a weak normalizer; GroupNorm (Wu & He, 2018) is the usual substitute when batch size is small.

When BatchNorm is the wrong choice. Any setting where the batch is small or the examples are not i.i.d.: detection or segmentation at 2 images per GPU, sequence models with variable-length batches, or serving where you cannot reproduce the training batch distribution. There the running statistics are either badly estimated or actively misleading, and a batch-independent normalizer is the right call.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do dropout and batch normalization differ between training and inference?

Answer

The 90-second answer. Both layers change behaviour between train and eval, and both changes exist to keep the expected output consistent across the two. Dropout injects noise only during training and compensates for it on the spot, so inference is a plain identity. BatchNorm normalizes with statistics drawn from the batch during training and from a running buffer at inference, so inference is deterministic and independent of what else is in the batch. The bug class is identical: run inference in train mode and your outputs depend on the batch.

traineval
Dropoutsample mask, scale by 1/(1-p)identity
BatchNormnormalize with batch stats, update running buffersnormalize with frozen running stats, no update

Dropout: inverted scaling. With p=0.5 and activations [4.0, -2.0], a mask [1, 0] gives [8.0, 0.0] after multiplying by 1/(1-p)=2. Expected output is 0.5·8.0 + 0.5·0.0 = 4.0, equal to the input, so nothing needs rescaling at test time. This is inverted dropout, what torch.nn.Dropout and Keras Dropout implement. The 2012 formulation scaled by p at test time instead; you only meet that in old code. Without the 1/(1-p) factor, dropping units shrinks the expected activation by (1-p), biasing every downstream pre-activation.

BatchNorm: two statistic sources. In train mode it computes mean and variance over the batch (per channel across N,H,W for conv), normalizes, then applies learned gamma/beta. In parallel it updates the running buffers as an exponential moving average: running = (1-momentum)·running + momentum·batch_stat. PyTorch defaults are momentum=0.1, eps=1e-5; Keras defaults are momentum=0.99 (weight on the old value: the opposite convention) and eps=1e-3. Trace with PyTorch defaults, running_mean starting at 0 and batch means 2.0 then 3.0: after batch 1, 0.9·0 + 0.1·2.0 = 0.2; after batch 2, 0.9·0.2 + 0.1·3.0 = 0.48. At inference it normalizes with those frozen buffers and updates nothing, which is what makes serving deterministic.

The buffers are an EMA with an effective window of roughly 1/momentum ≈ 10 batches, so they lag a shifting distribution and are noisy early in training. Evaluating before they converge, or on a distribution that differs from training, is exactly when frozen stats are the wrong choice.

Trade-offs. BatchNorm needs batch statistics, so at batch size 1 or very small the estimates are noisy and train-mode normalization itself becomes batch-dependent. LayerNorm and GroupNorm remove that dependence: LayerNorm is standard in transformers (per token), GroupNorm is common in detection and segmentation where batches are small, InstanceNorm in style transfer. Frozen running stats are wrong when you fine-tune on a shifted distribution (recalibrate them or use train-mode statistics) or when they never converged. Dropout placement matters too: put it after the activation, not immediately before a BatchNorm, because the dropped zeros corrupt BN's variance estimate. In convnets dropout usually lives only in the classifier head; in transformers it sits on attention weights and residual branches, typically p=0.1.

Failure modes and detection. Forgetting model.eval() makes outputs vary with batch composition and keeps updating running stats during inference: feed one sample at batch size 1 and again inside a batch of 32 and diff the logits; a mismatch means train mode. After export, checkpoints must carry running_mean, running_var and num_batches_tracked; a golden test comparing offline and served logits on the same input catches a dropped buffer. Dropout left on at serving gives stochastic outputs: two forward passes on identical input should be bit-identical.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

How do you regularize a neural network?

Answer

Core answer

Regularization is any constraint that keeps validation loss from diverging from training loss. I don't reach for one technique; I pick the cheapest control that closes the gap I actually measured.

Default order for a supervised net:

  1. More or better data and augmentation: cheapest, zero inference cost.
  2. Weight decay: one hyperparameter, zero inference cost.
  3. Early stopping: free, always on.
  4. Dropout and label smoothing: only if the gap survives the first three.

Then I read the curves. Train loss falling while val loss rises is variance: add capacity control. Both high is bias: regularization won't help, get more capacity or better features.

Mechanisms and numbers

  • Weight decay. SGD with L2 adds λw to the gradient: w ← w − lr·(g + λw). With lr=0.1 and λ=1e-4, every step multiplies w by (1 − 1e-5). In Adam this is not equivalent: the penalty is divided by √v̂, so parameters with a small gradient history get shrunk harder. AdamW (Loshchilov & Hutter, 2019) decouples it: w ← w − lr·λ·w applied outside the adaptive step. Typical λ: 0.01–0.1 for AdamW, 1e-4–5e-4 for SGD with momentum.
  • Dropout. Inverted dropout: at train time zero each activation with probability p and scale survivors by 1/(1−p); at inference it is the identity. p=0.5 for hidden layers, 0.2 for inputs (Srivastava et al., 2014). It averages over 2^n weight-sharing subnetworks per step.
  • Label smoothing. Replace the one-hot target with (1−ε) on the true class and ε/K spread over the rest; ε=0.1 is typical. It stops the logit gap from growing without bound.
  • Early stopping. Stop when val loss hasn't improved for patience epochs, then restore the best checkpoint.

Worked trace: inverted dropout

x = [2, 4, 6, 8], p = 0.5, mask = [1, 0, 1, 0]:

train output = [2, 0, 6, 0] × 1/(1−0.5) = [4, 0, 12, 0].

E[output] = 0.5·(2·2) + 0.5·0 = 2 = x. Inference: output = [2, 4, 6, 8], no scaling, which is why inference is a no-op.

Trade-offs and when not to use

  • Dropout and BatchNorm conflict: BN's batch statistics already inject noise, so dropout on the same activations slows convergence. Pick one.
  • Dropout hurts convnets with small spatial maps and transformers trained on large corpora: modern LLMs use weight decay with dropout=0.
  • Weight decay on biases and norm parameters (γ, β) usually hurts; exclude them.
  • Early stopping needs a clean val split. Under heavy augmentation the val loss is noisy, so smooth the metric before comparing.

Failure modes

  • Over-regularized: train loss plateaus high, val ≈ train but both bad. Detect: train accuracy stuck well below capacity. Fix: lower λ or p.
  • Dropout left on at inference: predictions are stochastic and mis-scaled. Detect: two forward passes on the same input differ.
  • Augmentation leakage: random crops applied before the train/val split inflate val. Detect: val accuracy collapses on a held-out set collected later.
  • Weight decay too high under Adam: sparse-gradient parameters collapse. Detect: embedding norms shrink toward zero over training.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How do you decide the depth and width of a neural network for a given problem?

Answer

Let the problem fix the ends, then let learning curves fix the middle.

Input width is whatever you actually feed the network: 784 for a 28×28 grayscale image, or the concatenated embedding dimensions for tabular data. Output width is the prediction you need: one unit for regression, C for C-way classification. Neither is a design choice; they are constraints on the first and last layer.

For the hidden stack I start from a baseline rather than guessing: one or two hidden layers at width 64–256 for tabular or small problems, or a convolutional stack where spatial size halves and channel count doubles for images. Then I read the learning curves. Train and validation loss both plateau high → underfitting, add capacity. Train loss keeps falling while validation loss turns up → capacity is sufficient, and the gap is a data or regularization problem, not a sizing one.

Depth and width buy different things:

DepthWidth
BuysCompositional, hierarchical features: layer k+1 combines layer k's featuresSmooth approximation within one feature level
Parameter costOne n×n matrix per added layerQuadratic in the middle of the stack
LatencySequential; layers cannot overlapParallel within a layer; memory-bound
Failure modeVanishing gradients, stalls without skip connectionsOverfits, dominates memory and step time

Parameter arithmetic makes the budget concrete. A dense stack costs Σ(n_i·n_{i−1} + n_i). For 784→256→256→10 that is 200,960 + 65,792 + 2,570 = 269,322 parameters, and forward FLOPs are roughly 2× that per sample, about 0.54 MFLOP. The asymmetry matters: widening a hidden layer from 256 to 512 adds 256·256 ≈ 65k parameters in the layer below and 512·256 ≈ 131k above, so width costs quadratically mid-stack, while one extra layer costs a single 256×256 matrix. Under a fixed latency budget, depth is usually the cheaper unit of representational power, until optimization degrades, which is where residual connections earn their place.

Connectivity is a separate decision from size. Multiple inputs, multiple heads, or a shared trunk mean the Functional API, not Sequential:

python import tensorflow as tf inp = tf.keras.Input(shape=(128,)) trunk = tf.keras.layers.Dense(256, activation="relu")(inp) head_a = tf.keras.layers.Dense(1, name="regression")(trunk) head_b = tf.keras.layers.Dense(5, activation="softmax", name="class")(trunk) model = tf.keras.Model(inp, [head_a, head_b])

Concrete failure modes: a narrow bottleneck (784→8→10) underfits and no schedule rescues it; a deep plain stack without skips stalls early; an oversized first layer dominates parameter count and memory while adding little accuracy. Detect all three by ablation: halve a width or drop a layer and check whether the validation metric actually moves. If a linear model or gradient-boosted trees match it, do not scale the network at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What do residual or skip connections change about a deep network: both in what it can represent and in how easily it trains?

Answer

Two separate claims: what the network can represent, and what SGD can find. Residual connections mostly change the second, and they make the first monotone in depth.

Start with the degradation problem. A plain 20-layer and a plain 56-layer conv net on CIFAR-10: the 56-layer net has higher training error, not just higher test error (He et al., 2016). That rules out overfitting. And the deeper net strictly contains the shallower one: set the extra layers to identity and it reproduces the 20-layer function exactly. The function class is fine; the optimizer cannot reach it.

The fix is y = x + F(x). Backward, dL/dx = dL/dy · (I + ∂F/∂x). The identity term is the point. In a plain stack the gradient reaching layer 0 is a product of per-layer Jacobians; if each has norm 0.5, 50 layers give 0.5^50 ≈ 8.9e-16, below float32 epsilon (1.2e-7): the signal is gone before it arrives. With residual blocks, expanding the product of (I + ∂F_i/∂x_i) gives a sum over 2^L paths, one of which is the pure identity with magnitude 1. Early layers get a gradient that is a sum of many terms, none of which has to be large. Forward, the same identity path preserves signal variance, and each block only has to learn a small perturbation rather than a full transformation.

python import tensorflow as tf from tensorflow.keras import layers

def residual_block(x, filters, stride=1): shortcut = x y = layers.Conv2D(filters, 3, strides=stride, padding="same", use_bias=False)(x) y = layers.BatchNormalization()(y) y = layers.ReLU()(y) y = layers.Conv2D(filters, 3, padding="same", use_bias=False)(y) y = layers.BatchNormalization()(y) # zero-init gamma -> block starts as identity if stride != 1 or x.shape[-1] != filters: shortcut = layers.BatchNormalization()( layers.Conv2D(filters, 1, strides=stride, use_bias=False)(x)) return layers.ReLU()(layers.Add()([shortcut, y]))

propertyplain stackresidual stack
parametersbaselineunchanged, plus 1x1 projection only when channels or stride change
gradient to layer 0product of Jacobians, geometric decaysum over 2^L paths, identity term = 1
training error, 56 vs 20 layers56 worse56 better
activation memoryone branchboth branches kept for backward

When I add a skip rather than change depth, width, or normalization: the signature is training loss getting worse as I add depth. That is degradation, and connectivity is the lever. If training loss is fine and the validation gap is the problem, that is capacity and regularization: width, dropout, data. If activations or gradients are badly scaled at initialization, that is init and normalization. Skip and normalization are complementary, not alternatives: the standard ordering is BN-ReLU-Conv inside the branch, with the last BN gamma zero-initialized so every block starts as identity and the network is effectively shallow at step 0.

Failure modes I check for. Shape mismatch when stride or channel count changes: needs the 1x1 projection, and forgetting it is a hard error, not a silent one. Residual branch collapse: if ||F(x)|| / ||x|| drifts toward zero across most blocks, the depth is decorative; I log that ratio per block. Memory: a residual block holds both branches' activations for backward, so the same parameter count costs more activation memory than a plain block. And because the identity path lets the network bypass a branch, a badly conditioned branch can be ignored rather than fixed: useful for optimization, but it means added depth is not automatically added capacity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How would you debug a neural network whose loss does not decrease?

Answer

First 90 seconds. Ask two things before touching code: is the loss flat from step 0, or does it drop and then plateau? And is it train loss or val loss? Flat-from-zero points at a correctness bug in the forward/loss/backward path; drop-then-plateau points at optimization or data scale. Assume PyTorch 2.x, supervised classification, cross-entropy, AdamW at lr=1e-3, batch 32.

The fastest discriminator is to overfit a tiny batch. Take 8 examples, call model.train(), disable augmentation, dropout and weight decay, and run 300 steps. A correct pipeline drives train loss well under 0.1 on 8 examples. If it doesn't, stop tuning: the bug is in the wiring, not the hyperparameters.

Python
import torch, torch.nn as nn
torch.manual_seed(0)
model = Net().train()
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.0)
xb, yb = next(iter(train_loader))
xb, yb = xb[:8], yb[:8]
for step in range(300):
    opt.zero_grad()
    logits = model(xb)
    loss = nn.functional.cross_entropy(logits, yb)
    loss.backward()
    if step == 0:
        print("init loss", loss.item(), "expected", torch.log(torch.tensor(10.)).item())
        for n, p in model.named_parameters():
            print(n, None if p.grad is None else round(p.grad.norm().item(), 6))
    opt.step()
print("final loss", loss.item())

Two numbers from that loop tell you most of it. At step 0, cross-entropy on C classes with near-uniform logits should be about ln(C): 2.303 for 10 classes. An initial loss of 0.0 usually means you applied softmax and then passed probabilities into CrossEntropyLoss, which applies log_softmax again. An initial loss far above ln(C) means labels and inputs are misaligned. Second, every parameter should have a non-None gradient with norm in the 1e-3 to 1e-1 range early on. All-None means the graph is detached: a stray .detach(), .item(), or numpy round-trip. All-zero with unchanged weights means lr=0, frozen params, or an optimizer built before the model moved to the device.

Then the failure modes, each with its signal:

symptomlikely causedetection
loss flat at ln(C) from step 0labels shuffled independently of inputstiny-batch overfit fails; shuffle labels and confirm loss stays at ln(C)
init loss ≈ 0softmax applied before CrossEntropyLosspass logits, not probabilities
grads all Nonegraph detached by .detach()/.item()/numpyprint p.grad is None per parameter
grads zero, weights unchangedlr=0, frozen params, optimizer built before .to(device)snapshot one weight before and after opt.step()
loss NaN within tens of stepslr too high, or log(0) in a custom losstorch.isfinite(loss) each step
loss magnitude off by ~batch sizereduction='sum' instead of 'mean'compare loss to per-example mean

Ordering matters: correctness before tuning. Only once the tiny batch converges do you touch initialization, normalization, batch size, schedule, or capacity. The one case where you skip the tiny-batch test is when loss already decreases on small data but plateaus on the full set: that's a scale/optimization problem, not a bug, and the fix is LR schedule, batch size, or normalization. If you suspect a custom layer rather than the pipeline, gradient-check it against numerical gradients, or swap in a torchvision reference model to isolate your code.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

How would you debug exploding or vanishing gradients?

Answer

Assume a deep stack (24 transformer blocks, or an RNN unrolled over 500 steps) and settle one thing first: did the loss go to NaN, or did it just stop improving? That splits exploding from vanishing before any tooling comes out.

Core answer. Log every layer's gradient norm before clipping, then read the ratio between consecutive layers rather than the absolute norm. On a healthy deep net, ||g_l|| / ||g_(l+1)|| stays within about 10x of 1 at every depth. Vanishing shows as that ratio pinned at 1e-2..1e-4 over ten layers or more. Exploding shows as a ratio above 1 compounding with depth, or a total norm that climbs step over step. Absolute norms track the learning rate and the AMP loss scale, so on their own they cannot tell you which failure you have.

Why it behaves that way. Backprop multiplies one Jacobian per layer, so the gradient reaching layer 1 is the product over l of dh_l/dh_(l-1), each factor roughly (activation derivative) x (weight spectral norm). Sigmoid's derivative tops out at 0.25 at z = 0; tanh's, 1 - tanh^2(z), drops below 0.07 once |z| > 2. Ten sigmoid layers with unit weights bound the gradient at layer 1 at 0.25^10 = 9.5e-7 of the output-layer gradient. ReLU's derivative is exactly 1 for z > 0, so depth alone is not the cause: saturating nonlinearities and mis-scaled weights are.

Initialization supplies the other half. He init sets Var(W) = 2/fan_in, the value that keeps activation and gradient variance flat across depth (the 2 pays for ReLU zeroing half the units); Glorot's 2/(fan_in + fan_out) does the same job for tanh. PyTorch's nn.Linear default is neither: it is kaiming_uniform_(a=sqrt(5)), i.e. U(-1/sqrt(fan_in), 1/sqrt(fan_in)), Var = 1/(3*fan_in), which is 0.41x He in standard deviation per layer. Check that before blaming the architecture.

Python
import torch

# after loss.backward(), before optimizer.step()
pre_clip = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
g = {n: p.grad.detach().norm().item()
     for n, p in model.named_parameters() if p.grad is not None}
print(step, float(pre_clip), g["layers.0.weight"], g["layers.23.weight"])

clip_grad_norm_ returns the total norm as computed before clipping, so this print is the real number. Logging the norm after clipping reads the clamp instead of the gradient: the most common reason an exploding run looks fine on a dashboard.

What you seeReadingMove
pre-clip norm 1e2 to 1e5 over ~50 steps, then NaNexplodingcheck warmup and LR first, then clip; max_norm = 1.0 is the de facto transformer default (GPT-3 lists a gradient clip of 1.0)
consecutive-layer ratio 1e-3 for 10+ layers, loss flatvanishingHe init, GELU/ReLU, residual + norm
ratio near 1, norm 1e3, loss noisyLR too high, not an architecture bugwarmup, lower LR
update:weight ratio (lr *g

Failure modes to rule out. Clipping hides explosion, so always log the pre-clip value. AMP is a second mask: torch's GradScaler starts at 65536, doubles the scale after 2000 clean steps, and halves it while skipping the step on inf/nan. Repeated halving means real overflow upstream, and each skip means no parameter moved that step. A fully padded attention row makes softmax over all -inf return NaN at one sequence position, which looks like explosion but is a masking bug. BatchNorm uses batch statistics in train and running statistics at eval, so a pattern visible only in train mode points at normalization, not depth. Truncated BPTT only exposes the last k steps of an RNN, hiding long-range decay. And fp32 survives the diagnosis: a layer-1 gradient of 9.5e-7 against weights of O(1) gives lr * g = 1e-9 at lr = 1e-3, below fp32's 1.19e-7 relative precision, so w - lr * g rounds straight back to w.

After a fix, re-read the same per-layer ratios, then disable clipping for one step and confirm the pre-clip norm is still stable: otherwise clipping is doing the work and the run will fail the moment you raise the LR.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do mixed precision and loss scaling affect training?

Answer

Core answer (first 90 seconds).

Assume an Ampere-or-later NVIDIA GPU, PyTorch, and a model whose matmuls dominate the step. Mixed precision means: store weights, activations and gradients in fp16 or bf16, keep an fp32 master copy of the weights, and run the optimizer update in fp32. The matmuls hit tensor cores, which on an A100 run 312 TFLOPS in fp16/bf16 against 19.5 TFLOPS in fp32, about 16x, and halve the bytes moved for weights and activations.

The catch is fp16's exponent: 5 bits, so max 65504, min normal 6.1e-5, subnormals down to 5.96e-8. Typical gradients sit at 1e-5 to 1e-7, so many flush to zero. Loss scaling fixes that: multiply the loss by S before backward, so gradients come out as S·g, then unscale by 1/S before clipping and the optimizer step. With S = 65536 (2^16, PyTorch's GradScaler default), a 1e-7 gradient becomes 6.55e-3, representable, and is restored to 1e-7 in fp32.

bf16 has 8 exponent bits, the same range as fp32, so it needs no loss scaling at all. That is the main reason to prefer it on Ampere and later.

Dynamic scaling. The scale is not fixed. GradScaler starts at 65536, doubles it every 2000 clean steps (growth_interval), and on inf/nan halves it and skips that step. So S tracks the gradient magnitudes instead of being a guess.

fp16bf16fp32
exponent bits588
mantissa bits10723
max655043.4e383.4e38
min normal6.1e-51.2e-381.2e-38
loss scalingrequirednot neededn/a
A100 tensor core312 TFLOPS312 TFLOPS19.5 TFLOPS
Python
scaler = torch.cuda.amp.GradScaler()          # init_scale=65536, growth_interval=2000
with torch.cuda.amp.autocast(dtype=torch.float16):
    out = model(x); loss = criterion(out, y)  # loss computed in fp32
scaler.scale(loss).backward()                 # grads are S*g, stored fp16
scaler.unscale_(optimizer)                    # back to g in fp32
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer); scaler.update()       # skips step on inf/nan, adapts S

Failure modes.

  • Overflow: a scaled gradient S·g above 65504 becomes inf. With S = 65536, any |g| above roughly 1 overflows. GradScaler sets found_inf and skips the step.
  • Scale collapse: repeated overflow halves S; if it reaches 1 and still overflows, every step is skipped and training stalls with no error. Watch the scale value and the skipped-step rate.
  • Silent underflow: if S is too small, gradients flush to zero and the loss plateaus. Detect by histogramming unscaled gradient norms, not by waiting for a crash.
  • Ops without fp16 kernels: large-dim reductions and batchnorm lose precision in fp16; keep them in fp32 (Apex O2 does this for batchnorm).
  • bf16's 7 mantissa bits give about 2 decimal digits against fp16's 3, so some models converge worse in bf16 even though it needs no scaler.

When not to use it. If bf16 is available, use it: no scaler, no skipped steps. Skip mixed precision for small models where memory is not the bottleneck, for CPU-only training, and for numerically delicate losses (large-logit softmax, some RL objectives) unless you have verified convergence against an fp32 baseline.

What I would check. Convergence curves and held-out metrics against fp32, the scaler value and skipped-step rate over time, and export parity: fp32 weights out of the checkpoint.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you investigate training that works on CPU but diverges on GPU?

Answer

First I pin down what "diverges" means, because the two cases are different bugs. If the very first forward pass already differs, it's numerics or a kernel. If the loss tracks for 500 steps and then blows up, it's accumulation or optimizer state. I state my assumptions out loud: same code, same batch order, same init checkpoint, and I'm allowed to slow the GPU down. I do not assume bitwise identity is achievable: it isn't across different reduction trees.

The core move is to bisect on one batch. Load the checkpoint, run a single forward pass on both devices, and compare the logits tensor, not the loss. The loss hides where the difference enters. Then walk layer by layer; the first layer whose max-abs diff exceeds tolerance is the culprit.

Mechanism, because that's what the interviewer is probing. Floating-point addition isn't associative. A CPU sums a reduction sequentially; a GPU splits it across warps and blocks and combines partial sums in a tree. Same inputs, different grouping, different rounding. In FP32, 1e8 has an ulp of 8, so 1e8 + 1.0 rounds back to 1e8. Sum [1e8, 1.0, -1e8] left to right: (1e8 + 1.0) = 1e8, then 1e8 - 1e8 = 0.0. Tree order: (1e8 + -1e8) + 1.0 = 1.0. Same three numbers, answers 0.0 and 1.0. That's your divergence, and it isn't a bug.

Second mechanism: TF32. On Ampere and later, cuDNN convolutions default to torch.backends.cudnn.allow_tf32 = True, while matmul TF32 is opt-in. TF32 keeps 10 mantissa bits instead of 23, so a matmul that runs FP32 on CPU carries roughly 1e-3 relative error on GPU. That alone explains a loss that drifts.

Third: AMP. GradScaler starts at 65536, doubles every 2000 steps, halves on overflow. If the CPU path runs FP32 and the GPU path runs autocast, you're comparing two different precisions.

Failure modes, each with how I detect it:

  • Nondeterministic kernel: run the same GPU forward twice on the same input. If the two GPU outputs differ, it's the kernel, not the device. Fix with torch.use_deterministic_algorithms(True) plus CUBLAS_WORKSPACE_CONFIG=:4096:8; it raises on ops with no deterministic version instead of silently differing.
  • TF32: set both cudnn.allow_tf32 and cuda.matmul.allow_tf32 to False and rerun. If the divergence shrinks to ~1e-6, it was precision, not logic.
  • AMP overflow: log the GradScaler scale each step. A scale that collapses toward 1.0 means repeated inf/nan in grads: real numerical instability, not a platform difference.
  • NaN: torch.autograd.set_detect_anomaly(True) points at the op that produced it.

Trade-offs: determinism costs throughput. Deterministic cuDNN algorithms and disabled TF32 can run 10-30% slower, and some ops have no deterministic kernel at all. So I don't ship determinism globally; I use it to localize, then decide whether the residual difference is within tolerance for the task.

Tolerance: torch.testing.assert_close defaults to rtol=1.3e-6, atol=1e-5 for FP32. If my per-layer diff is under that, I stop. If it's 1e-3, I keep going.

Finally I minimize: shrink to the smallest layer and batch that reproduces, and add a regression test that runs on both devices at that tolerance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you make neural-network experiments reproducible?

Answer

The 90-second answer

"Reproducible" splits into two claims, and I'd ask which one before answering. Bitwise-identical numbers on the same hardware and library stack is achievable and worth it for debugging. The same conclusion on a different GPU is statistical reproducibility, same metric within a stated tolerance, and you get that by fixing data, code and environment and reporting dispersion across seeds. I'll assume the strict version.

The recipe: fix every input to the computation, then remove the nondeterminism that parallel floating-point introduces.

Why it's nondeterministic

Three mechanisms, and naming them is most of the answer:

  1. Floating-point addition isn't associative. A parallel reduction (summing a batch, or the all-reduce in DDP) accumulates in whatever order threads finish, so the rounding differs run to run.
  2. CUDA atomics. Embedding backward, scatter_add and index_add use atomicAdd; the update order isn't fixed.
  3. Kernel selection. cuDNN and cuBLAS choose algorithms by heuristic or by timing. cudnn.benchmark=True times candidates and picks the fastest, which varies between runs; cuBLAS picks different algorithms for different workspace sizes.

On top of that, dropout, shuffling and augmentation consume RNG.

What I set

Python
import os, random, numpy as np, torch

os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"  # before CUDA init
os.environ["PYTHONHASHSEED"] = "0"

random.seed(0); np.random.seed(0)
torch.manual_seed(0); torch.cuda.manual_seed_all(0)

torch.use_deterministic_algorithms(True)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False

DataLoader:

Python
g = torch.Generator(); g.manual_seed(0)

def worker_init_fn(worker_id):
    s = torch.initial_seed() % 2**32
    np.random.seed(s); random.seed(s)

loader = DataLoader(ds, batch_size=64, shuffle=True, generator=g,
                    num_workers=4, worker_init_fn=worker_init_fn)

CUBLAS_WORKSPACE_CONFIG is required for deterministic cuBLAS on CUDA 10.2+; without it use_deterministic_algorithms(True) raises on the first matmul.

Why order matters: a trace

Python
xs = np.full(100, 1e-8, dtype=np.float32)
acc = np.float32(1.0)
for x in xs:
    acc = np.float32(acc + x)      # 1.0 — each 1e-8 is below half an ulp
acc2 = np.float32(1.0) + xs.sum()  # 1.000001 — smalls summed first

float32's ulp at 1.0 is ~1.19e-7, so 1.0 + 1e-8 rounds back to 1.0. Sum the smalls first and you get 1e-6, which survives. Same inputs, different reduction order, different result: the whole problem in one line.

Trade-offs and failure modes

  • Throughput. Deterministic kernels are slower. Illustrative, from one A100 run: step time went 210 ms → 245 ms (~17%) with deterministic algorithms on and benchmark off. Measure your own; the penalty is workload-dependent.
  • Missing kernels. Some CUDA ops have no deterministic implementation and use_deterministic_algorithms(True) raises. Use warn_only=True or replace the op.
  • Cross-hardware. Changing GPU count changes all-reduce order; changing driver or cuDNN changes algorithm choice. Bitwise reproducibility holds per (hardware, driver, library) tuple, not across them.
  • Precision. TF32 and AMP change rounding; set the allow_tf32 flags and fix the AMP dtype.
  • Data. Version the split, the preprocessing and the augmentation, or the seeds reproduce the wrong data.

What I'd report

For a result that matters: N seeds, mean and standard deviation, and the tolerance you'd accept. Bitwise determinism is a debugging tool; statistical reproducibility is what a conclusion rests on.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

What should a training checkpoint contain?

Answer

Core answer. A resumable training checkpoint is four groups of state, and each group exists because a specific thing breaks without it. Model state, optimizer state, training-loop state, and provenance. If you can name what breaks when a group is missing, you know what belongs in the file.

1. Model. The architecture config plus every tensor that changes the forward pass: parameters and buffers. BatchNorm's running_mean, running_var and num_batches_tracked are buffers, not parameters, and they are not in model.parameters(). Drop them and eval metrics shift after resume. Frozen or non-trainable weights still belong here: they affect the forward pass even though the optimizer never touches them.

2. Optimizer. optimizer.state_dict(). For Adam/AdamW that is two fp32 moment buffers per parameter (exp_avg, exp_avg_sq) plus the step count. Drop it and momentum restarts at zero: you see a loss spike for a few hundred steps before the moments rebuild. SGD with momentum is one buffer per parameter; that difference is why optimizer state dominates checkpoint size.

3. Training-loop state. Global step and epoch, LR scheduler state, AMP GradScaler.state_dict(), RNG states, and the data-sampler position. Drop the step and the LR schedule restarts at its initial value; drop the scaler and AMP re-discovers its loss scale from scratch; drop RNG and dropout and augmentation differ, so the run is not reproducible; drop sampler position and the epoch boundary duplicates or skips samples.

4. Provenance. Code commit, config hash, library versions, hardware/driver, and the data snapshot id. Without these a checkpoint is loadable but not reproducible.

Python
ckpt = {
    "model": model.state_dict(),        # params + buffers
    "optim": optim.state_dict(),        # Adam: exp_avg, exp_avg_sq, step
    "sched": sched.state_dict(),
    "scaler": scaler.state_dict(),      # AMP GradScaler
    "step": global_step, "epoch": epoch,
    "rng": {"torch": torch.get_rng_state(),
            "cuda": torch.cuda.get_rng_state_all(),
            "numpy": numpy.random.get_state(),
            "py": random.getstate()},
    "sampler_epoch": sampler.epoch,     # DistributedSampler.set_epoch
    "provenance": {"commit": git_sha, "config_hash": cfg_hash,
                   "torch": torch.__version__, "data_snapshot": snap_id},
}

Sizing, worked. Take 7B parameters, bf16 weights, Adam, fp32 optimizer states and fp32 master weights. Weights 14 GB; master weights 28 GB; exp_avg and exp_avg_sq at 28 GB each = 56 GB. Total ≈ 98 GB per checkpoint. That is why retention is a policy, not an afterthought: last-3-plus-best is four times that.

Format and write. torch.save (pickle) is the default and handles arbitrary state dicts; safetensors for weights-only artifacts; torch.distributed.checkpoint when the model is sharded across ranks and you want to reshard on load. Write to ckpt.tmp on the same filesystem, fsync, then os.replace: atomic on POSIX. Record a sha256 of the file so a truncated write fails at load, not at step 40k.

Serving artifact is a different object. It intentionally omits optimizer, scheduler, scaler, RNG and sampler state, and exposes a versioned inference signature. Do not ship the training checkpoint to the inference server.

Restore test. Load the checkpoint, run one known batch, take one optimizer step, and compare the loss to the value recorded at save time within a stated tolerance. That is the only check that catches a missing RNG or sampler field.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

A model has great training accuracy but poor validation accuracy. What do you do?

Answer

Start by pinning down what the gap actually is, because "great train, poor val" is three different problems wearing one label. I'll assume a same-distribution held-out split, accuracy as the metric, and something like 99% train against 78% val. The gap size and the shape of the learning curve decide whether this is variance, leakage, or a broken evaluation, and I check the last two first, because they're cheap and they masquerade as overfitting. Only when those are clean do I treat it as variance and reach for regularization or more data.

Leakage is the one people skip. If the same entity (a user, a document, a near-duplicate image) lands in both splits, the model memorizes that entity's label. Train accuracy climbs because it has seen the answer; val accuracy on genuinely unseen entities stays flat. Two cheap detections: group rows by entity ID and check the overlap between splits, and shuffle the labels and retrain. If val accuracy stays well above chance on shuffled labels, say 60% on a balanced binary task, the split is leaking, not the model overfitting.

Then read the learning curve. Train on 10%, 25%, 50%, 100% of the data and plot train and val loss:

symptomlikely causefirst check
val near chance, train highleakage or label misalignmententity overlap; shuffle-label test
val loss falls then risesoverfittingearly stopping on val
train and val both high, convergingunderfittingcapacity, features
val fine in dev, bad in proddistribution shiftfeature drift (PSI or KS test)

A gap that stays wide and flat as you add data is variance. A gap that closes as data grows means you were data-starved, not over-parameterized.

That table is the trade-off. More data versus more regularization is decided by the curve, not by taste. If val loss is still decreasing at your full dataset, more data is the higher-leverage fix: variance error falls as you add samples, and no amount of dropout substitutes for it. If you can't get data, regularize: dropout in the 0.1–0.5 range, weight decay around 1e-4 to 1e-2 with AdamW, and early stopping on the val metric. Shrinking the architecture only helps when train loss fits in a few epochs: otherwise you're trading variance for bias you didn't have.

Concrete failure modes, with how I'd catch each:

  • Over-regularizing a leakage problem. You'll flatten the gap, ship, and fail in production because the model never learned the generalizable signal. Detection: hold out a truly unseen entity set and re-measure.
  • Preprocessing parity break. Augmentation or normalization applied in training but not at validation inflates the gap. Detection: push a val batch through the training pipeline and diff the tensors.
  • Label misalignment. Class-index mapping differs between train and val. Detection: print the val confusion matrix and check the class distribution against train.

Worked example, hypothetical numbers: 50k rows, 99% train / 78% val. Shuffle-label test gives 51% val: clean. Learning curve shows val loss still dropping at 50k. I double the data to 100k; val moves to 86%, train drops to 97%. The remaining gap is variance I can regularize, not a split bug. If instead the shuffle test had returned 62%, I'd stop tuning and fix the split first: every regularization knob would have been wasted effort. Tune on a development split, keep the final test untouched, and report seed dispersion so a single lucky run doesn't drive the decision.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you decide when to stop training a neural network?

Answer

I pin down three things first: the metric that decides (validation loss, or the task metric on a split that never feeds gradients), the noise floor of that metric, and the compute budget. Then I stop on the validation signal, never on training loss: training loss keeps falling while the model overfits, so it cannot tell me when to quit.

Concretely, early stopping watches a monitored quantity, requires an improvement larger than min_delta, tolerates patience epochs without one, and restores the weights from the best epoch. In Keras 3:

python import keras

early = keras.callbacks.EarlyStopping( monitor="val_loss", min_delta=1e-2, patience=8, restore_best_weights=True, start_from_epoch=5, mode="min") reduce = keras.callbacks.ReduceLROnPlateau( monitor="val_loss", factor=0.5, patience=3, min_lr=1e-5)

model.fit(x, y, validation_data=(x_val, y_val), epochs=200, callbacks=[early, reduce])

The ordering matters: ReduceLROnPlateau's patience must be shorter than EarlyStopping's, or the run ends before the LR drop has had a chance to move the metric. With 3 and 8, the run gets two LR reductions before it can quit.

A trace where this fires correctly (illustrative numbers, ~40 s/epoch):

epochtrain lossval losslrnote
11.421.381e-3
50.610.661e-3
120.340.411e-3best val so far
150.290.441e-33 epochs flat → halve LR
160.270.435e-4
220.210.395e-4new best, patience resets
280.180.412.5e-4
360.160.422.5e-48 epochs since epoch 22 → stop, restore epoch 22

Val loss bottoms at 0.39 on epoch 22 while training loss keeps dropping to 0.16. The last 14 epochs cost about 9 minutes and bought nothing.

What goes wrong:

  • Stopping on training loss, or on a metric computed on the training split. Both are monotone-ish and will never trigger.
  • Patience shorter than the metric's noise. With a 2,000-example validation set, epoch-to-epoch val-loss standard deviation is often around 0.01; a min_delta of 1e-4 tracks noise and stops on a random dip. Set min_delta at or above the observed spread, or monitor an EMA-smoothed validation metric.
  • Stopping mid-schedule. Cosine decay or a warm restart is designed to finish at low LR. If the rule fires at the first plateau you never collect the gain the schedule was going to deliver. Either make patience cover the schedule, or run the schedule to completion and stop on the final metric.
  • Plateau-then-drop. Runs sometimes sit flat for many epochs, then improve after an LR drop or a phase transition. Short patience kills them.
  • Peeking at validation repeatedly turns it into a training set. The stopping epoch is a hyperparameter chosen on validation; report the final number on a test split touched once.
  • Wrong metric. If you care about F1 or calibration at a threshold, monitor that, not val loss: they disagree often enough to matter.

When not to use it: fixed-budget training (large pretraining runs, big sweeps) usually stops on a step or token budget with the schedule annealed to zero, because a per-run early-stopping decision makes runs incomparable and wastes the tail of the schedule. Early stopping is also a regularizer in its own right, the cheapest one, so if you rely on it, don't tune weight decay as though the validation curve were clean.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

You have 5,000 labelled images for a new classification task. Walk me through how you decide between training from scratch, using a pretrained model as a frozen feature extractor, and fine-tuning some or all of its weights.

Answer

Three things decide this before any code: how many labelled examples I have, how close the new domain is to the pretraining corpus, and whether I have unlabelled in-domain data. Compute budget decides how far I can push, not where I start.

For 5,000 labelled images my default is a frozen ImageNet backbone plus a new head. It trains in minutes, gives a number to beat, and cannot overfit the body because the body is not moving. If that linear probe lands near chance, pretraining is not transferring, then I look at scratch training, or self-supervised pretraining on unlabelled in-domain data, before spending anything on fine-tuning.

The table I actually use:

labelled examplesdomain close to pretrainingdomain far from pretraining
<1kfrozen features + linear headfrozen features from an earlier block; a classical baseline may compete
1k–10kunfreeze last block + headunfreeze 2–3 blocks, heavy augmentation
10k–100kfine-tune the whole net at low LRfine-tune whole net, or scratch if in-domain pretraining data exists
>1Mscratch is competitivescratch

Unfreezing order is head first, then the last block, then progressively deeper. Early layers encode edges and textures that transfer almost everywhere and hold most of the parameters, so they are the last thing I let move. Concretely, with ResNet-50 (25.6M parameters) and 4,000 training images at batch 32, one epoch is 125 steps: ten epochs is 1,250 steps, more than enough to overfit, so the schedule stays short.

Learning rates are discriminative: head at 1e-3 with Adam, body at 1e-5 to 1e-4, i.e. 10–100x lower, with warmup and cosine decay. A randomly initialized head at 1e-3 sends large gradients into the body, which is why the head trains alone first.

python import tensorflow as tf

base = tf.keras.applications.ResNet50(weights="imagenet", include_top=False) base.trainable = False

inputs = tf.keras.Input(shape=(224, 224, 3)) x = tf.keras.applications.resnet50.preprocess_input(inputs) x = base(x, training=False) # frozen BN must stay in inference mode x = tf.keras.layers.GlobalAveragePooling2D()(x) x = tf.keras.layers.Dropout(0.2)(x) outputs = tf.keras.layers.Dense(5, activation="softmax")(x) model = tf.keras.Model(inputs, outputs) model.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_ds, validation_data=val_ds, epochs=5)

stage 2: unfreeze the last block, drop the LR 100x

base.trainable = True for layer in base.layers[:-30]: layer.trainable = False model.compile(optimizer=tf.keras.optimizers.Adam(1e-5), loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_ds, validation_data=val_ds, epochs=10)

training=False matters: a frozen BatchNorm layer still updates its moving statistics when called in training mode, and with batch 8 those statistics are noisy enough to wreck validation accuracy even though no weight changed.

Failure modes I watch for:

  • Catastrophic forgetting. Validation loss jumps in the first epoch after unfreezing everything at head LR. The tell is a fine-tuned model scoring below the frozen-feature baseline I already measured. Fix: unfreeze less, lower the body LR, re-check against that baseline.
  • Overfitting the small fine-tune set. Train 99%, validation 71% after three epochs. Fix: freeze more blocks, fewer epochs, augmentation, weight decay, early stopping on validation loss.
  • Domain mismatch. Spectrograms or histopathology look nothing like ImageNet; a frozen probe near chance is the signal to pretrain in-domain rather than fine-tune harder.

I'd report the frozen-probe accuracy, the fine-tuned accuracy, and the gap, so the choice is a measured one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How do you detect data leakage in a neural-network pipeline?

Answer

The 90-second version. Leakage is any feature whose value at training time depends on information that does not exist at the moment you would have to score that row in production. It is not a code smell you can grep for, it is a property of the join between your feature pipeline and your label, so I detect it with differential experiments: change one thing about how the data was assembled, retrain, and watch whether the metric moves. If AUC collapses when you fix a join, the join was the model.

Assumptions I state up front: I know the prediction timestamp and the label horizon ("will this user churn in the next 14 days"), and I have the raw event tables with their own timestamps, not just the assembled feature matrix. Without those two things you cannot tell a leak from a strong feature.

Cheapest check first: a timestamp assertion. Every training row must satisfy max(feature_ts) <= event_ts. That runs in seconds in CI and catches the most common leak: a snapshot table joined on the wrong side.

Python
import pandas as pd

events = pd.DataFrame({
    "user_id": [1, 1, 2],
    "event_ts": pd.to_datetime(["2024-03-01 10:00", "2024-03-03 09:00", "2024-03-02 12:00"]),
    "label": [0, 1, 0],
})
snapshots = pd.DataFrame({
    "snapshot_ts": pd.to_datetime(["2024-03-01 00:00", "2024-03-02 00:00", "2024-03-03 00:00"]),
    "sessions_7d": [4, 9, 12],
})

ok = pd.merge_asof(
    events.sort_values("event_ts"), snapshots.sort_values("snapshot_ts"),
    left_on="event_ts", right_on="snapshot_ts", direction="backward",
)
print(ok[["user_id", "event_ts", "sessions_7d"]])

Trace: rows sort to 03-01 10:00 (user 1), 03-02 12:00 (user 2), 03-03 09:00 (user 1). backward takes the latest snapshot at or before each event, so the values are 4, 9, 12 in that order. Switch to direction="forward" and the first row picks up the 03-02 snapshot: sessions_7d=9, which counts activity that happened after the event that produced the label. The third row gets NaN, because no snapshot exists after it. That NaN is the second tell: a leaky join usually cannot cover the prediction-time rows at all, so it silently drops or fills them.

Then the retraining tests, in increasing cost. Numbers below are illustrative for a churn model, not benchmarks.

testwhat it catchesleak signalcost
label shuffleany feature encoding the targetAUC stays above ~0.55 after permuting labels; should sit at 0.501 training run
group holdoutsame entity in train and testAUC falls 0.94 → 0.78 when users are split by ID1 run
time holdoutas-of joins, post-outcome fields, driftAUC falls 0.92 (random split) → 0.61 (train before T, test after)1 run
single-feature ablationone column carrying the labeldropping it costs >0.15 AUC1 run per group

Trade-offs. A random split gives you more training rows and a lower-variance estimate, and it is fine when the process is stationary and every feature is genuinely point-in-time. A time holdout throws away your most recent data and gives a noisier number, but it is the only honest split once any as-of logic exists. Ablation is the only test that catches leakage the network has learned to lean on, and it costs a full training run per feature group: on a 6-hour job you cannot run forty of them, so you run the timestamp fixture on every pipeline change and the retraining tests once per feature addition. Label shuffle is cheap and catches gross leakage, but it misses leakage confined to a subset of rows. Ablation is confounded by redundancy: drop one of two correlated leaky features and the metric barely moves.

Failure modes and their signals. A post-outcome field like account_closed_date shows up as single-feature AUC near 1.0 and a random-split score of 0.99 against 0.52 on a time holdout. Target encoding computed on the full frame leaks the label directly; recompute it out-of-fold and compare. A scaler or tokenizer vocabulary fit before the split leaks test statistics: usually only a point or two, but it is real and it is free to fix. Early stopping or checkpoint selection on the test set turns it into a validation set; hold out a third split and the reported number drops. A 10M-parameter network will memorize a leaky column that has a handful of rows, and regularization does not help, because the problem is in the data, not the capacity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you evaluate whether a neural network is better than a simpler model?

Answer

What a strong candidate says first (60–120 s). "Better" isn't a property of a model, it's a property of the decision the model drives. So before training anything I fix three things: the incumbent (whatever is actually in production. A business rule, logistic regression, or gradient-boosted trees), the split (time-based, matching deployment, not a random shuffle), and one primary metric tied to the action the model takes. Then the neural net has to clear two bars: beat the baseline by more than the run-to-run noise of its own training, and still be worth its operational bill. If the gain sits inside the seed spread, the answer is no, whatever the mean says.

Why the noise band and not the mean. A single training run is one draw. Retrain the same architecture with five seeds and the spread is often as large as the difference you're trying to claim. That's the mechanism behind "stability across seeds": if seed variance is about the size of the lift, you're measuring the seed, not the model. Same logic for the split: a random split leaks near-duplicate rows across train and test and inflates every model, but it inflates the high-capacity one most.

Learning curves before the bake-off. If the net's train and validation curves converge at a low value, it's data-limited and more data may close the gap; if train sits far above validation, it's overfitting and that gap, not the baseline, is what to fix first. Comparing a net that hasn't converged against a tuned baseline is a wasted experiment.

Worked check (hypothetical numbers). Incumbent logistic regression scores 0.812 AUC on a held-out time window. The net, five seeds: 0.818, 0.826, 0.809, 0.821, 0.817. Mean 0.8182, sample sd 0.0062. The mean gain is 0.0062: exactly one standard deviation of the net's own seed-to-seed spread. That is not a win; it's a coin flip with a nicer architecture. I'd need more seeds to shrink the interval, or a gain several times the spread, before spending GPU inference on it.

Compare at the operating point, not the ranking metric. AUC is threshold-free; the product ships a threshold. So the comparison is decision-shaped:

logistic regressionneural net
AUC (time-split holdout)0.8120.818 ± 0.006
rows flagged at the frozen threshold41,20038,900
precision at that threshold0.310.33
p99 latency at peak QPS12 ms180 ms
retrain cadencequarterlymonthly

(Hypothetical figures.) The net ranks better and flags 2,300 fewer rows at slightly higher precision: that's the number the on-call team feels. It also costs 15× the tail latency and 3× the retraining cadence. Whether that trade is good depends on the cost of a false positive versus a false negative, which I'd ask for before choosing.

Failure modes and how I'd catch them.

  • Slice regression. The net wins overall and loses on a segment: a rare locale, a new device class. Detect by evaluating per-slice with a confidence interval wide enough to matter; a slice whose interval crosses zero in the wrong direction blocks the swap.
  • Calibration drift. Better ranking, worse probabilities, so the frozen threshold flags the wrong volume. Detect with a reliability curve and Brier/ECE, plus the flagged-count column above; if flagged volume moves more than the team can absorb, recalibrate before shipping.
  • Latency tail. A single-request benchmark hides queueing. Detect with a load test at peak QPS, watching p99, not the mean.
  • Faster decay. The net degrades quicker between retrains. Detect by holding back a later time window and comparing metric decay against the incumbent's.

Fairness of the comparison. Same features, same split, same tuning budget. Giving the net a 200-trial hyperparameter search and the baseline its defaults is the most common way a "win" is manufactured. For significance, use a paired test on the same rows: McNemar's test on the disagreement counts, or a paired bootstrap over per-row errors, not two independent intervals.

Curated: · Written: · Reviewed:

Difficulty: Hard