A packed sequence lets recurrent neural networks process variable-length sequences in batches without forcing every item into one equally sized tensor. PyTorch sorts sequences by length, processes active items together, and shrinks the effective batch as shorter sequences finish. section 4.3
A practical packed-sequence workflow is:
- Represent sequences with different lengths, such as names containing 3, 3, 4, 5, and 6 characters. section 4.3
- Pack them so the recurrent layer processes all five items initially, then continues with only sequences that still have remaining time steps. section 4.3
- Wrap nn.Embedding when necessary: unpack with pad_packed_sequence, embed the padded tensor, then repack with pack_padded_sequence. section 4.3.2
Figure 4.13 Example of packing a batch of five items with sequence lengths of 3, 3, 4, 5, and 6. For the first three steps, we process all five sequences. On the fourth step t = 4, two of the sequences have run out, so we drop them and continue the batch on only the sequences that have a length ≥ 4. Packing organizes the data by length to make this fast and efficient.
The figure makes the shrinking batch visible across time steps, showing why packing avoids wasted recurrent computation on completed sequences. section 4.3
