ML Coding RoundsAdvanced18 min read5 questions

PyTorch Fluency & Debugging Under Interview Pressure

Write a correct training loop from memory, explain autograd precisely, and debug a broken model live — the three things a PyTorch round actually tests.

Covers: Autograd, Dataset/DataLoader, training loops, debugging NaNs and shapes, custom layers, profiling

PyTorch rounds are less about exotic knowledge and more about fluency: can you write a correct training loop without a template, do you know what zero_grad actually does, and can you find a bug in someone else's model in ten minutes?

Filter
0/5 mastered
AdvancedautogradpytorchgradientsAsked at Meta AI, NVIDIA

30-second answer

PyTorch builds a dynamic computation graph during the forward pass, recording each operation and its inputs. Calling `.backward()` traverses it in reverse applying the chain rule and accumulating into `.grad`. `requires_grad` marks a tensor as needing gradients; `detach()` returns a tensor sharing storage but cut from the graph; `no_grad()` disables graph construction entirely for a block; `retain_graph=True` keeps the graph alive so you can backward through it twice.

Intermediatepytorchtraining-loopbest-practicesAsked at Meta AI, Tesla

30-second answer

Set the model to train mode, iterate batches, move to device, zero gradients, forward, compute loss, backward, clip gradients, optimiser step, scheduler step. Then a validation pass under `no_grad()` in eval mode, tracking the best checkpoint. The details that separate correct from nearly-correct are `zero_grad(set_to_none=True)`, `.item()` for accumulation, model.train()/eval() toggling, and stepping the scheduler at the right granularity.

AdvanceddebuggingpytorchtrainingAsked at Meta AI, OpenAI

30-second answer

For NaN: check for division by zero or log(0) in the loss, exploding gradients (log the gradient norm), fp16 overflow, and bad input data. For not-learning: verify the loss is actually connected to the parameters, that `zero_grad` and `step` are both called, that the learning rate is sane, that labels align with predictions, and that the model can overfit a single batch.

Intermediatedataloaderpytorchdata-pipelineAsked at Hugging Face, Meta AI

30-second answer

Implement `__len__` and `__getitem__` returning a single unbatched example, then write a `collate_fn` that pads sequences to the batch maximum and builds an attention mask. Pad to the longest in the batch rather than a global maximum, and use a length-grouped sampler so batches contain similar lengths — that alone often cuts wasted compute by 30–50%.

AdvancedprofilingperformancegpuAsked at NVIDIA, Meta AI

30-second answer

30% utilisation almost always means the GPU is starved by the input pipeline, not that the model is slow. Check data loading first (num_workers, pin_memory, expensive per-item transforms, slow storage), then synchronisation points (`.item()`, `.cpu()`, printing inside the loop), then the model itself. Use the PyTorch profiler to see the actual gaps rather than guessing.

Showing 5 of 5 questions for pytorch-and-ml-engineering-coding.

Check your understanding

5 questions · no sign-up, nothing stored

0/5 answered
Question 1

1.`total_loss += loss` inside a training loop causes:

Question 2

2.For a balanced 10-class classification problem, the initial cross-entropy loss of an untrained model should be approximately:

Question 3

3.In a variable-length text pipeline, you should pad each batch to:

Question 4

4.GPU utilisation is 30% during training. The most likely cause is:

Question 5

5.The difference between `.detach()` and `torch.no_grad()` is:

Hands-on challenge

Build it — this is what you talk about in a deep-dive round.

Fix a deliberately broken training script

Build a training script, plant realistic bugs, then write the diagnostic tooling that finds them.

Requirements

  • A complete training loop with AMP, gradient clipping, scheduler, early stopping and checkpointing.
  • A `diagnose()` function checking inputs, shapes, initial loss vs ln(k), per-layer gradient norms, and single-batch overfitting.
  • A custom Dataset with length-grouped batching; measure and report the padding-waste reduction.
  • A profiling run showing the bottleneck, plus before/after timings for each optimisation you apply.

Stretch goals

  • Plant five bugs (detached branch, wrong label alignment, missing eval mode, LR 100× too high, missing zero_grad) and verify your diagnostic catches each.
  • Add torch.compile and report the speedup plus any graph breaks it reports.