KatInterview

Diagnosing a Misbehaving Encoder-Decoder Training Loop

Machine LearningModel answer
HardModel answerMachine Learningtransformerspytorchdebugging

Last updated

Find and fix the hidden bugs in a PyTorch encoder-decoder trainer where validation stays at chance, AMP crashes, and runs are not reproducible, then plan the debugging.

Scenario

A teammate hands you a PyTorch sequence-to-sequence training script built around a multi-head-attention encoder-decoder. It includes:

  • tokenization with padding and truncation
  • attention and causal masks
  • AdamW with weight decay
  • gradient clipping
  • a cosine learning-rate schedule with warmup
  • mixed-precision (AMP) training with gradient accumulation
  • teacher forcing

The run behaves badly in four ways:

  1. Sporadic shape errors or IndexErrors in code that touches attention masks.
  2. Training loss falls (or sometimes blows up), yet validation accuracy stays close to chance.
  3. Occasional crashes when AMP and gradient accumulation are used together.
  4. Two runs with the same config give different results.

Your tasks

  1. Name at least four distinct root causes that could explain these symptoms. Useful areas to consider: mask shape, dtype, device and polarity; label shifting and PAD handling in the loss; placement of zero_grad; the order of scaling, unscaling and clipping under AMP; positional-encoding shape or index range; which parameters get weight decay; and train/validation leakage.
  2. For each cause, describe the signal that reveals it, give a minimal code fix, and write a unit test or runtime assertion that would prevent a regression.
  3. Give a component-by-component debugging plan with concrete checks for: data preprocessing, tokenization and masks, positional encodings, loss computation, optimizer/scheduler/clipping, AMP settings, seeding and deterministic kernels, and distributed (DDP) sampling.
  4. Describe sanity checks and metrics, such as overfitting a tiny subset, a copy task, gradient and activation statistics, and NaN/Inf detection, plus one small experiment that confirms each fix.

Hints

Hint 1

Start from the symptom: train-good/validation-chance usually means the model sees information at train time that it will not have at inference (no label shift, future leakage, or split leakage).

Hint 2

Check conventions at every API boundary: in PyTorch attention modules a True boolean mask means 'block', while tokenizers usually emit 1 for 'keep'; also check batch_first versus sequence-first layouts.

Hint 3

For AMP with accumulation, write out the exact order of scale, backward, unscale, clip, step, update, zero_grad, and scheduler step, and decide which of them happen every micro-batch versus once per optimizer step.

Hint 4

Prefer cheap isolating experiments: overfit 32 examples, run a copy task, perturb future tokens and confirm earlier outputs do not change, and compare accum=4 with batch 8 against accum=1 with batch 32.