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.
Explain the transfer-learning workflow with a pretrained backbone: feature extraction versus fine-tuning, which layers to freeze or unfreeze, and how dataset size and domain similarity should influence the strategy.
Sample Answer
Direct answer
The transfer-learning workflow with a pretrained backbone comes down to one core choice, feature extraction (freeze the backbone) versus fine-tuning (also update backbone weights), and that choice should follow directly from how much labeled data you have and how similar your domain is to the pretraining data.
Structured elaboration
Feature extraction: freeze the pretrained backbone entirely and train only a new classifier head on top of its frozen output features. This is fast, has a low overfitting risk, and works well when the target dataset is small and reasonably similar in domain to the pretraining data (natural images pretrained on ImageNet, applied to another natural-image task).
Fine-tuning: unfreeze some or all of the backbone and continue training it (usually at a much lower learning rate than the new head) alongside the new head. This is the better choice when you have a moderate-to-large labeled dataset, or when there is a real domain shift between the pretraining data and your task (e.g. medical images versus natural photographs) that the frozen features do not capture well.
Which layers to freeze or unfreeze: a common practical pattern is to freeze early layers (they tend to capture generic, low-level features like edges and textures that transfer broadly) and unfreeze later layers (which capture more task-specific, higher-level features); train the new head alone first, then progressively unfreeze the last block or two of the backbone if validation performance still has room to improve.
Dataset size and domain similarity, combined: small dataset plus similar domain favors pure feature extraction; small dataset plus a dissimilar domain is the riskiest combination, since neither the frozen features nor a lightly-fine-tuned backbone may transfer well, and heavier regularization or in-domain self-supervised pretraining may be needed; a large dataset generally supports full fine-tuning regardless of domain similarity, since there is enough signal to safely adapt the whole network.
Negative transfer: fine-tuning is not automatically beneficial. When the pretraining domain is sufficiently different from the target task, forcing the backbone to adapt with too little target data can actively DEGRADE performance relative to either training from scratch or leaving the backbone frozen, because the fine-tuning process can overwrite generically useful features with noise fit to a small target dataset before it has learned anything better to replace them with.
Worked example
A typical layerwise learning-rate setup: head learning rate 10−3, backbone learning rate 10−4 (a 10x reduction), trained for a few epochs with the backbone frozen first, then unfrozen with the SAME reduced backbone learning rate for further epochs; this order (head-first, then careful backbone unfreezing) avoids large, noisy early gradients from an untrained head corrupting the pretrained backbone's already-useful weights.
Trade-offs & pitfalls
To validate that transfer learning is actually helping in a production evaluation pipeline (rather than assuming it), run a direct ablation: frozen-backbone versus partially-fine-tuned versus fully-fine-tuned versus trained-from-scratch, all on the SAME validation split, and compare not just final accuracy but training time and the size of the train/validation gap, since a negative-transfer case will show a fine-tuned model doing WORSE than the frozen-feature baseline, which is the concrete signal to fall back to feature extraction or reduce how much of the backbone you unfreeze.
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.
A model trained with Adam generalizes worse than the same model trained with SGD and momentum. Explain the algorithmic and numerical reasons this can happen and how you would experimentally investigate and mitigate it.
Sample Answer
Direct answer
When Adam generalizes worse than SGD with momentum on the identical model, the leading suspects are Adam's per-parameter adaptive scaling converging to sharper, less-robust minima, and naive (non-decoupled) weight decay behaving differently under Adam than under SGD, and the way to tell them apart is a controlled, one-variable-at-a-time experimental comparison rather than guessing.
Structured elaboration
Algorithmic reasons: Adam's adaptive, per-parameter step sizes can converge faster but toward SHARPER minima, which a body of empirical work associates with worse generalization than the flatter minima plain SGD's more uniform, noisier updates tend to find; if weight decay is applied naively (added into the gradient before Adam's own adaptive rescaling, rather than as AdamW's decoupled term), the EFFECTIVE regularization strength ends up inconsistent across parameters with different gradient histories, which is a different, independent generalization risk from the sharp-minima question.
Numerical/implementation reasons: an inappropriate epsilon or overly aggressive bias correction early in training can distort Adam's early dynamics in ways that are easy to overlook if you're only comparing final accuracy rather than full training curves.
Experimental investigation, designed to isolate WHICH cause is actually responsible: run BOTH optimizers with matched compute budget and multiple random seeds (5 or more) to separate a genuine effect from run-to-run noise; first swap plain Adam for AdamW specifically (isolating whether naive weight decay coupling is the culprit) while holding everything else fixed; separately, measure a SHARPNESS proxy (such as the loss increase under a small random perturbation to the found minimum, or the largest Hessian eigenvalue if tractable) for both optimizers' final solutions, to test the sharp-versus-flat-minima hypothesis directly rather than just inferring it from the generalization gap alone.
Worked example
A concrete, falsifiable diagnostic sequence: (1) re-run with AdamW and a properly-tuned weight decay value; if the generalization gap closes substantially, naive weight-decay coupling was the primary cause, not anything more fundamental about Adam's adaptive updates; (2) if switching to AdamW does NOT close the gap, measure the sharpness proxy for both optimizers' solutions on the SAME model and data; a meaningfully sharper minimum for the Adam/AdamW solution is evidence for the adaptive-optimizer-finds-sharp-minima hypothesis specifically, pointing toward a different mitigation (e.g. adding explicit sharpness-aware regularization, or accepting SGD's slower convergence in exchange for its generalization advantage on this particular task).
Trade-offs & pitfalls
A common mistake is changing weight decay AND learning rate AND the optimizer's beta parameters all in the same comparison run; if the gap closes, you cannot attribute the improvement to any ONE of those changes specifically, which matters for actually understanding (and being able to reproduce) the fix rather than accidentally re-tuning your way to a coincidentally-better configuration. A second common gap is comparing final test accuracy alone without also comparing the FULL training and validation curves; a generalization gap that appears only late in training (versus one present from early on) points toward different underlying causes and different appropriate fixes.
Derive the subgradient of the hinge loss L = max(0, 1 - y*f(x)) with respect to model parameters when f(x) is linear. Explain how SGD uses this subgradient at the non-differentiable point and the implications for convergence and support vectors.
Sample Answer
Direct answer
The hinge loss's subgradient is exactly −yx when the margin is violated, exactly zero when the margin is comfortably satisfied, and any value in between at the exact kink where the two cases meet, a genuine ambiguity that SGD resolves in practice simply by picking one of these valid subgradients according to how the boundary condition happens to be coded.
Structured elaboration
For L(θ)=max(0,1−yθ⊤x), let z=1−yθ⊤x. If z>0 (the margin is genuinely violated, this example is being misclassified or under-confidently classified), L=z directly, so ∂L/∂θ=−yx. If z<0 (the example is classified correctly with margin to spare), L=0, so ∂L/∂θ=0. At exactly z=0 (the non-differentiable kink), the SUBDIFFERENTIAL is the entire convex hull between these two limiting values, any vector of the form −αyx for α∈[0,1] is a mathematically valid subgradient at that exact point.
How SGD handles this in practice: a real implementation needs to output ONE specific vector, not a whole set, so it picks based on how the boundary comparison is coded (commonly treating z≥0 as "violated", giving −yx, or z>0 strictly, giving 0 at the exact boundary); this ambiguity does not break convergence theory for subgradient methods (which are specifically designed to handle a general subgradient choice at non-smooth points), though an inappropriately large step size can cause slower or oscillatory behavior specifically AROUND this non-smooth boundary.
Worked example
This was verified numerically at two concrete points: with x=[1,2,−1], y=1, and θ=[0.1,0.1,0.1] (giving z=0.8>0, a genuinely violated margin), the analytic subgradient −yx=[−1,−2,1] matched a finite-difference numerical gradient EXACTLY. With θ=[5,5,5] (giving z=−9<0, a comfortably satisfied margin), the numerical gradient was exactly [0,0,0], confirming the loss genuinely contributes zero gradient once the margin is safely met, both matching the two-case derivation above precisely.
Trade-offs & pitfalls
Implications for support vectors: only examples with z≥0 (margin violated or exactly met) receive a non-zero subgradient at all, meaning ONLY these examples actually influence any given parameter update; examples comfortably beyond the margin contribute nothing, mathematically IDENTICAL to not being in the training set at all for that particular update. This is exactly the classical "support vector" property: at the optimum of a regularized hinge-loss objective (an SVM), the examples that determine the final decision boundary are precisely those sitting on or inside the margin, every other, comfortably-classified example could be REMOVED from the training set without changing the final solution at all, a genuinely useful sparsity property that a smooth loss like cross-entropy (where every example always contributes SOME nonzero gradient) does not share.
Describe strategies for training when labeled data is scarce: self-supervised pretraining, semi-supervised learning, data augmentation, and transfer learning. How would you use learning curves and active learning to decide if you have enough labeled data, and how would you validate gains without confirmation bias?
Sample Answer
Direct answer
When labeled data is scarce, self-supervised pretraining, semi-supervised learning, augmentation, and transfer learning all extract extra signal from the SAME small labeled set (or from unlabeled data you already have), but validating that any of them genuinely helped requires a validation protocol specifically designed to resist confirmation bias, since pseudo-labeling in particular can easily produce numbers that look like progress but aren't.
Structured elaboration
Self-supervised pretraining: learn general representations from UNLABELED data first (contrastive methods like SimCLR/MoCo, or masked-reconstruction methods like MAE), giving the network a strong starting point before it ever sees the scarce labels; a quick way to sanity-check whether this pretraining actually captured something useful is LINEAR PROBING (freezing the pretrained representation and training only a simple linear classifier on top), which is cheap and gives an early signal before committing to full fine-tuning.
Transfer learning: fine-tune (or use as a frozen feature extractor) a checkpoint already pretrained on a large, related dataset; compare a frozen-feature linear probe against full fine-tuning specifically to gauge how much genuine domain shift exists between the pretraining data and your task.
Semi-supervised learning: consistency regularization (enforcing that predictions stay stable under input augmentation, as in Mean Teacher or FixMatch) and pseudo-labeling (assigning high-confidence labels to unlabeled examples and training on them) both use UNLABELED data beyond the scarce labeled set, typically via a teacher-student or exponential-moving-average setup that smooths the targets rather than trusting the model's own raw, possibly-overconfident predictions directly.
Data augmentation: label-preserving transformations (and stronger policies like RandAugment or MixUp/CutMix) synthetically expand the effective diversity of the scarce labeled set.
Using learning curves and active learning to decide if you have enough data: plot validation performance against labeled-dataset SIZE (training repeatedly on increasing subsets); a curve that is still climbing steeply at your current dataset size is direct evidence more labels would help meaningfully, while a curve that has visibly flattened suggests you're near the point of diminishing returns FOR THIS architecture and task. Active learning (having the model flag its most UNCERTAIN unlabeled examples for human labeling next) directs limited labeling budget toward the examples likely to teach the model the most, rather than labeling more data uniformly at random.
Worked example
A concrete anti-confirmation-bias validation protocol for pseudo-labeling specifically: reserve a CLEAN labeled validation set that NEVER participates in generating pseudo-labels and is never touched by the semi-supervised training loop at all; run an explicit ABLATION comparing (a) labels-only baseline, (b) labels plus self-supervised pretraining, and (c) labels plus pretraining plus pseudo-labeling, all evaluated on that SAME untouched clean validation set; and require the reported improvement to be consistent across multiple random seeds (not a single lucky run) before accepting it as real, ideally with a statistical test (a paired comparison or bootstrap confidence interval) rather than a single point-estimate comparison.
Trade-offs & pitfalls
The single most common confirmation-bias trap is evaluating a pseudo-labeling pipeline on a validation set that WAS INVOLVED, even indirectly, in generating the pseudo-labels being trained on; this systematically inflates the reported gain, since the model has effectively been validated against data whose "ground truth" the model itself helped produce. A second common mistake is accepting a pseudo-labeling gain from a SINGLE training run without checking it holds up across seeds or via a proper statistical comparison; semi-supervised methods can show meaningfully higher run-to-run variance than fully-supervised training, and a single favorable run is weak evidence on its own.
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.