Sequence masking and teacher forcing
Quick answer
Variable-length sequences need padding and masking for batches. In sequence-to-sequence learning, an encoder reads source tokens and a decoder emits target tokens. Teacher forcing supplies the previous true target during training, but inference must use previously generated tokens. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Teacher forcing shift
Expected output (locally tested): [1, 4, 7] [4, 7, 2]. The current prediction label is one step ahead of its decoder input.
How it works
Right-pad to a common length and construct a valid mask where time index is less than the actual length. Never infer padding solely from numeric zero when zero is a valid token. pack_padded_sequence accepts positive CPU lengths, and enforce_sorted=False permits unsorted batches. Packing avoids recurrent transitions on padding; a masked loss separately excludes invalid target positions. For token loss, divide by the number of valid targets, not padded batch size; reject batches with no valid targets or define an explicit skip policy. For sequence-to-sequence training with target [A,B,EOS], decoder inputs are [BOS,A,B]. At position t the decoder predicts the current target using source and earlier targets only. During autoregressive inference, start with BOS, feed back predictions, stop at EOS or a stated maximum length. Teacher-forced token accuracy does not measure free-running generation; evaluate that separately. Bidirectional encoders can read the complete available source, but a bidirectional decoder over future targets leaks information. Split by complete sequence or originating entity before creating overlapping windows. The milestone is a sequence recall classification task, not full translation.
Pack variable length sequences
import torchfrom torch.nn.utils.rnn import pack_padded_sequencex=torch.tensor([[[1.],[2.],[99.]],[[3.],[4.],[5.]]])p=pack_padded_sequence(x,[2,3],batch_first=True,enforce_sorted=False)print(p.batch_sizes.tolist(),sorted(p.data.flatten().tolist()))Expected output (locally tested): [2, 2, 1] [1.0, 2.0, 3.0, 4.0, 5.0]. The padding sentinel 99 is excluded from the packed sequence.
Common mistakes
Do not feed the current target into its own prediction step. Do not count padded positions in accuracy or treat padding as valid history. Do not shuffle individual overlapping windows across partitions.
Practice and next steps
Build shifted decoder inputs, count valid target tokens, and check that arbitrary padding values do not change packed states.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sequence masking and teacher forcing — knowledge check
Apply sequence masking and teacher forcing to small examples and debugging scenarios.
What is the decoder input for target [A,B,EOS]?
Why use explicit lengths?
What does packed recurrence exclude?
What should inference feed to the next decoder step?
What is the split unit for overlapping windows?