Diagnosing a Misbehaving Encoder-Decoder Training Loop
Machine LearningModel answerLast 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:
- Sporadic shape errors or
IndexErrors in code that touches attention masks. - Training loss falls (or sometimes blows up), yet validation accuracy stays close to chance.
- Occasional crashes when AMP and gradient accumulation are used together.
- Two runs with the same config give different results.
Your tasks
- 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. - 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.
- 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.
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to approach it
Map each symptom to a short list of likely causes, then isolate each with a cheap test rather than guessing. For every bug, give the signal, the fix, and a regression test.
| Symptom | Likely causes |
|---|---|
Shape errors / IndexError | Mask layout or batch_first mismatch; position ids beyond the table size |
| Train loss falls, validation at chance | Missing label shift; future leakage via a wrong causal mask; split leakage |
| AMP + accumulation crashes or divergence | Wrong unscale/clip/step order; fp16 mask overflow; misplaced zero_grad |
| Nondeterminism | Unseeded workers, cudnn.benchmark, missing set_epoch |
Bug 1: Mask polarity, shape or dtype
Signal. Boolean masks in nn.MultiheadAttention / nn.Transformer use True = "do not attend". Tokenizer attention_mask uses 1 = "keep". Feeding it directly inverts the mask, so the model attends only to padding. A missing or transposed causal mask lets the decoder see future tokens: train loss collapses, autoregressive validation stays at chance. A (T, B) mask with batch_first=True raises shape errors.
Fix.
causal = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1)
src_pad = (src_ids == pad_id) # (B, S), True = pad
tgt_pad = (tgt_in == pad_id)
out = model(src, tgt, tgt_mask=causal,
src_key_padding_mask=src_pad,
tgt_key_padding_mask=tgt_pad,
memory_key_padding_mask=src_pad)
For additive float masks, use torch.finfo(dtype).min, not -1e9, since fp16 turns the latter into -inf and a fully masked row yields NaN.
Tests.
def test_no_future_leak(model):
model.eval()
x = torch.randint(5, 100, (2, 10))
y1 = model.decode(x)
x2 = x.clone(); x2[:, 6:] = 7
assert torch.allclose(y1[:, :6], model.decode(x2)[:, :6], atol=1e-5)
Add a pad-invariance test (appending PAD must not change outputs at real positions) and an assertion that the padding mask is bool with the same shape as input_ids.
Bug 2: No label shift, or PAD counted in the loss
Signal. If decoder input and target are the same sequence, the model learns identity: train loss goes to ~0, greedy decoding is garbage. Counting PAD inflates accuracy and biases predictions toward PAD.
Fix.
dec_in, labels = tgt[:, :-1], tgt[:, 1:].clone()
labels[labels == pad_id] = -100
loss = F.cross_entropy(logits.reshape(-1, V), labels.reshape(-1),
ignore_index=-100, label_smoothing=0.1)
Test. Where both are non-pad, assert labels[i, t] == tgt[i, t+1] and that dec_in[i, t+1] equals the label at t shifted correctly. Also assert the loss is unchanged when extra PAD positions are appended.
Bug 3: AMP + accumulation ordering
Signals.
clip_grad_norm_beforescaler.unscale_clips scaled gradients (norms ~65536x too large), so clipping is wrong.- Calling
unscale_twice beforestepraises aRuntimeError, often only on the final partial accumulation window. zero_gradevery micro-step discards accumulation; never calling it lets gradients grow until divergence.- Stepping the scheduler per micro-batch shortens warmup by a factor of
accum.
Fix.
for i, batch in enumerate(loader):
with torch.autocast("cuda", dtype=torch.float16):
loss = compute_loss(model, batch) / accum
scaler.scale(loss).backward()
if (i + 1) % accum == 0 or i + 1 == len(loader):
scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt); scaler.update()
opt.zero_grad(set_to_none=True)
sched.step()
Test. In fp32 with fixed seeds, one step with accum=4, bs=8 must match accum=1, bs=32 within ~1e-5. Log scaler.get_scale() and alert if it keeps collapsing.
Bug 4: Positional encoding shape or range
Signal. A sinusoidal buffer shaped (max_len, 1, d) added to (B, T, d) broadcasts silently when B == 1 or T == B, otherwise errors. Learned position ids beyond max_len trigger a device-side assert that looks like a random IndexError on long batches.
Fix. Store the buffer as (1, max_len, d), slice pe[:, :T], and truncate in the tokenizer (truncation=True, max_length=max_len).
Test.
assert x.size(1) <= max_len, "sequence longer than max_len"
assert (x + pe[:, :x.size(1)]).shape == x.shape
Bug 5: Weight decay on LayerNorm and biases
Signal. Decaying LayerNorm gains pulls them toward 0, shrinking activations and slowly hurting quality; excluding everything removes regularization.
Fix.
decay = [p for p in model.parameters() if p.ndim >= 2]
no_decay = [p for p in model.parameters() if p.ndim < 2]
opt = torch.optim.AdamW([{"params": decay, "weight_decay": 0.01},
{"params": no_decay, "weight_decay": 0.0}], lr=lr)
Test. The groups partition all parameters with no overlap, and every norm and bias parameter is in no_decay. (Embeddings are a judgment call; state your choice.)
Bug 6: Nondeterminism and leakage
Signals. Different results per run from unseeded workers, cudnn.benchmark=True, or nondeterministic atomics; identical shuffles each epoch when DistributedSampler.set_epoch is missing; leakage when splits depend on a shuffled seed or near-duplicates cross splits.
Fix.
seed_everything(s)
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True) # needs CUBLAS_WORKSPACE_CONFIG=:4096:8
g = torch.Generator().manual_seed(s)
DataLoader(ds, generator=g, worker_init_fn=lambda w: np.random.seed(s + w))
sampler.set_epoch(epoch)
Assign splits by hashing a stable example ID, and deduplicate before splitting.
Debugging plan, component by component
- Data. Decode a few batches back to text; verify truncation, PAD positions, and input/label alignment. Check split overlap by ID and by near-duplicate hash.
- Masks. Visualize mask tensors for a small batch; run the future-perturbation and pad-invariance tests.
- Positions. Assert max position id < table size; check shapes with
B != T. - Loss. Confirm
ignore_index, the shift, and that a random-init model starts nearlog(V). - Optimizer. Print parameter groups, LR per step, and effective batch size; confirm one scheduler step per optimizer step.
- AMP. Compare fp32 vs. AMP curves; track grad norm after unscale and the scaler scale; enable
torch.autograd.set_detect_anomalybriefly. - Determinism. Run twice with the same seed; expect identical losses for the first N steps, then bisect any divergence.
- DDP. Verify per-rank shards are disjoint,
set_epochis called, and only one rank logs or saves.
Sanity checks and verification
- Overfit 32 examples. Loss should approach 0 and exact-match should reach ~100%. Failure points to model, loss or mask bugs.
- Copy / reverse task. A tiny model should solve it within minutes; failure with a causal mask on points to mask polarity.
- Statistics. Per-layer activation and gradient norms; flag NaN/Inf with hooks.
- Metrics. Train and validation loss, token accuracy with PAD excluded, grad norm, LR, scaler scale, and throughput.
- Per-fix experiments. Apply one fix at a time and show the specific test turns from red to green, then confirm validation moves off chance on a small subset.
Common mistakes
- Fixing several things at once, so you cannot attribute the improvement.
- Trusting training loss alone without an autoregressive validation check.
- Using
-1e9fill values in fp16. - Forgetting the last partial accumulation window.