Meta’s PyTorch org maintains the training stack behind its ranking and recommendation models, and its interviews like to probe whether you can read a loop the way a profiler does. In a coding round for that team, the interviewer hands you a 36-line PyTorch training and validation script. An AI coding assistant generated it for fine-tuning a 10-class classifier with BatchNorm and Dropout layers. The script runs without a single syntax or runtime exception. The small build_model() head is the minimal reproduction, and the production job plugs a pretrained encoder into the same loop.
Code Under Review (Spot the 4 Silent Bugs):
01 import torch
02 import torch.nn as nn
03 import torch.nn.functional as F
04
05 def build_model(in_dim=32, hidden=64, num_classes=10):
06 return nn.Sequential(
07 nn.Linear(in_dim, hidden), nn.BatchNorm1d(hidden), nn.ReLU(),
08 nn.Dropout(p=0.3), nn.Linear(hidden, num_classes))
09
10 def fit(model, train_loader, val_loader, epochs=5, device="cuda"):
11 model.to(device)
12 criterion = nn.CrossEntropyLoss()
13 optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
14 history = []
15 for epoch in range(epochs):
16 for x, y in train_loader:
17 x, y = x.to(device), y.to(device)
18 logits = model(x)
19 probs = F.softmax(logits, dim=-1)
20 loss = criterion(probs, y)
21 loss.backward()
22 optimizer.step()
23 train_loss = loss.item()
24
25 batch_losses = []
26 for x, y in val_loader:
27 x, y = x.to(device), y.to(device)
28 logits = model(x)
29 batch_losses.append(criterion(logits, y))
30 val_loss = sum(batch_losses) / len(val_loader)
31 history.append(val_loss)
32 print(f"epoch {epoch}: train {train_loss:.3f} "
33 f"val {val_loss.item():.3f}")
34 return history
35
36 # usage: history = fit(build_model(), train_dl, val_dl)Three things go wrong in practice. (1) Training loss starts near 2.30, falls to about 1.65 within the first few dozen steps, and then stops improving. (2) GPU memory climbs by roughly 10 GB on every validation pass until a CUDA out-of-memory error kills the job during epoch 4 on a 40 GB card. (3) The validation set has 1,030 samples and the loader uses batch size 128, so the final batch holds only 6 samples, and the reported epoch validation loss jumps erratically whenever that short batch is present.
Walk through the script in the order data and gradients flow. Identify the 4 silent bugs planted in the training and validation loops, and explain the exact mathematical or autograd reason each one triggers its symptom. Then provide the corrected training and validation code, and write a compact verification test that proves every fix works.

Figure 1: Illustrative telemetry from the run. Training loss stalls near 1.65, memory steps up every epoch until the 40 GB limit, and identical weights report different validation losses as the batch size changes.
1Inspection Checklist (Where to Look)
(1) Loss Contract: Check what tensor reaches the loss function and whether that loss already normalizes its input.
(2) Gradient Lifecycle: Check what happens to every parameter’s .grad buffer between one step and the next.
(3) Evaluation Context: Validation must neither mutate layer statistics nor keep autograd graphs alive across epochs.
(4) Metric Aggregation: An epoch metric is a statement about samples, not batches; check how unequal batch sizes are weighted.
2Visual Review Map (Figure 2)

Figure 2: The data path (solid) and gradient path (dashed) through the script. The question-mark markers flag the stages a reviewer inspects next.
3Interviewer Nudge & Line Focus
Walk the script in execution order and answer the interviewer’s Socratic check at each stage:
nn.CrossEntropyLoss already apply internally, and what happens to logit gradients when its input is pre-squashed into [0, 1]?
loss.backward() accumulates into .grad via +=; where in the inner loop is that buffer cleared before the next batch?
BatchNorm/Dropout) and autograd graph recording are two independent switches. Why does history.append(val_loss) pin ~10 GB per epoch?
batch_size=128, batch 9 has 6 samples. How much weight does sum(batch_losses) / len(val_loader) give those 6 samples?
Leave a Reply