CD0015 Debug Left-Padded LM Loss

Mode A · Bug Hunt 30 Min PyTorch 2.x 4 Silent Bugs

On an OpenAI supervised fine-tuning pipeline, the data collator left-pads variable-length chat transcripts because the same batching code also feeds batched generation, where left padding keeps every row’s newest token in the last column. A teammate’s loss function written on top of those batches never crashes; a unit test that scores a single unpadded sequence against a hand-written reference matches to six decimal places.

On real batches, three anomalies show up in the training telemetry:
(1) Perplexity on padded batches is dramatically lower than when the same sequences are scored one at a time, and per-position dumps show padding tokens among the scored targets.
(2) Re-padding the identical validation rows to a longer max_len changes the reported loss.
(3) On the longest rows of a batch, the opening real tokens never appear among the scored targets.

Trace the label-construction and loss-reduction lines below. Identify the 4 silent bugs, explain how each one interacts with left padding, and patch the function in place. Then write a verification test proving the loss is identical whether the same sequences are left-padded, right-padded, or unpadded.

Code Under Review (38 Lines):

01  import torch
02  import torch.nn.functional as F
03
04
05  def causal_lm_loss(logits: torch.Tensor,
06                     input_ids: torch.Tensor,
07                     attention_mask: torch.Tensor) -> torch.Tensor:
08      """Mean next-token NLL over real (context, target) token pairs.
09
10      logits:         (B, T, V) model outputs for input_ids
11      input_ids:      (B, T) left-padded token ids, each row starts with BOS
12      attention_mask: (B, T) 1 = real token, 0 = padding
13      Contract: the same sequences give the same loss under any padding.
14      """
15      B, T, V = logits.shape
16      real = attention_mask.bool()  # (B, T)
17
18      # trim leading columns that are padding in every row
19      n_lead = int(real.any(dim=0).int().argmax())
20      n_lead = (n_lead + 7) // 8 * 8  # trim in multiples of 8 for tensor cores
21      logits = logits[:, n_lead:]  # (B, T', V)
22      real = real[:, n_lead:]  # (B, T')
23      labels = input_ids[:, n_lead:].clone()  # (B, T')
24      labels[:, 0] = -100  # BOS has no left context
25
26      # next-token shift: slot t predicts token t + 1
27      logits = logits[:, :-1]  # (B, T'-1, V)
28      labels = labels[:, 1:]  # (B, T'-1)
29
30      nll = F.cross_entropy(
31          logits.reshape(-1, V).float(),
32          labels.reshape(-1),
33          reduction="sum",
34      )
35
36      # average over every next-token slot in the batch
37      denom = B * (T - 1)
38      return nll / denom
A left-padded batch of three rows with real lengths 11, 7 and 4 laid out over 14 columns, showing pad cells, a BOS cell and content tokens; below it the padding-invariance contract and three symptom boxes: low padded perplexity, a loss that moves with max_len, and opening tokens of the longest rows never scored

Figure 1: A left-padded batch as the collator emits it, the padding-invariance contract the loss must honor, and the three symptoms observed in training telemetry.

Interactive PyTorch Workspace: Switch to the split-screen workspace to hunt the 4 silent bugs in the live editor and run the padding-invariance checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Trim Contract: Compare the promise in the comment on line 18 with the number of columns actually removed, using the row that has the least padding.
(2) Label Contract: List which label slots should be prediction targets, then check whether anything in the function marks the other slots so cross-entropy skips them.
(3) Column Assumptions: Any hard-coded column index is a left-padding red flag. Ask where each row’s BOS actually sits after the trim and after the shift.
(4) Reduction Contract: The docstring promises a mean over real pairs. Check what the divisor counts and whether it depends on T.

2Visual Review Map (Figure 2)
Review map of the loss function: five stages in order (leading-column trim, label construction, next-token shift, cross-entropy call, reduction divisor), each marked with the same question mark and an open question beneath it

Figure 2: The five stages a strong candidate walks aloud. Every stage carries the same question mark, so answer each open question before deciding which lines to edit.

3Interviewer Nudge & Line Focus

Trace one concrete batch (real lengths 21, 14, 9 and 5, left-padded to T = 24) and answer each Socratic check before editing:

Label Contract: After line 23, what value sits in a label slot whose token is padding, and does F.cross_entropy treat that value as a class to predict or as a slot to skip?
Trim Stage: Line 18 promises to remove only columns that are padding in every row. With 3, 10, 15 and 19 leading pads, how many columns do lines 19-20 remove, and where does the longest row’s BOS end up?
BOS Target: Line 24 writes into column 0 before the shift on line 28. Which (context, target) pair does that write remove after the shift, and which pair is left behind for a row whose BOS sits in column 10?
Reduction Divisor: Re-pad the same four rows from T = 24 to T = 32. Which of nll and denom changes, and which one should?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *