You implement label smoothing with alpha=0.1 for a 5-class classification problem. The original one-hot label for class 2 is [0, 0, 1, 0, 0]. What is the smoothed label vector?
Smoothed = (1-alpha) × one_hot + alpha/num_classes = 0.9×[0,0,1,0,0] + 0.1/5×[1,1,1,1,1] = [0.02, 0.02, 0.92, 0.02, 0.02]. The true class gets 0.92 probability and each wrong class gets 0.02, preventing overconfident predictions; this happens because label smoothing redistributes probability mass from the target to other classes
Smoothed = [0.1, 0.1, 0.9, 0.1, 0.1] which sums to 1.3; alpha is distributed equally to all classes including the correct one
Smoothed = [0, 0, 0.9, 0, 0]; just reduce the correct class by alpha, the others stay at 0
Smoothed = [0.025, 0.025, 0.9, 0.025, 0.025]; alpha is split among the 4 wrong classes only, giving alpha/4=0.025 each
Answer: A. Smoothed = (1-alpha) × one_hot + alpha/num_classes = 0.9×[0,0,1,0,0] + 0.1/5×[1,1,1,1,1] = [0.02, 0.02, 0.92, 0.02, 0.02]. The true class gets 0.92 probability and each wrong class gets 0.02, preventing overconfident predictions; this happens because label smoothing redistributes probability mass from the target to other classes
ExplanationLabel smoothing formula: y_smooth = (1-alpha)×y_hot + alpha×(1/K). With alpha=0.1, K=5: uniform component = 0.1/5 = 0.02 for each class. True class: 0.9×1 + 0.02 = 0.92. Other classes: 0.9×0 + 0.02 = 0.02. Smoothed: [0.02, 0.02, 0.92, 0.02, 0.02]. Sum check: 0.02×4 + 0.92 = 0.08+0.92 = 1.0. Label smoothing prevents the model from becoming overconfident because it can never achieve zero loss — even a perfect prediction has loss = -0.92×ln(0.92) - 4×0.02×ln(0.02) > 0.
Question 162 · Mixed Precision Loss Scaling · hard
Calculate the following: In mixed precision training (FP16/FP32), the loss scale starts at 65536. After a training step with no overflow, the scale is multiplied by 2. After a step WITH overflow, the scale is divided by 2. If the first 3 steps have no overflow and step 4 overflows, what is the loss scale after step 4?
Step 0: scale=65536. Step 1 (ok): 65536×2=131072. Step 2 (ok): 131072×2=262144. Step 3 (ok): 262144×2=524288. Step 4 (overflow): 524288/2=262144. The gradients from step 4 are discarded and the optimizer step is skipped because the overflowed gradients are invalid
Because overflow resets the scale to its initial value rather than halving the previous scale, the loss scale after step 4 equals 65536
Because the overflow check is assumed to skip only the multiplication and leave the prior step's scale untouched, the loss scale after step 4 equals 524288, the same value it held after step 3
Since overflow is assumed to drive the scale toward zero rather than halve it, the loss scale after step 4 equals 0, treated here as a safety floor
Answer: A. Step 0: scale=65536. Step 1 (ok): 65536×2=131072. Step 2 (ok): 131072×2=262144. Step 3 (ok): 262144×2=524288. Step 4 (overflow): 524288/2=262144. The gradients from step 4 are discarded and the optimizer step is skipped because the overflowed gradients are invalid
ExplanationDynamic loss scaling adjusts to balance precision and range in FP16. Starting scale: 65,536 (2^16). Step 1 (no overflow): ×2 → 131,072. Step 2 (no overflow): ×2 → 262,144. Step 3 (no overflow): ×2 → 524,288. Step 4 (overflow detected in the FP16 gradients): ÷2 → 262,144. When an overflow occurs, the optimizer skips that step entirely because the FP16 gradients contain inf/nan values and cannot produce valid weight updates; halving the scale then reduces the chance of overflow on the next step. The loss scale after step 4 is 262,144.
Question 163 · U-Net Skip Connections · hard
You have a U-Net architecture for image segmentation. The encoder path has 4 downsampling stages (each halves spatial size), going from 256×256 to 128→64→32→16. The decoder mirrors this with upsampling. At the 64×64 decoder stage, a skip connection concatenates encoder features. If the encoder has 128 channels and decoder has 128 channels at this stage, what is the channel count after concatenation?
256 channels — skip connection concatenation along the channel dimension combines 128 encoder + 128 decoder = 256 channels at 64×64 spatial resolution. The subsequent convolution layer then reduces this back to 128 channels while combining local decoder features with fine-grained encoder details.
128 channels — skip connections add features element-wise, not concatenate them
64 channels — concatenation averages the channels: (128+128)/4 = 64 due to the 4-stage encoding
128 channels total — skip connections replace the decoder features with encoder features
Answer: A. 256 channels — skip connection concatenation along the channel dimension combines 128 encoder + 128 decoder = 256 channels at 64×64 spatial resolution. The subsequent convolution layer then reduces this back to 128 channels while combining local decoder features with fine-grained encoder details.
ExplanationU-Net skip connections CONCATENATE encoder and decoder feature maps along the channel axis (not add — that is ResNet). At 64×64: encoder features have shape (batch, 128, 64, 64) and decoder features have shape (batch, 128, 64, 64). Concatenation produces (batch, 256, 64, 64). The next conv layer (typically 3×3) maps 256→128 channels, learning to combine the encoder's high-resolution details with the decoder's semantic understanding. This is why U-Net excels at segmentation — it preserves spatial precision through skip connections while building semantic understanding through the bottleneck.
Question 164 · Receptive Field Analysis · hard
You compute the receptive field of a CNN with 3 consecutive 3×3 conv layers (stride 1, no padding). What is the effective receptive field size, and why might this be preferred over a single 7×7 convolution?
Receptive field = 7×7. Each 3×3 layer adds 2 to each side: layer 1 sees 3×3, layer 2 sees 5×5, layer 3 sees 7×7. Three 3×3 layers have 3×(3×3×C×C)=27C² parameters vs one 7×7 layer with 49C² parameters — 45% fewer parameters with the same receptive field, plus 3 ReLU nonlinearities instead of 1, giving more representational power.
Receptive field = 9×9 because 3×3×3 = 27 and sqrt(27) ≈ 5.2, rounded to 9
Receptive field = 3×3 because convolutions do not increase the receptive field when stacked
Same 7×7 receptive field, but with MORE total parameters than a single 7×7 convolution, since three stacked layers multiply the parameter count roughly 3×
Answer: A. Receptive field = 7×7. Each 3×3 layer adds 2 to each side: layer 1 sees 3×3, layer 2 sees 5×5, layer 3 sees 7×7. Three 3×3 layers have 3×(3×3×C×C)=27C² parameters vs one 7×7 layer with 49C² parameters — 45% fewer parameters with the same receptive field, plus 3 ReLU nonlinearities instead of 1, giving more representational power.
ExplanationFor stride-1 convolutions, receptive field = 1 + L×(k-1) where L=number of layers, k=kernel size. RF = 1 + 3×(3-1) = 1 + 6 = 7. Alternatively: layer 1 output pixel sees 3×3 input. Layer 2 sees 3×3 of layer 1 outputs, each seeing 3×3 input = 5×5 input. Layer 3: 7×7 input. Parameter comparison: three 3×3 = 3×9C² = 27C². One 7×7 = 49C². Savings: 27/49 = 55% of 7×7 params. Plus, 3 nonlinearities vs 1 means the 3-layer version can represent more complex functions. This VGGNet insight revolutionized CNN architecture design.
Question 165 · Cosine Annealing Schedule · hard
You implement a cosine annealing learning rate schedule with lr_max = 0.2, lr_min = 0.0, and period T = 200 epochs, using lr_t = lr_min + 0.5(lr_max − lr_min)(1 + cos(π × t / T)). What are the learning rates at epoch 50, epoch 100, and epoch 150?
Epoch 50: lr = 0 + 0.5×0.2×(1+cos(π/4)) = 0.1×1.7071 = 0.1707. Epoch 100: lr = 0.1×(1+cos(π/2)) = 0.1×1.0 = 0.1000. Epoch 150: lr = 0.1×(1+cos(3π/4)) = 0.1×0.2929 = 0.0293.
Epoch 50: 0.15, Epoch 100: 0.1, Epoch 150: 0.05; the schedule decreases linearly from lr_max to lr_min as t runs from 0 to T.
All three epochs give lr = 0.1 because cosine annealing simply outputs the average of lr_max and lr_min at every point within a period.
Epoch 50: lr = 0.2, Epoch 100: lr = 0.0, Epoch 150: lr = 0.2; the schedule reaches its minimum at t = T/2 and rises back to the maximum by t = T.
Answer: A. Epoch 50: lr = 0 + 0.5×0.2×(1+cos(π/4)) = 0.1×1.7071 = 0.1707. Epoch 100: lr = 0.1×(1+cos(π/2)) = 0.1×1.0 = 0.1000. Epoch 150: lr = 0.1×(1+cos(3π/4)) = 0.1×0.2929 = 0.0293.
ExplanationCosine annealing follows lr(t) = lr_min + 0.5(lr_max − lr_min)(1 + cos(π×t/T)). With lr_max = 0.2, lr_min = 0.0, and T = 200, the amplitude term 0.5(lr_max − lr_min) = 0.1. At t = 50, π×50/200 = π/4, and cos(π/4) ≈ 0.7071, giving lr = 0.1×(1+0.7071) = 0.1707. At t = 100, π×100/200 = π/2, and cos(π/2) = 0, giving lr = 0.1×(1+0) = 0.1000 — exactly the midpoint between lr_max and lr_min, reached halfway through the period. At t = 150, π×150/200 = 3π/4, and cos(3π/4) ≈ −0.7071, giving lr = 0.1×(1−0.7071) = 0.0293. The learning rate therefore decays smoothly and non-linearly from lr_max toward lr_min as t runs from 0 to T, reaching the true minimum only at t = T, never at t = T/2. Treating the decay as linear would instead predict 0.15, 0.1, and 0.05, and assuming the rate stays fixed at the average value throughout ignores the shape of the cosine curve entirely.
Question 166 · Temperature Scaling in Distillation · hard
In knowledge distillation, the teacher model outputs logits [5.0, 3.0, 1.0] for 3 classes (use e^2.5=12.18, e^1.5=4.48, e^0.5=1.65, e^5=148.4, e^3=20.09, e^1=2.718). Using temperature T=2, what are the softened probabilities, and how do these compare to standard softmax at T=1?
T=2: logits/T = [2.5, 1.5, 0.5]. Softmax: sum=12.18+4.48+1.65=18.31. P=[0.665, 0.245, 0.090]. T=1: sum=148.4+20.09+2.718=171.2. P=[0.867, 0.117, 0.016]. Higher temperature produces softer (more uniform) probabilities that reveal relative similarities between classes, giving the student richer learning signal.
T=2: multiply logits by T → [10, 6, 2]. Softmax becomes even more peaked than T=1
T=2: P = [0.5, 0.3, 0.1] / sum → normalized; temperature just scales the probabilities linearly
T=2 and T=1 produce identical probabilities because softmax is scale-invariant
Answer: A. T=2: logits/T = [2.5, 1.5, 0.5]. Softmax: sum=12.18+4.48+1.65=18.31. P=[0.665, 0.245, 0.090]. T=1: sum=148.4+20.09+2.718=171.2. P=[0.867, 0.117, 0.016]. Higher temperature produces softer (more uniform) probabilities that reveal relative similarities between classes, giving the student richer learning signal.
ExplanationWith T=2: divide logits by T → [2.5, 1.5, 0.5]. Softmax: e^2.5=12.18, e^1.5=4.48, e^0.5=1.65. Sum=18.31. P = [12.18/18.31, 4.48/18.31, 1.65/18.31] = [0.665, 0.245, 0.090]. With T=1: e^5=148.4, e^3=20.09, e^1=2.718. Sum=171.2. P = [0.867, 0.117, 0.016]. At T=1 the model is very confident (86.7% class 0). At T=2 the distribution is softer (66.5% class 0). The softer distribution reveals that class 1 is more similar to class 0 than class 2 is — this inter-class structure is the dark knowledge the student learns. Temperature scaling works because dividing logits by T > 1 flattens the distribution, while T < 1 sharpens it, calibrating confidence.
Question 167 · Gradient Clipping · hard
You implement gradient clipping with max_norm=5.0. Your gradient vector is g = [3, 4, 0, 0]. What is the L2 norm of g, is clipping applied, and what is the resulting gradient?
||g|| = sqrt(9+16+0+0) = sqrt(25) = 5.0. Since ||g|| = max_norm exactly, clipping is not applied (or equivalently, scale factor = max_norm/||g|| = 1.0). The gradient remains [3, 4, 0, 0] unchanged because it does not exceed the threshold
||g||² = 3²+4² = 9+16 = 25, and comparing this squared norm directly to max_norm=5.0, since 25 > 5.0, clipping is applied with scale factor 5/25 = 0.2, giving a resulting gradient of [0.6, 0.8, 0, 0]
||g|| = 7 (sum of absolute values), which exceeds 5.0, so g is scaled to [3×5/7, 4×5/7, 0, 0] = [2.14, 2.86, 0, 0]
Clipping sets each component to min(component, 5.0), giving [3, 4, 0, 0] unchanged because no component exceeds 5
Answer: A. ||g|| = sqrt(9+16+0+0) = sqrt(25) = 5.0. Since ||g|| = max_norm exactly, clipping is not applied (or equivalently, scale factor = max_norm/||g|| = 1.0). The gradient remains [3, 4, 0, 0] unchanged because it does not exceed the threshold
ExplanationL2 norm: ||g|| = sqrt(3²+4²+0²+0²) = sqrt(9+16) = sqrt(25) = 5.0. Gradient clipping: if ||g|| > max_norm, scale g by max_norm/||g||. Here ||g|| = 5.0 = max_norm (not strictly greater), so no scaling is needed and the result is [3, 4, 0, 0]. A common error is comparing the squared norm (25) to max_norm instead of the actual norm (5.0), which would wrongly trigger clipping and produce [0.6, 0.8, 0, 0] instead. Another error is using the L1 norm (sum of absolute values = 7) instead of the L2 norm. A third error is clamping each component independently with min(component, max_norm) instead of scaling the whole vector uniformly, which would distort the gradient's direction rather than preserve it. Important: gradient clipping scales the ENTIRE vector uniformly to preserve direction, unlike per-component clamping.
Question 168 · Class-Weighted Cross-Entropy · hard
You train a model using cross-entropy loss with class weights to handle imbalance. Classes are: A (500 samples, weight=1.0), B (100 samples, weight=5.0), C (50 samples, weight=10.0). If the model predicts sample i of class B with probability p=0.3, what is the weighted loss for this sample vs unweighted?
Unweighted CE = -ln(0.3) = 1.204. Weighted CE = weight_B × (-ln(0.3)) = 5.0 × 1.204 = 6.02. The weight makes misclassifying a class B sample 5 times more costly than class A, forcing the model to pay more attention to the minority class during gradient updates.
Weighted CE = -ln(0.3 × 5.0) = -ln(1.5) = -0.405; the weight multiplies the probability before taking the log
Weighted CE = -5.0 × ln(0.3 × 5.0) = -5.0 × ln(1.5) = -2.03; both multiply the probability and the log
Dividing by the weight: -ln(0.3) / 5.0 = 0.241; weights divide the loss for minority classes to reduce their impact
Answer: A. Unweighted CE = -ln(0.3) = 1.204. Weighted CE = weight_B × (-ln(0.3)) = 5.0 × 1.204 = 6.02. The weight makes misclassifying a class B sample 5 times more costly than class A, forcing the model to pay more attention to the minority class during gradient updates.
ExplanationStandard cross-entropy for true class B with predicted p=0.3: CE = -ln(0.3) = 1.204. Weighted version multiplies the loss by the class weight: Weighted_CE = w_B × CE = 5.0 × 1.204 = 6.02. The gradient for this sample is also 5× larger, making the model update 5× more strongly to correct this misclassification. The weights are typically set inversely proportional to class frequency: w = N_total/(num_classes × N_class). For class C with only 50 samples, weight=10 ensures that getting C wrong has 10× the penalty of getting A wrong, compensating for the 10:1 sample imbalance.
Question 169 · Vanishing Gradient Problem · hard
During backpropagation in a 10-layer deep network, the gradients in the first few layers become extremely small (e.g., 1e-12). Training stalls — the early layers stop learning. What is this phenomenon called, what causes it mathematically, and how do modern architectures solve it?
This is the vanishing gradient problem. Cause: backprop multiplies gradients through each layer via the chain rule. If each layer's gradient is < 1 (e.g., sigmoid derivative max = 0.25), after 10 layers: 0.25^10 ≈ 9.5e-7. Solutions: (1) ReLU activation (gradient = 1 for positive inputs, no shrinkage), (2) skip/residual connections (gradients flow directly through shortcuts), (3) batch normalization (keeps activations in healthy gradient range)
This is overfitting — the network has memorized the training data so well that gradients become unnecessary. Solution: add more training data or increase dropout rate to 90%
This is the dead neuron problem, caused by learning rates being too high. Solution: reduce the learning rate to 1e-15 so gradients accumulate more slowly
This is gradient explosion (not vanishing). Gradients of 1e-12 are actually very large in neural network terms. Solution: remove all activation functions to let gradients flow freely
Answer: A. This is the vanishing gradient problem. Cause: backprop multiplies gradients through each layer via the chain rule. If each layer's gradient is < 1 (e.g., sigmoid derivative max = 0.25), after 10 layers: 0.25^10 ≈ 9.5e-7. Solutions: (1) ReLU activation (gradient = 1 for positive inputs, no shrinkage), (2) skip/residual connections (gradients flow directly through shortcuts), (3) batch normalization (keeps activations in healthy gradient range)
ExplanationThe chain rule multiplies local gradients: dL/dw1 = dL/dz10 * dz10/dz9 * ... * dz2/dz1 * dz1/dw1. If each factor is < 1, the product shrinks exponentially. Sigmoid's max derivative is 0.25 (at z=0), so 10 sigmoid layers: gradient ≤ 0.25^10 ≈ 1e-6. Early layers receive near-zero gradients and stop learning. ReLU fixes this: its derivative is exactly 1 for positive inputs (no shrinkage). ResNets add skip connections: x + F(x), giving gradient paths that bypass layers entirely. He initialization (variance = 2/n) also helps by keeping initial activations in the linear regime.
Question 170 · GAN Training Dynamics · hard
In a GAN, the generator G creates fake images and the discriminator D classifies images as real/fake. Explain the minimax objective: min_G max_D [E[log D(x)] + E[log(1 - D(G(z)))]]. What happens if D becomes too strong too quickly?
D maximizes: log D(x) (correctly identifying real as real) + log(1-D(G(z))) (correctly identifying fake as fake). G minimizes: log(1-D(G(z))) (wants D to think fakes are real). If D becomes too strong, D(G(z)) → 0, so log(1-D(G(z))) → log(1) = 0 — G's gradient vanishes and it stops learning. This is the "vanishing gradient" problem for the generator. Solution: train D and G in alternating steps, or use Wasserstein loss which provides gradients even when D is confident
The minimax objective means G and D are trained simultaneously on the same loss. If D is too strong, G automatically becomes stronger because they share weights
D maximizes fake image quality while G minimizes it. If D becomes too strong, it starts generating better images than G, and their roles swap
The minimax objective means both G and D try to minimize the same loss. If D is too strong, training converges faster because D provides better supervision for G
Answer: A. D maximizes: log D(x) (correctly identifying real as real) + log(1-D(G(z))) (correctly identifying fake as fake). G minimizes: log(1-D(G(z))) (wants D to think fakes are real). If D becomes too strong, D(G(z)) → 0, so log(1-D(G(z))) → log(1) = 0 — G's gradient vanishes and it stops learning. This is the "vanishing gradient" problem for the generator. Solution: train D and G in alternating steps, or use Wasserstein loss which provides gradients even when D is confident
ExplanationThe GAN game: D wants to output 1 for real data (maximize log D(x)) and 0 for fake data (maximize log(1-D(G(z)))). G wants D to output 1 for its fakes (minimize log(1-D(G(z)))). If D is perfect: D(real)=1, D(fake)=0. Then G's loss = log(1-0) = 0 with near-zero gradient — G cannot learn which direction to improve. This is why GAN training is notoriously unstable. Wasserstein GAN (WGAN) uses Earth Mover's distance instead, providing meaningful gradients even when D is confident. Practical fix: train D for k=1 step, then G for 1 step, keeping them balanced.
Question 171 · Q-Learning and Exploration · hard
You implement Q-learning for a grid-world robot. The update rule is: Q(s,a) ← Q(s,a) + α[r + γ·max_a' Q(s',a') - Q(s,a)]. The robot is at state S with Q-values: Q(S,up)=5, Q(S,right)=8, Q(S,down)=3, Q(S,left)=2. With ε-greedy (ε=0.1), what action does it take and why?
With ε=0.1: 90% probability it exploits (picks the best action) = right (Q=8). 10% probability it explores (picks a random action from all four). ε-greedy balances exploitation (using what it knows) with exploration (discovering potentially better paths). Without exploration, the robot might miss a shorter route it never tried. Over time, ε is typically decayed toward 0
It always picks 'right' because Q(S,right)=8 is highest. The ε parameter only affects the learning rate α, not action selection
It picks a random action with probability 0.9 and the best action with probability 0.1. ε represents the exploitation rate, not the exploration rate
It picks 'up' because ε=0.1 means the agent adds 0.1 to each Q-value before selecting, and Q(S,up)+0.1 rounds up to the highest adjusted value
Answer: A. With ε=0.1: 90% probability it exploits (picks the best action) = right (Q=8). 10% probability it explores (picks a random action from all four). ε-greedy balances exploitation (using what it knows) with exploration (discovering potentially better paths). Without exploration, the robot might miss a shorter route it never tried. Over time, ε is typically decayed toward 0
Explanationε-greedy: with probability ε (0.1), choose a random action (explore); with probability 1-ε (0.9), choose argmax Q(s,a) (exploit). Here, exploitation chooses 'right' (Q=8, highest). The 10% exploration ensures the robot occasionally tries non-optimal actions, which might lead to discovering better long-term strategies. The Q-update rule uses the Bellman equation: current estimate + α*(target - current), where target = immediate reward + discounted future value. α controls learning speed, γ controls how much future rewards matter.
Question 172 · Static vs Contextual Embeddings · hard
In NLP, the sentence "Bank of the river" and "Bank gave me a loan" use "bank" with different meanings. Compare how Word2Vec embeddings handle this polysemy problem vs how contextual embeddings (like BERT) solve it — what is the output embedding for "bank" in each scenario?
Word2Vec assigns ONE fixed vector per word regardless of context — "bank" gets a single embedding that is an average of all its meanings (financial + river). This fails for polysemy. BERT generates DIFFERENT embeddings for the same word based on surrounding context: "bank" near "river" gets a geography-related vector, "bank" near "loan" gets a finance-related vector. BERT achieves this through self-attention across the entire sentence
Word2Vec creates separate vectors for each meaning automatically by detecting context during training. BERT is no different — it just uses larger vectors
Word2Vec handles polysemy perfectly because the skip-gram model considers the 5-word window around each occurrence, generating context-specific embeddings
Neither Word2Vec nor BERT can handle polysemy. This requires a dictionary lookup table that maps words to their correct meaning based on the sentence topic
Answer: A. Word2Vec assigns ONE fixed vector per word regardless of context — "bank" gets a single embedding that is an average of all its meanings (financial + river). This fails for polysemy. BERT generates DIFFERENT embeddings for the same word based on surrounding context: "bank" near "river" gets a geography-related vector, "bank" near "loan" gets a finance-related vector. BERT achieves this through self-attention across the entire sentence
ExplanationWord2Vec (skip-gram/CBOW) learns one vector per word type from co-occurrence statistics. The single "bank" vector ends up somewhere between its financial and geographical meanings — a compromise that represents neither perfectly. BERT processes the full sentence through 12+ transformer layers with self-attention: each token's representation is influenced by ALL other tokens. So "bank" attends to "river" and produces a nature-context embedding, while "bank" attending to "loan" produces a finance-context embedding. This is why BERT revolutionized NLP — contextual embeddings capture word sense naturally.
Question 173 · Transfer Learning and Fine-Tuning · hard
You are fine-tuning a pre-trained ResNet-50 (trained on ImageNet, 1000 classes) for classifying 5 types of Indian street food images (samosa, vada pav, pani puri, dosa, jalebi). Evaluate this scenario — which layers do you freeze, which do you replace, and what happens during the forward pass through the modified architecture?
Freeze early layers (edges, textures — universal features), freeze middle layers (shapes, patterns — mostly transferable), REPLACE the final classification layer (1000 → 5 neurons). Fine-tune the last few convolutional blocks with a small learning rate. This works because ImageNet features (edges, textures, shapes) transfer to food images — only the final class-specific mapping needs relearning. Training from scratch would require 100x more food images
Replace ALL layers because ImageNet classes (dogs, cars) share nothing with food images. Every weight must be randomly reinitialized and trained from scratch on your 5-class dataset
Freeze all layers and only add a new fully connected layer on top. Never fine-tune any pre-trained weights because this causes catastrophic forgetting of ImageNet features
Only replace the first convolutional layer because that is where class-specific features are stored. The rest of the network is generic and transfers automatically
Answer: A. Freeze early layers (edges, textures — universal features), freeze middle layers (shapes, patterns — mostly transferable), REPLACE the final classification layer (1000 → 5 neurons). Fine-tune the last few convolutional blocks with a small learning rate. This works because ImageNet features (edges, textures, shapes) transfer to food images — only the final class-specific mapping needs relearning. Training from scratch would require 100x more food images
ExplanationCNN feature hierarchy: early layers learn edges, corners, textures (universal to all images); middle layers learn shapes, parts (mostly transferable); final layers learn class-specific combinations. This produces the result that food classification works because edges/textures of crispy samosa crust and round vada pav shape are built from universal low/mid-level features. Only the final mapping (features → food classes) is domain-specific. Strategy: (1) Replace final FC layer: nn.Linear(2048, 5), because the original outputs 1000 classes. (2) Freeze early+middle layers (layers 1-45 of 50). (3) Fine-tune last 1-2 residual blocks with lr=1e-4 (10x smaller than new layer's lr=1e-2). This requires only ~500-1000 images per class instead of millions, since the frozen layers already extract useful features.
Question 174 · Dropout Regularization · hard
Explain dropout with p=0.5 during training. If a hidden layer has 100 neurons and dropout is applied, how many neurons are active on average per forward pass? Why must the outputs be scaled during inference?
With p=0.5 dropout, each neuron is randomly deactivated with 50% probability per forward pass. On average, 50 of 100 neurons are active. During inference (no dropout), ALL 100 neurons fire — producing outputs 2x larger than training. To compensate, inference outputs are scaled by (1-p) = 0.5, OR training outputs are scaled by 1/(1-p) = 2 (inverted dropout, more common). Without scaling, the magnitude mismatch between training and inference breaks the model
50 neurons are active, but no scaling is needed because the weights automatically adjust during training to account for the missing neurons
All 100 neurons are active — dropout only affects the learning rate, not neuron activation. Scaling is applied to gradients, not outputs
75 neurons are active (p=0.5 means 50% extra neurons are added temporarily). During inference, the extra neurons are removed, so no scaling is needed
Answer: A. With p=0.5 dropout, each neuron is randomly deactivated with 50% probability per forward pass. On average, 50 of 100 neurons are active. During inference (no dropout), ALL 100 neurons fire — producing outputs 2x larger than training. To compensate, inference outputs are scaled by (1-p) = 0.5, OR training outputs are scaled by 1/(1-p) = 2 (inverted dropout, more common). Without scaling, the magnitude mismatch between training and inference breaks the model
ExplanationDropout randomly zeroes each neuron's output with probability p during training. With p=0.5 and 100 neurons: E[active] = 100*(1-0.5) = 50. This forces the network to learn redundant representations (no single neuron can be relied upon). At inference, dropout is disabled — all 100 neurons fire, doubling the expected output magnitude. Inverted dropout (standard in PyTorch/TF) scales training outputs by 1/(1-p) = 2, so inference needs no modification. Mathematically: during training, E[output] = (1-p)*x * 1/(1-p) = x. During inference: output = x. The expectations match.
Question 175 · Model Capacity and Overfitting · medium
A student asks: "If I increase my model from 2 layers to 200 layers, won't it always perform better since it can learn more complex patterns?" Given that the 2-layer model has 50,000 parameters and the 200-layer model has 5,000,000 parameters, evaluate this claim — what happens to training loss vs validation loss as depth increases?
False. While more layers increase model capacity (ability to represent complex functions), diminishing returns and new problems emerge: (1) Overfitting — with limited training data, a 200-layer model memorizes noise. (2) Vanishing/exploding gradients make training unstable. (3) Computation: 100x more parameters = 100x more memory and training time. (4) The bias-variance tradeoff: too much capacity increases variance. The right depth depends on dataset size, task complexity, and regularization
True. Universal approximation theorem guarantees that more layers always produce better results, with no exceptions. The only constraint is GPU memory
True for image tasks, false for text tasks. Image data requires deep networks while text data requires wide networks. The layer count should match the data modality
False, but only because 200 layers is too few. Modern AI requires at least 1000 layers to see any benefit from depth. The magic number is approximately 500 layers for most tasks
Answer: A. False. While more layers increase model capacity (ability to represent complex functions), diminishing returns and new problems emerge: (1) Overfitting — with limited training data, a 200-layer model memorizes noise. (2) Vanishing/exploding gradients make training unstable. (3) Computation: 100x more parameters = 100x more memory and training time. (4) The bias-variance tradeoff: too much capacity increases variance. The right depth depends on dataset size, task complexity, and regularization
ExplanationThe universal approximation theorem says a single hidden layer CAN approximate any function — but doesn't say it's practical. Depth helps learn hierarchical features (edges → shapes → objects), but too much depth with insufficient data leads to overfitting because the model memorizes noise. A 200-layer model (5M params) on 1000 training images produces training loss near 0.001 but validation loss of 2.5+ — classic overfitting. Additionally, deeper networks face vanishing gradients (gradient shrinks by 0.25^200 with sigmoid), which causes early layers to stop learning entirely. ResNets solve this with skip connections, and GPT-3 with 96 layers cost ~$4.6M to train. The result is that model complexity must match data complexity — 200 layers need millions of samples to generalize.
Question 176 · Self-Attention Mechanism · medium
In attention mechanisms, Q (query), K (key), and V (value) matrices are used. For a sentence with 5 tokens and embedding dimension 64, compute the dimensions of Q, K, V, and the attention weight matrix — what is the shape of each output in the self-attention calculation?
Q, K, V each have shape (5, 64) — 5 tokens, 64-dimensional. Attention weights = softmax(Q · K^T / sqrt(64)), shape = (5, 5). Each entry (i,j) represents how much token i attends to token j. Output = attention_weights · V, shape = (5, 64). The sqrt(64) scaling prevents dot products from becoming too large (which would make softmax produce near-one-hot distributions, killing gradients)
Q has shape (64, 64), K has shape (5, 5), V has shape (64, 5). The attention matrix is (64, 64) because attention operates in embedding space, not token space
Q, K, V all have shape (5, 5). Attention weights have shape (64, 64). The computation is V · Q · K, not Q · K^T · V
Q and K have shape (5, 64) but V has shape (5, 1) because values are scalar scores. The attention output is a single number per token
Answer: A. Q, K, V each have shape (5, 64) — 5 tokens, 64-dimensional. Attention weights = softmax(Q · K^T / sqrt(64)), shape = (5, 5). Each entry (i,j) represents how much token i attends to token j. Output = attention_weights · V, shape = (5, 64). The sqrt(64) scaling prevents dot products from becoming too large (which would make softmax produce near-one-hot distributions, killing gradients)
ExplanationGiven input X (5×64): Q = X·W_Q, K = X·W_K, V = X·W_V, where W matrices are (64×64), giving Q,K,V all (5×64). Attention scores: Q·K^T = (5×64)·(64×5) = (5×5). Each entry = dot product of two 64-dim vectors. Scale by 1/sqrt(64) = 1/8 to prevent large magnitudes. Softmax row-wise: each row sums to 1, giving a probability distribution over tokens. Multiply by V: (5×5)·(5×64) = (5×64). Result: each token's output is a weighted sum of all tokens' values, weighted by attention scores. This is the core of Transformers.
Question 177 · LSTM vs Vanilla RNN · hard
Compare LSTM and vanilla RNN for processing a 100-word sentence. The vanilla RNN suffers from vanishing gradients — analyze how the LSTM's cell state mechanism solves this, and what is the role of the forget gate f_t = sigma(W_f * [h_{t-1}, x_t] + b_f)?
In a vanilla RNN, the hidden state is overwritten each step: h_t = tanh(W*h_{t-1} + U*x_t). After 100 steps, gradients multiply through 100 tanh derivatives (max 1.0), shrinking exponentially. LSTM adds a cell state C_t that flows through time with only element-wise operations (no matrix multiply), preserving gradients. The forget gate f_t decides what to ERASE from memory: f_t ≈ 0 erases, f_t ≈ 1 preserves. For word 100 to influence word 1's gradient, the cell state provides a "gradient highway" that bypasses the vanishing problem
LSTMs and vanilla RNNs process sequences identically — the only difference is that LSTMs have more parameters, making them slower but not fundamentally different in gradient flow
The forget gate controls the learning rate: f_t = 0 means no learning occurs at time t, while f_t = 1 means maximum learning rate. It has nothing to do with memory or gradient flow
LSTMs solve vanishing gradients by using ReLU instead of tanh in the cell state update. The forget gate is a regularization mechanism equivalent to dropout at each time step
Answer: A. In a vanilla RNN, the hidden state is overwritten each step: h_t = tanh(W*h_{t-1} + U*x_t). After 100 steps, gradients multiply through 100 tanh derivatives (max 1.0), shrinking exponentially. LSTM adds a cell state C_t that flows through time with only element-wise operations (no matrix multiply), preserving gradients. The forget gate f_t decides what to ERASE from memory: f_t ≈ 0 erases, f_t ≈ 1 preserves. For word 100 to influence word 1's gradient, the cell state provides a "gradient highway" that bypasses the vanishing problem
ExplanationVanilla RNN gradient: dL/dh_1 = product(dh_t/dh_{t-1}, t=2..100). Each factor involves tanh derivative (max 1.0) and weight matrix W, producing a product that shrinks exponentially over 100 steps — word 1 gets near-zero gradient from word 100. LSTM cell state: C_t = f_t * C_{t-1} + i_t * tanh(W_C * [h_{t-1}, x_t]). The gradient through C flows as: dC_{t-1}/dC_t = f_t (element-wise multiply, no matrix multiply). If f_t ≈ 1, gradients flow unchanged through 100 steps — this is the "gradient highway." The forget gate f_t = sigma(W_f * [h_{t-1}, x_t] + b_f) learns when to clear memory (f_t→0) vs preserve (f_t→1). For a pronoun resolution task, f_t keeps "she" in memory until the referent is resolved.
Question 178 · Multi-Head Attention · hard
In a transformer model, multi-head attention uses h=8 heads with d_model=512. What is the dimension d_k per head, and how would you evaluate why multiple smaller attention heads outperform a single large attention head of dimension 512?
d_k = d_model / h = 512/8 = 64 per head. Each head independently computes attention with its own W_Q, W_K, W_V projections (512→64 each). 8 heads outperform 1 large head because each head can learn DIFFERENT attention patterns: head 1 might capture syntactic dependencies (subject-verb), head 2 might capture semantic similarity, head 3 might focus on positional proximity. A single 512-dim head would blend all patterns into one, losing this specialization
d_k = 512 * 8 = 4096 per head. Multiple heads are used for computational parallelism only — they produce identical results to a single large head but run faster on GPUs
d_k = 512 for all 8 heads (each head uses the full dimension). Multiple heads are just an ensemble technique that averages 8 identical attention computations for stability
d_k = 8 (the number of heads). Each head attends to exactly 8 positions in the sequence, and the outputs are concatenated to form the 512-dim result
Answer: A. d_k = d_model / h = 512/8 = 64 per head. Each head independently computes attention with its own W_Q, W_K, W_V projections (512→64 each). 8 heads outperform 1 large head because each head can learn DIFFERENT attention patterns: head 1 might capture syntactic dependencies (subject-verb), head 2 might capture semantic similarity, head 3 might focus on positional proximity. A single 512-dim head would blend all patterns into one, losing this specialization
Explanationd_k = d_model/h = 512/8 = 64. Each head has separate learned projections: W_Q^i (512×64), W_K^i (512×64), W_V^i (512×64). Head i computes: Attention_i = softmax(Q_i * K_i^T / sqrt(64)) * V_i. All 8 outputs (each 64-dim) are concatenated back to 512-dim, then linearly projected. Why this works: in "The cat sat on the mat because it was tired," different heads learn different "it" → "cat" attention patterns. Head 1 might attend based on recency, head 2 on syntactic role, head 3 on semantic fit. Total parameters: 8 * 3 * (512*64) = 786,432 for Q,K,V projections. This is the same parameter count as a single 512-dim head: 3 * (512*512) = 786,432.
Question 179 · SARSA vs Q-Learning · hard
In reinforcement learning, what is the difference between on-policy (SARSA) and off-policy (Q-learning) methods? Given state S, action a=right (chosen by epsilon-greedy), reward R=10, next state S', and next action a'=up (chosen by epsilon-greedy), how does each method compute the TD target?
SARSA (on-policy) TD target: R + gamma * Q(S', a') = 10 + gamma * Q(S', up). It uses the ACTUAL next action a' chosen by the current policy (including exploratory actions). Q-learning (off-policy) TD target: R + gamma * max_a Q(S', a). It uses the BEST possible next action regardless of what was actually taken. Difference: SARSA learns the value of the policy being followed (including exploration mistakes). Q-learning learns the value of the optimal policy even while exploring
Both methods use identical TD targets: R + gamma * Q(S', a'). The on-policy vs off-policy distinction only affects how actions are selected, not how values are updated
SARSA uses: R + gamma * min_a Q(S', a) (pessimistic estimate). Q-learning uses: R + gamma * max_a Q(S', a) (optimistic estimate). SARSA is always safer but slower to converge
On-policy means the agent follows a fixed policy forever. Off-policy means the agent randomly switches between policies each episode. The TD target calculation is the same for both
Answer: A. SARSA (on-policy) TD target: R + gamma * Q(S', a') = 10 + gamma * Q(S', up). It uses the ACTUAL next action a' chosen by the current policy (including exploratory actions). Q-learning (off-policy) TD target: R + gamma * max_a Q(S', a). It uses the BEST possible next action regardless of what was actually taken. Difference: SARSA learns the value of the policy being followed (including exploration mistakes). Q-learning learns the value of the optimal policy even while exploring
ExplanationSARSA update: Q(S,a) += alpha * [R + gamma * Q(S',a') - Q(S,a)], where a' is the action actually taken at S'. Q-learning update: Q(S,a) += alpha * [R + gamma * max_a' Q(S',a') - Q(S,a)], where max_a' gives the value of the best action. With alpha=0.1, gamma=0.99, and R=10: SARSA target = 10 + 0.99*Q(S',up), Q-learning target = 10 + 0.99*max_a Q(S',a). Practical impact: near a cliff edge with reward -100, epsilon-greedy (epsilon=0.1) sometimes picks 'fall off cliff'. SARSA accounts for this risk because a' might be the bad action, producing lower Q-values near cliffs. Q-learning ignores exploration risk because it uses max (the optimal action). This makes SARSA "safer" — it learns policies that account for the agent's 10% exploration mistakes, giving more conservative behavior.
Question 180 · VAE Reparameterization Trick · medium
In a Variational Autoencoder (VAE), the encoder outputs mu and log_sigma, and we sample z = mu + sigma * epsilon where epsilon ~ N(0,1). Evaluate why this "reparameterization trick" is necessary — what happens if you try to backpropagate through a random sampling operation directly?
Direct sampling z ~ N(mu, sigma^2) is a stochastic node with no gradient — you cannot compute dL/dmu or dL/dsigma because the sampling operation is not differentiable. The reparameterization trick rewrites z = mu + sigma * epsilon, moving the randomness to epsilon (which is independent of parameters). Now dL/dmu and dL/dsigma can be computed because z is a deterministic differentiable function of mu and sigma. This enables standard backpropagation through the encoder
Direct sampling works fine for backpropagation. The reparameterization trick is purely for computational efficiency — it makes GPU matrix operations faster but doesn't change the gradients
The reparameterization trick converts continuous latent variables to discrete ones, which are easier to optimize. Without it, the VAE would need to enumerate all possible z values
Direct sampling produces identical results to the reparameterization trick. The trick was introduced for historical reasons and has been deprecated in modern frameworks like PyTorch 2.0
Answer: A. Direct sampling z ~ N(mu, sigma^2) is a stochastic node with no gradient — you cannot compute dL/dmu or dL/dsigma because the sampling operation is not differentiable. The reparameterization trick rewrites z = mu + sigma * epsilon, moving the randomness to epsilon (which is independent of parameters). Now dL/dmu and dL/dsigma can be computed because z is a deterministic differentiable function of mu and sigma. This enables standard backpropagation through the encoder
ExplanationThe core problem: backprop needs d(output)/d(parameters) for every node. A sampling node z ~ N(mu, sigma^2) has no meaningful derivative — "how does z change when mu changes by 0.01?" has no answer because z is random. The trick: z = mu + sigma * epsilon, where epsilon ~ N(0,1) is sampled ONCE and treated as a constant. Now: dz/dmu = 1, dz/dsigma = epsilon — both are well-defined. Gradients flow through: dL/dmu = dL/dz * 1, dL/dsigma = dL/dz * epsilon. This produces the result that the encoder parameters (mu, sigma) receive gradient updates, enabling end-to-end training. Without this trick, VAEs cannot be trained with standard backpropagation — you'd need REINFORCE estimators, which have high variance and slow convergence.