PrepStack › AI › Deep Learning

Deep Learning interview cheat sheet

Neurons, backprop, optimisers, regularisation, CNNs, RNNs and PyTorch training

Deep learning interviews check that you understand why networks train, not just how to call a library. Expect questions on backpropagation and the chain rule, activations and vanishing gradients, losses, optimisers like Adam vs AdamW, regularisation, normalisation, CNN shapes and RNN gates, plus practical PyTorch: the training loop, model.eval() vs torch.no_grad(), and how to debug a loss that will not go down. Read the 15-minute revision first; the pure-Python demos show the maths with real numbers.

15-minute revision

  1. A neuron computes activation(w·x + b). A perceptron uses a step function and can only learn linearly separable data, so it cannot learn XOR.
  2. Without a non-linear activation, any stack of linear layers collapses into one linear layer. Non-linearity is what gives depth its power.
  3. Universal approximation: one hidden layer with enough units can approximate any continuous function on a bounded domain. Depth makes this far more parameter-efficient.
  4. Losses: MSE for regression, cross-entropy (softmax + negative log-likelihood) for multi-class, BCE (sigmoid) for binary or multi-label. PyTorch CrossEntropyLoss takes raw logits.
  5. Backprop = chain rule applied backwards over the computational graph, reusing upstream gradients. Cost is about 2x the forward pass.
  6. Sigmoid's derivative is at most 0.25, so deep sigmoid nets get vanishing gradients. Fixes: ReLU family, He/Xavier init, normalisation, residual connections, LSTM gates.
  7. Xavier/Glorot init (variance ≈ 2/(fan_in+fan_out)) suits tanh/sigmoid. He/Kaiming init (variance 2/fan_in) suits ReLU.
  8. Adam = momentum (1st moment) + RMSProp (2nd moment) + bias correction. AdamW decouples weight decay from the gradient update, which is the correct way to regularise with Adam.
  9. Typical recipe: AdamW, linear warmup then cosine decay, mini-batches of 32–512, gradient clipping for RNNs/transformers.
  10. 1 epoch = one pass over the data. Iterations per epoch = ceil(N / batch_size). One iteration = one optimiser step.
  11. Dropout randomly zeroes activations in training and scales the rest by 1/(1−p) (inverted dropout); it is off in eval().
  12. BatchNorm normalises each feature across the batch (needs running stats at inference). LayerNorm normalises across features of one sample (used in transformers and RNNs).
  13. Conv output size: ⌊(N + 2P − K) / S⌋ + 1. Two stacked 3x3 convs see a 5x5 receptive field with fewer parameters than one 5x5.
  14. ResNet skip connections compute x + F(x), giving gradients a direct path and making 100+ layer nets trainable.
  15. LSTM has forget, input and output gates plus a cell state; GRU merges them into update and reset gates. Attention lets a decoder look at every encoder state instead of one fixed vector.
  16. PyTorch loop: zero_grad → forward → loss → backward → step. Use model.eval() + torch.no_grad() (or inference_mode) for evaluation; they do different things.

Neural network basics

Neuron & perceptron

A neuron is a weighted sum plus bias passed through an activation. The perceptron is the simplest version with a step function.

  • An artificial neuron computes z = w·x + b, then a = f(z). The weights scale each input, the bias shifts the decision boundary away from the origin.
  • The perceptron (Rosenblatt, 1958) uses a step activation and the update rule w += lr * (y − ŷ) * x. It only changes weights when it makes a mistake.
  • The perceptron convergence theorem: if the data is linearly separable, the rule finds a separating line in a finite number of updates.
  • A single perceptron draws one straight line (hyperplane). It cannot learn XOR; this limit (Minsky & Papert, 1969) helped cause the first AI winter.
  • Modern neurons replace the step with a differentiable activation (sigmoid, ReLU) so we can train with gradients instead of the perceptron rule.
  • Logistic regression is exactly one neuron with a sigmoid activation and BCE loss.

Interview questions

  • What is a perceptron and what are its limits?
  • Why do we need a bias term?
  • How is logistic regression related to a neural network?

MLP, depth & universal approximation

A multi-layer perceptron stacks fully connected layers with non-linear activations, which lets it model non-linear functions such as XOR.

  • An MLP (feed-forward net) has an input layer, one or more hidden layers and an output layer. Each layer computes h = f(W h_prev + b).
  • The forward pass is just these matrix multiplies and activations applied layer by layer to produce a prediction.
  • Universal approximation theorem: a network with one hidden layer and a suitable non-linear activation can approximate any continuous function on a compact set, given enough units. It says nothing about how to find the weights or how many units you need.
  • Depth beats width in practice: deep nets build features hierarchically (edges → shapes → objects) and some functions need exponentially many units if you only have one layer.
  • Parameter count of a dense layer = in * out + out (weights plus biases).
  • Two hidden ReLU units are enough to solve XOR, as the demo shows.

Interview questions

  • What does the universal approximation theorem say, and what does it not say?
  • Why use deep networks instead of one very wide layer?
  • How many parameters does a 784 → 128 → 10 MLP have?

Activation functions & why non-linearity

Activations add non-linearity. ReLU is the default for hidden layers, GELU dominates transformers, and softmax/sigmoid turn outputs into probabilities.

  • Without non-linearity, W2(W1 x) = (W2 W1) x: the whole network is one linear map, no matter how deep.
  • Sigmoid squashes to (0, 1); good for binary outputs, bad in hidden layers because it saturates and is not zero-centred.
  • Tanh squashes to (−1, 1) and is zero-centred, but still saturates. Its max derivative is 1 (sigmoid's is 0.25).
  • ReLU max(0, z) is cheap and does not saturate for positive inputs. Risk: dying ReLU, where a unit's input stays negative and its gradient is always 0.
  • Leaky ReLU keeps a small slope (e.g. 0.01) for negatives. GELU z·Φ(z) is a smooth ReLU used in BERT/GPT. SiLU/Swish z·σ(z) is similar.
  • Softmax turns a vector of logits into a probability distribution that sums to 1. Use it on the output for single-label multi-class problems.

Interview questions

  • Why do neural networks need non-linear activation functions?
  • Why is ReLU preferred over sigmoid in hidden layers?
  • What is the dying ReLU problem and how do you fix it?
  • Softmax vs sigmoid on the output layer?

Loss functions: MSE, cross-entropy, BCE

The loss turns predictions into one number to minimise. Match it to the task and the output activation.

  • MSE mean((y − ŷ)²) for regression. It punishes large errors heavily, so it is sensitive to outliers. MAE/Huber are more robust.
  • Cross-entropy −log p(true class) for multi-class classification. It is the negative log-likelihood of the correct label under the softmax distribution.
  • Binary cross-entropy −[y log p + (1 − y) log(1 − p)] for binary or multi-label tasks with sigmoid outputs.
  • Cross-entropy with softmax has the clean gradient p − y with respect to the logits, which is why it trains much faster than MSE on probabilities.
  • For numerical stability, frameworks fuse the activation into the loss: nn.CrossEntropyLoss (log-softmax + NLL) and nn.BCEWithLogitsLoss (sigmoid + BCE). Both expect raw logits.
  • Extras worth naming: label smoothing (CrossEntropyLoss(label_smoothing=0.1)), class weights for imbalance, focal loss for heavy imbalance.

Interview questions

  • Why use cross-entropy instead of MSE for classification?
  • Difference between CrossEntropyLoss, NLLLoss and BCEWithLogitsLoss?
  • What is label smoothing?
  • Your classifier has a 99:1 class imbalance. What loss changes help?

Training mechanics

Backpropagation, chain rule & computational graphs

Backprop applies the chain rule backwards through the computational graph to get every parameter's gradient in one pass.

  • The forward pass builds a computational graph: nodes are operations, edges carry tensors. Each op knows its local derivative.
  • Chain rule: ∂L/∂w = ∂L/∂y · ∂y/∂w. Backprop starts with ∂L/∂L = 1 and walks the graph in reverse, multiplying each upstream gradient by the local one.
  • It is reverse-mode automatic differentiation: one backward pass gives the gradient for all parameters, at roughly 2x the cost of the forward pass. This is why it beats finite differences.
  • Forward activations must be stored for the backward pass. That is why training needs much more memory than inference (and why gradient checkpointing trades compute for memory).
  • When a value feeds several nodes, its gradients from each branch are summed.
  • Gradient checking: compare analytic gradients with (L(w+ε) − L(w−ε)) / 2ε to catch bugs in hand-written backward code.

Interview questions

  • Explain backpropagation in simple terms.
  • Backprop vs gradient descent: what is the difference?
  • Why does training use more memory than inference?
  • What is a computational graph and is PyTorch's static or dynamic?

Batch vs mini-batch vs SGD, epochs & iterations

How many examples you use per update trades gradient accuracy against update speed. Mini-batches are the standard.

  • Batch gradient descent uses the whole dataset per update: exact gradient, but slow and memory-heavy.
  • Stochastic gradient descent (strictly) uses one example per update: noisy but cheap, and the noise can help escape sharp minima.
  • Mini-batch (e.g. 32–512) is the practical middle: vectorised on GPUs, reasonably smooth gradients. In practice “SGD” usually means mini-batch SGD.
  • Epoch = one full pass over the training set. Iteration/step = one mini-batch forward + backward + optimiser update.
  • Iterations per epoch = ceil(N / batch_size) (or floor with drop_last=True).
  • Larger batches → fewer, more accurate steps; the linear scaling rule says scale LR roughly with batch size (with warmup). Very large batches can generalise slightly worse.

Interview questions

  • Difference between an epoch, a batch and an iteration?
  • Why is mini-batch gradient descent the default?
  • How do you train with an effective batch of 1024 when only 128 fits in memory?

Optimisers: SGD, momentum, RMSProp, Adam, AdamW

All optimisers follow the negative gradient; they differ in how they smooth it (momentum) and scale it per parameter (adaptive methods).

  • SGD: w -= lr * g. Simple; with a good schedule it often generalises best for CNNs.
  • Momentum: keep a velocity v = β v + g, update w -= lr * v. It speeds up along consistent directions and damps zig-zags in narrow valleys. Nesterov looks ahead before computing the gradient.
  • RMSProp: keeps a running average of squared gradients and divides by its square root, so each parameter gets its own effective step size.
  • Adam: momentum (1st moment m) + RMSProp (2nd moment v) + bias correction because both start at 0. Defaults lr=1e-3, betas=(0.9, 0.999), eps=1e-8.
  • AdamW: applies weight decay directly to the weights (w -= lr * λ * w) instead of adding λw to the gradient. With Adam, L2-in-the-gradient gets rescaled by the adaptive denominator, so it is not real weight decay. AdamW is the default for transformers (PyTorch default weight_decay=0.01).
  • Adam uses about 3x the parameter memory for optimiser state + params (params, m, v), which matters for large models.

Interview questions

  • Explain Adam. Why does it need bias correction?
  • What is the difference between Adam and AdamW?
  • How does momentum help?
  • When would you choose SGD with momentum over Adam?

Learning rate, schedules & warmup

The learning rate is the most important hyperparameter. Start high enough to make progress, then decay; warm up first for large models.

  • Too high: the loss oscillates or becomes NaN. Too low: training is slow and can stall on plateaus.
  • Step decay: multiply LR by e.g. 0.1 at fixed epochs (StepLR, MultiStepLR). Exponential decay shrinks it every epoch.
  • Cosine annealing smoothly lowers LR from the max to a minimum along a half cosine. One-cycle ramps LR up then down within one run.
  • Warmup: increase LR linearly from near 0 for the first few hundred or thousand steps. Early gradients are large and Adam's v estimate is unreliable, so warmup prevents early divergence. Standard for transformers.
  • ReduceLROnPlateau lowers LR when a validation metric stops improving.
  • LR range test: increase LR exponentially over a short run and pick a value a bit below where the loss starts rising.

Interview questions

  • Why do we use learning rate warmup?
  • Your loss goes down quickly then plateaus early. What do you try with the LR?

Vanishing/exploding gradients & weight init

Gradients are products of many per-layer factors; if those factors are mostly below or above 1, gradients vanish or explode. Good init keeps signal variance steady.

  • Backprop multiplies one Jacobian per layer. If each factor is < 1 (e.g. sigmoid' ≤ 0.25) the gradient shrinks exponentially with depth; if > 1 it explodes.
  • Symptoms: early layers barely change (vanishing), or loss/weights become NaN/inf (exploding).
  • Xavier/Glorot init: Var(w) = 2 / (fan_in + fan_out), designed for tanh/sigmoid so variance is kept in both forward and backward passes.
  • He/Kaiming init: Var(w) = 2 / fan_in. The factor 2 compensates for ReLU zeroing half its inputs.
  • Never initialise all weights to the same value (e.g. zeros): every unit in a layer gets the same gradient, so they stay identical (symmetry problem). Biases can be 0.
  • Other fixes: ReLU-family activations, BatchNorm/LayerNorm, residual connections, LSTM/GRU gating, and gradient clipping for exploding gradients.

Interview questions

  • What is the vanishing gradient problem?
  • How do you deal with exploding gradients?
  • Xavier vs He initialisation?
  • Why not initialise all weights to zero?

Regularisation & normalisation

Regularisation: dropout, weight decay, early stopping, augmentation

Regularisation reduces overfitting by limiting what the model can memorise or by showing it more varied data.

  • Overfitting: training loss keeps falling while validation loss rises. The model memorises noise.
  • Dropout zeroes each activation with probability p during training and scales survivors by 1/(1−p) (inverted dropout), so nothing changes at inference. It acts like training an ensemble of sub-networks.
  • Weight decay / L2 penalises large weights, giving smoother functions. L1 pushes weights to exactly 0 (sparsity).
  • Early stopping: monitor validation loss, keep the best checkpoint, stop after patience epochs without improvement.
  • Data augmentation: random crops, flips, colour jitter, mixup/cutmix for images; noise, masking, back-translation for audio/text. Only apply it to the training set.
  • Others: label smoothing, smaller model, more data, stochastic depth, batch norm's mild noise.

Interview questions

  • How does dropout work, and what happens at inference?
  • What is the difference between L1 and L2 regularisation?
  • Your model has 99% training accuracy and 70% validation accuracy. What do you do?

Batch norm vs layer norm

Both normalise activations to zero mean and unit variance, then rescale with learnable γ and β. They differ in which axis they average over.

  • BatchNorm computes mean/variance per feature (channel) across the batch (and spatial positions for CNNs). It keeps running averages to use at inference.
  • LayerNorm computes mean/variance per sample across its features. It behaves the same in training and inference and does not depend on batch size.
  • Benefits: allows higher learning rates, makes training less sensitive to init, smooths the loss landscape, and BN adds mild regularising noise.
  • BN struggles with small batches, variable-length sequences and when train/inference batches differ. That is why transformers and RNNs use LayerNorm (or RMSNorm, which skips the mean subtraction).
  • Variants: GroupNorm (groups of channels, good for small-batch detection/segmentation), InstanceNorm (style transfer).
  • Transformers today mostly use pre-norm (normalise before attention/MLP inside the residual branch), which trains more stably than post-norm.

Interview questions

  • What is the difference between BatchNorm and LayerNorm?
  • How does BatchNorm behave differently in training and inference?
  • Why do transformers use LayerNorm instead of BatchNorm?
  • Why does BatchNorm help training?

Architectures

CNNs: convolution, stride, padding, pooling, receptive field

Convolutions slide small shared filters over the input, giving local, translation-equivariant features with far fewer parameters than dense layers.

  • A kernel/filter (e.g. 3x3xC_in) is slid over the input; at each position it computes a dot product, producing one feature map. A layer has C_out filters.
  • Parameter sharing and local connectivity: a 3x3 conv from 64 to 128 channels has 3·3·64·128 + 128 = 73,856 params regardless of image size.
  • Stride S skips positions (downsampling). Padding P adds zeros around the border; P = (K−1)/2 with stride 1 keeps the size (“same”).
  • Output size: ⌊(N + 2P − D(K−1) − 1) / S⌋ + 1, which is ⌊(N + 2P − K)/S⌋ + 1 with dilation D = 1.
  • Pooling (max/average) downsamples and adds small translation invariance; it has no parameters. Global average pooling replaces big dense layers at the end of modern CNNs.
  • Receptive field: how much of the input one output unit sees. It grows with depth, kernel size, stride and dilation. 1x1 convs mix channels cheaply (bottlenecks).

Interview questions

  • Why use convolutions instead of fully connected layers for images?
  • Compute the output size: 64×64 input, 5×5 kernel, stride 2, padding 2.
  • Why do VGG and ResNet stack 3×3 convs instead of using large kernels?
  • What is a 1×1 convolution for?

Classic CNNs: LeNet → ResNet & skip connections

Each classic architecture added one key idea; ResNet's residual connections made very deep networks trainable.

  • LeNet-5 (1998): conv → pool → conv → pool → dense for digit recognition. Established the conv-pool pattern.
  • AlexNet (2012): won ImageNet by a wide margin using ReLU, dropout, data augmentation and GPUs. Started the deep learning boom.
  • VGG (2014): only 3×3 convs, very uniform, 16–19 layers; simple but heavy (~138M params for VGG-16).
  • GoogLeNet/Inception (2014): parallel 1×1/3×3/5×5 branches with 1×1 bottlenecks; very parameter-efficient.
  • ResNet (2015): a residual block outputs F(x) + x. A deeper plain net trained *worse* (the degradation problem); with identity skips, layers only learn a residual and can easily act as identity. Enabled 152+ layers.
  • Later: DenseNet (concatenate all previous features), MobileNet (depthwise separable convs), EfficientNet (compound scaling), ConvNeXt (modernised ResNet), and Vision Transformers.

Interview questions

  • What problem do residual connections solve?
  • Walk through the evolution from LeNet to ResNet.
  • What is a depthwise separable convolution?

RNNs, LSTM & GRU

RNNs process sequences step by step with a hidden state. LSTMs and GRUs add gates so information and gradients can survive over long ranges.

  • A vanilla RNN updates h_t = tanh(W_x x_t + W_h h_{t−1} + b) with the same weights at every time step. Training uses backprop through time (BPTT) over the unrolled sequence.
  • Repeated multiplication by W_h makes gradients vanish or explode over long sequences, so plain RNNs forget after ~10–20 steps. Truncated BPTT and clipping help a bit.
  • LSTM adds a cell state c_t updated additively, controlled by sigmoid gates: forget (what to erase), input (what to write), output (what to expose as h_t).
  • Because c_t = f ⊙ c_{t−1} + i ⊙ g, the gradient through the cell is multiplied by the forget gate, not by a weight matrix, so it can flow for many steps when f ≈ 1.
  • GRU merges forget and input into an update gate and adds a reset gate; no separate cell state. Fewer parameters, often similar accuracy.
  • Today transformers dominate most sequence tasks, but RNNs remain relevant for streaming/low-latency use and as the basis of modern state-space and linear-recurrent models.

Interview questions

  • Explain the gates of an LSTM.
  • How does an LSTM help with vanishing gradients?
  • LSTM vs GRU?
  • Why did transformers replace RNNs for most NLP tasks?

Seq2seq & attention (intro)

Seq2seq maps one sequence to another with an encoder and a decoder. Attention lets the decoder look at all encoder states, removing the fixed-vector bottleneck.

  • Encoder–decoder (seq2seq): the encoder reads the input (e.g. a French sentence) into hidden states; the decoder generates the output token by token.
  • Early seq2seq squeezed the whole input into one context vector, a bottleneck that hurt long sentences.
  • Attention (Bahdanau 2014): at each decoder step compute a score between the decoder state and every encoder state, softmax them into weights, and use the weighted sum as the context.
  • Scaled dot-product attention: softmax(QKᵀ / √d_k) V. Dividing by √d_k keeps the dot products from growing with dimension and saturating the softmax.
  • Teacher forcing: during training the decoder gets the true previous token, not its own prediction. Fast and stable, but causes exposure bias at inference.
  • Decoding: greedy, beam search (keep top-k partial sequences), or sampling (temperature, top-k, top-p). The Transformer (2017) uses attention only, with no recurrence.

Interview questions

  • What problem did attention solve in seq2seq models?
  • Why divide by √d_k in scaled dot-product attention?
  • What is teacher forcing and what problem does it cause?

Generative models: GANs, VAEs, diffusion

GANs learn via a generator-vs-discriminator game, VAEs learn a probabilistic latent space, and diffusion models learn to reverse a gradual noising process.

  • GAN: a generator G maps noise to samples; a discriminator D tries to tell real from fake. They train in a minimax game. Sharp samples but unstable training and mode collapse (G produces little variety).
  • GAN stabilisers: Wasserstein loss with gradient penalty, spectral norm, careful LR balance, StyleGAN-style architectures.
  • Autoencoder: encoder compresses to a latent code, decoder reconstructs. A VAE makes the latent a distribution: loss = reconstruction + KL divergence to a standard normal prior.
  • The reparameterisation trick z = μ + σ ⊙ ε, ε ~ N(0, I) makes sampling differentiable so the encoder can be trained by backprop. VAEs train stably but samples are often blurry.
  • Diffusion models add Gaussian noise over many steps (forward process) and train a network (often a U-Net or transformer) to predict the noise at each step. Generation starts from pure noise and denoises step by step.
  • Diffusion gives high quality and diversity with stable training, at the cost of slow multi-step sampling (reduced by DDIM-style samplers, distillation). Latent diffusion (Stable Diffusion) runs the process in a VAE's latent space to save compute.

Interview questions

  • How does a GAN work and why is it hard to train?
  • What is the reparameterisation trick in a VAE?
  • Explain diffusion models in two minutes.

Deep learning in practice (PyTorch)

PyTorch training loop & autograd

Every PyTorch training step is: zero the grads, forward, compute loss, backward, optimiser step. Evaluation uses model.eval() and torch.no_grad().

  • Tensors with requires_grad=True are tracked by autograd. loss.backward() fills .grad on each leaf parameter.
  • Gradients accumulate across backward() calls, so call optimizer.zero_grad() every step (default set_to_none=True frees the memory).
  • model.train() / model.eval() switch layer behaviour: dropout on/off, BatchNorm batch stats vs running stats. They do not turn off gradient tracking.
  • torch.no_grad() (or the stricter, faster torch.inference_mode()) disables graph building, saving memory and time. It does not change dropout/BN behaviour. Use both for evaluation.
  • Move the model and each batch to the same device (.to(device)). Use DataLoader for batching, shuffling and parallel loading (num_workers, pin_memory).
  • Save model.state_dict() (and optimiser/scheduler state for resuming), not the whole pickled model. torch.compile(model) can speed up training in PyTorch 2.x.

Interview questions

  • Walk me through a PyTorch training step.
  • What is the difference between model.eval() and torch.no_grad()?
  • Why do we call optimizer.zero_grad()?
  • torch.no_grad() vs torch.inference_mode()?

Transfer learning & fine-tuning

Start from a model pretrained on a big dataset, replace the head, then train only the head (feature extraction) or the whole network with a small LR (fine-tuning).

  • Early layers learn generic features (edges, textures, syntax); later layers are task-specific. Reusing them gives good results with little data and compute.
  • Feature extraction: freeze the backbone (requires_grad=False), train only the new head. Best for small datasets similar to the pretraining data.
  • Fine-tuning: unfreeze some or all layers and train with a small LR (often 10–100x lower for the backbone than for the head) to avoid destroying pretrained weights (catastrophic forgetting).
  • Common schedule: train head first, then unfreeze top blocks gradually (gradual unfreezing), using discriminative LRs per layer group.
  • Use the same preprocessing as pretraining (input size, normalisation mean/std, tokenizer).
  • For large language models, parameter-efficient fine-tuning (LoRA, adapters) trains a small number of extra weights instead of the full model.

Interview questions

  • What is transfer learning and why does it work?
  • Feature extraction vs fine-tuning?
  • You fine-tune with LR 1e-2 and accuracy collapses. Why?

GPUs & mixed precision

GPUs run the massive parallel matrix multiplies deep learning needs. Mixed precision runs most ops in fp16/bf16 for speed and memory, keeping sensitive parts in fp32.

  • Training is dominated by matrix multiplies and convolutions, which GPUs parallelise across thousands of cores; Tensor Cores accelerate low-precision matmuls further.
  • Bottlenecks besides compute: GPU memory (weights, activations, gradients, optimiser state) and data loading (CPU-bound augmentation, slow disks).
  • Mixed precision (AMP): torch.autocast runs matmuls/convs in fp16 or bf16 and keeps reductions and losses in fp32. Master weights stay fp32.
  • fp16 has a small exponent range, so tiny gradients underflow to 0. Loss scaling (GradScaler) multiplies the loss before backward and unscales before the step, skipping steps with inf/NaN.
  • bf16 has the same exponent range as fp32 (less mantissa), so it usually needs no loss scaling; it is preferred on Ampere+ GPUs and TPUs.
  • Scaling further: DDP (data parallel, one model copy per GPU), FSDP/ZeRO (shard params, grads and optimiser state), gradient checkpointing, and torch.compile.

Interview questions

  • Why are GPUs so much faster than CPUs for deep learning?
  • What is mixed precision training and why does fp16 need loss scaling?
  • fp16 vs bf16?
  • Your model does not fit in GPU memory. What are your options?

Debugging training: loss not decreasing

Most training failures are bugs in data, shapes, loss setup or learning rate. Check them systematically, starting by overfitting one small batch.

  • Overfit a single batch first. A correct model and pipeline should drive training loss near 0 on ~10–100 examples. If it cannot, the bug is in the code, not the data size.
  • Check the initial loss: for C balanced classes, CE should start near ln(C) (≈2.30 for 10 classes). Much higher means bad init or wrong logits scale.
  • Inspect the data: visualise inputs after transforms, confirm labels match inputs, check normalisation, shuffling, and class balance.
  • Check shapes and loss setup: logits vs probabilities, target dtype, softmax applied twice, (N, C) vs (N, C, ...) mix-ups, broadcasting in MSE ((N,1) vs (N,)).
  • Learning rate: try a few values on a log scale; NaN usually means too high or a bad op (log 0, division by 0). Also check zero_grad(), model.train(), and that the optimiser has the right params.
  • Monitor gradient norms and activation statistics per layer; plot train and val curves together to separate underfitting from overfitting.

Interview questions

  • Your training loss is not decreasing. How do you debug it?
  • Loss becomes NaN after a few hundred steps. What do you check?
  • Validation accuracy is higher than training accuracy. Is that a bug?