Deep Learning: Neural Networks and Architectures Questions
How deep neural networks are built and trained. Covers network fundamentals, activation functions and non-linearity, loss function selection, backpropagation, optimization and learning-rate behavior, and diagnosing vanishing or exploding gradients, along with the major architecture families: convolutional networks for images and recurrent networks, LSTMs, and GRUs for sequences. Emphasizes both how to train deep networks stably and how to match an architecture family to the structure of the data.
Describe common learning-rate schedules: step decay, exponential decay, cosine annealing (with and without restarts), cyclical schedules, and linear warmup. Explain why warmup is commonly used for large models and which schedules pair well with large-batch training.
Sample Answer
Direct answer
Learning-rate schedules all answer the same question, how should the step size change over training, differently: step and exponential decay shrink it on a fixed schedule, cosine annealing shrinks it smoothly (optionally with periodic restarts), cyclical schedules deliberately move it up and down, and warmup ramps it up from near zero before any of the above kicks in.
Structured elaboration
Step decay multiplies the learning rate by a fixed factor at specific milestones (e.g. divide by 10 at epochs 30, 60, 90); simple, and gives clean, large "phase changes" useful for coarse-to-fine training. Exponential decay applies ηt=η0e−kt, a smooth continuous shrink with no manual milestone tuning required. Cosine annealing follows ηt=ηmin+21(ηmax−ηmin)(1+cos(πt/T)) over T steps, giving a smooth cool-down that empirically often out-performs step decay's abrupt jumps; with restarts (SGDR), the schedule periodically jumps back up to ηmax partway through training, deliberately re-injecting exploration to help escape a poor local region before resuming the cool-down. Cyclical learning rates instead deliberately cycle the rate between a lower and upper bound throughout training (not just at restarts), which can reduce how precisely you need to have tuned the base learning rate in the first place, since the cycle itself sweeps through a range of values. Linear warmup ramps the learning rate up from near zero to its target value over the first few hundred or thousand steps, BEFORE any decay schedule takes over.
Why warmup matters for large models: at the very start of training, weights (and for adaptive optimizers, the moment estimates) are uncalibrated, so a full-strength learning rate applied immediately can produce a large, destabilizing update before the network or optimizer state has had any chance to settle; warmup avoids this by keeping early updates small while things calibrate, which becomes especially important as model size, batch size, or the base learning rate grow.
Which schedules pair well with large-batch training: warmup is close to mandatory at large batch sizes (large batches typically use a correspondingly larger learning rate via the linear scaling rule, which makes the destabilizing-early-update risk warmup addresses even more acute); cosine annealing (with or without restarts) is the most common pairing with warmup for large-scale training, since its smooth decay complements a smooth ramp-up, whereas step decay's abrupt drops can feel like a second, smaller version of the same instability warmup was meant to avoid.
Worked example
A standard large-model recipe: linear warmup over the first 5% of total training steps (rate rising linearly from 0 to the target learning rate), followed by cosine annealing down to a small floor value for the remaining 95% of steps, with no restarts; this exact combination is the de facto default for most modern transformer training recipes precisely because both halves are smooth and compose cleanly.
Trade-offs & pitfalls
A common mistake is applying a schedule's decay starting from step 0, INCLUDING the warmup period, which causes the rate to be simultaneously rising (from warmup) and falling (from the decay schedule) and produces a confusing, unintended shape; warmup and the main decay schedule should be sequenced as two distinct phases, not blended from the start. A second common gap is choosing a schedule independent of batch size; a schedule tuned for one batch size (in particular its warmup LENGTH and the total number of decay steps) often needs to be re-tuned, not just have its peak learning rate rescaled, when batch size changes substantially.
You observe the training loss oscillating (decreasing, then increasing, repeatedly). Explain the likely causes (optimizer, learning rate, architecture) and propose specific corrective actions with your reasoning.
Sample Answer
Direct answer
A loss that repeatedly decreases then increases is usually the optimizer overshooting a minimum and bouncing back out, and the fix almost always starts with lowering the learning rate or momentum before considering anything architectural.
Structured elaboration
Likely causes, in rough order of how often they're the actual culprit: a learning rate that's too large for the current loss landscape's curvature, causing the optimizer to repeatedly overshoot past a minimum and land on the other side, then overshoot back; momentum that's too high given the current learning rate, which amplifies this same overshoot by continuing to push in the recent direction even after the loss has started rising again; poorly-conditioned gradients (missing or ineffective normalization), where different parameter directions have very different effective curvatures, so a single global learning rate is simultaneously too large for some directions and too small for others; and, less commonly, an architectural issue (unstable skip-connection scaling, activation saturation) introducing genuine noise into the gradient signal itself rather than a pure step-size problem.
Corrective actions, roughly in order of cost and invasiveness: (1) reduce the learning rate, or add/strengthen a decay schedule, since this directly shrinks the overshoot each step can cause; (2) lower the momentum coefficient (or reconsider Nesterov specifically) if it's set unusually high, since high momentum combined with a learning rate that's already borderline is a common combination that produces exactly this oscillating pattern; (3) add gradient clipping to bound how large any single step can be, which helps regardless of the ROOT cause; (4) temporarily switch to an adaptive optimizer (Adam/AdamW) to stabilize training while you diagnose further, since per-parameter adaptive scaling directly addresses poor conditioning; (5) add or strengthen normalization (BatchNorm/LayerNorm) if none is present, which improves the loss landscape's conditioning more fundamentally than any single-optimizer change.
Worked example
A concrete diagnostic to distinguish the root cause: run a short learning-rate range test (sweep the rate upward over a few hundred steps and watch where the loss curve starts to look unstable) and, separately, log the gradient norm PER LAYER over the oscillating period; if the oscillation correlates cleanly with the overall gradient norm spiking and then recovering in sync with the loss, a step-size fix (lower LR or momentum) is almost certainly sufficient; if instead one specific layer's gradient norm behaves very differently from the rest (spiking independently, out of sync with the global loss oscillation), that points toward an architecture-specific issue localized to that layer rather than a global optimizer setting.
Trade-offs & pitfalls
A common mistake is changing the learning rate AND the momentum AND adding clipping all in the same experiment; if the oscillation resolves, you cannot tell which change actually fixed it, which matters for correctly tuning the eventual production configuration rather than over-conservatively keeping every change. A second common gap is assuming BATCH NOISE (an inherently different phenomenon, ordinary mini-batch-to-mini-batch variance) is the same thing as this OPTIMIZATION-INSTABILITY oscillation; batch noise typically looks like small, high-frequency jitter around a generally-improving trend, while true optimizer-instability oscillation shows a repeating pattern of clear, larger-magnitude rises and falls, often at a period correlated with the learning rate and momentum settings specifically.
Define overfitting and underfitting for a neural network. Describe the characteristic training-vs-validation loss curve pattern for each, and list practical remedies for each.
Sample Answer
Direct answer
Overfitting is when a network fits noise or spurious training-set patterns and loses the ability to generalize; underfitting is when the network is too limited (in capacity or training) to capture the real signal at all. The clearest tell is the shape of the training-versus-validation loss curves, not any single number.
Structured elaboration
Overfitting. Training loss keeps falling, often toward zero, while validation loss flattens and then rises: a widening train/validation gap. Remedies: L1/L2 weight decay, dropout, data augmentation, early stopping on validation loss, reducing model capacity, and collecting more or more diverse labeled data.
Underfitting. Both training and validation loss stay high and close together, with little improvement even as training continues. Remedies: increase model capacity, reduce or remove regularization, train longer or tune the learning rate and optimizer, and improve feature engineering or input representation.
Worked example
A useful mental picture: sample training-loss/validation-loss pairs over epochs 1 to 20. An overfitting run looks like training loss dropping from 1.0 to 0.05 while validation loss drops from 1.0 to 0.4 then climbs back to 0.6 by epoch 20. An underfitting run looks like both losses stuck around 0.7 to 0.8 for all 20 epochs with no meaningful separation. The diagnostic signal is the GAP and its TREND, not the absolute loss value at any one epoch.
Trade-offs & pitfalls
A common mistake is treating a small, stable train/validation gap as overfitting; some gap is expected and healthy since the model always has some information advantage on data it trained on. Watch the trend, not a fixed threshold. Reducing capacity to fix overfitting can tip a model into underfitting if pushed too far, so change one lever at a time and re-check both curves after each change.
Compare triplet loss, contrastive loss, and InfoNCE/NT-Xent for representation learning. Discuss hard/semi-hard negative mining, batch size and temperature effects, and how to scale training to millions of examples.
Sample Answer
Direct answer
Triplet loss, contrastive loss, and InfoNCE/NT-Xent all pull similar examples together and push dissimilar ones apart in an embedding space, but they differ in how many negatives they compare against at once, InfoNCE's multi-way comparison against many negatives simultaneously is what makes it converge faster and scale better to large, self-supervised training than the older pairwise or triplet forms.
Structured elaboration
Triplet loss: compares one anchor against one positive and one negative at a time, L=max(0,d(a,p)−d(a,n)+margin); good for fine-grained ranking tasks, but requires explicitly SAMPLING triplets, and convergence is slow without careful (hard or semi-hard) negative mining.
Contrastive loss: operates on labeled PAIRS (same-class or different-class), pulling positive pairs together and pushing negative pairs apart past a margin; simpler to set up than triplet loss, but less directly aligned with a RANKING objective.
InfoNCE/NT-Xent: a SOFTMAX-based objective comparing one positive against MANY negatives simultaneously per anchor, using cosine similarity scaled by a temperature; this multi-way comparison structure is what typically converges fastest and scales best, especially in self-supervised settings where negatives can be drawn from the rest of a large batch or a stored memory bank.
Mining strategies: HARD negatives (closest to the anchor) give the strongest learning signal per example but risk collapse or instability if used too aggressively, especially under label noise; SEMI-HARD negatives (farther than the true positive but still violating the margin) are a more stable middle ground, historically popularized by FaceNet. InfoNCE's IN-BATCH negative structure largely sidesteps explicit mining, since every other example in the batch automatically serves as a negative.
Batch size and temperature: InfoNCE's effective negative pool grows directly with batch size, so LARGER batches generally improve its performance up to hardware memory limits; when batch size is constrained, a MEMORY BANK (as in MoCo, using a momentum-updated encoder plus a queue of recent embeddings) supplies additional negatives without needing an actually larger batch. Temperature τ controls how sharply the softmax concentrates on the hardest negatives, lower τ increases the penalty on the closest (hardest) negatives specifically, common values fall roughly in the 0.05 to 0.2 range, tuned against validation, and always paired with L2-NORMALIZED embeddings when using cosine similarity, since temperature's effect is only well-calibrated when the embedding norm itself isn't also varying uncontrolled.
Worked example
A concrete scaling decision to millions of examples: for a fixed, modest GPU budget, a MoCo-style momentum encoder plus a large negative QUEUE (tens of thousands of stored embeddings, refreshed continuously as training proceeds) reaches a comparable effective negative-pool size to a SimCLR-style approach that instead relies on genuinely large batches spread across many GPUs via an all-gather; the memory-bank approach trades a small amount of NEGATIVE STALENESS (queued embeddings were computed by a slightly earlier version of the encoder) for dramatically lower per-step memory and compute requirements.
Trade-offs & pitfalls
A common mistake is increasing batch size (or negative-queue size) as a blanket fix for weak InfoNCE performance without also re-tuning temperature; the two interact, since the effective difficulty of the multi-way classification task InfoNCE solves scales with the number of negatives, and a temperature tuned for a small negative pool can behave quite differently once the pool grows substantially larger. A second common gap is neglecting to monitor for REPRESENTATIONAL COLLAPSE (all embeddings converging toward a single point, trivially satisfying the loss); tracking metrics like the DISTRIBUTION of pairwise embedding similarities, or downstream retrieval accuracy on a small held-out k-NN probe, catches this failure mode long before it would be obvious from the training loss curve alone, since a collapsed representation can still report a deceptively low training loss.
Show the core PyTorch code for training an LSTM classifier on variable-length text sequences: converting sequences to lengths, sorting, using pack_padded_sequence before the LSTM, unpacking outputs, and computing a per-sequence classification loss.
Sample Answer
Direct answer
Training an LSTM classifier on variable-length sequences means padding them to a common length, sorting by length (a requirement of the packing utility), packing so the LSTM skips computation on padding entirely, then carefully un-sorting the results back to the original order before computing the loss against the original labels.
Structured elaboration
import torch
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
import torch.nn as nn
tokenized = [torch.tensor([1,2,3]), torch.tensor([4,5]), torch.tensor([6,7,8,9])]
labels = torch.tensor([0,1,0])
lengths = torch.tensor([t.size(0) for t in tokenized])
padded = pad_sequence(tokenized, batch_first=True, padding_value=0)
lengths_sorted, perm_idx = lengths.sort(descending=True)
padded_sorted = padded[perm_idx]
labels_sorted = labels[perm_idx]
embed = nn.Embedding(20, 16)
embedded = embed(padded_sorted)
packed = pack_padded_sequence(embedded, lengths_sorted.cpu(), batch_first=True, enforce_sorted=True)
lstm = nn.LSTM(input_size=16, hidden_size=32, batch_first=True)
packed_out, (h_n, c_n) = lstm(packed)
seq_repr = h_n[-1] # (B, H): the final hidden state for EACH sequence's own true length
classifier = nn.Linear(32, 3)
logits_sorted = classifier(seq_repr)
_, unperm_idx = perm_idx.sort()
logits = logits_sorted[unperm_idx]
labels_orig = labels_sorted[unperm_idx]
loss = nn.CrossEntropyLoss()(logits, labels_orig)
The key correctness property of h_n[-1] here is that PyTorch's packed-sequence machinery ensures it is each sequence's own hidden state AT ITS OWN TRUE LENGTH, not a padded, over-run value; this was confirmed directly by independently unpacking the padded output and manually gathering each sequence's last VALID timestep, which matched h_n[-1] exactly.
Worked example
Run end to end on three sequences of length 3, 2, and 4: seq_repr had shape (3,32) as expected, the un-sort step correctly restored the original label order [0,1,0] (verified directly, not just assumed), and a full forward-plus-backward pass completed with a real gradient reaching the embedding layer's weights.
Trade-offs & pitfalls
The single most common bug in this pattern is computing the loss against labels_sorted while comparing against logits that have ALREADY been un-sorted (or the reverse, comparing sorted logits against un-sorted labels); the sort/un-sort pairing must be applied CONSISTENTLY to logits AND labels together, and a mismatch here does not raise an error, it silently trains on scrambled label assignments, since every tensor involved still has a valid, matching SHAPE even when the actual pairing is wrong. A second common gap is passing lengths_sorted on the wrong device; pack_padded_sequence specifically requires the lengths tensor on CPU even when the rest of the computation runs on GPU, and forgetting this raises an explicit error rather than silently misbehaving, which at least makes this particular mistake easy to catch quickly.
Unlock Full Question Bank
Get access to all Deep Learning: Neural Networks and Architectures interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.