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
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.
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 .
2Visual Review Map (Figure 2)

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 ) and answer each Socratic check before editing:
F.cross_entropy treat that value as a class to predict or as a slot to skip?
nll and denom changes, and which one should?
Leave a Reply