PyTorch DataLoader collate_fn: Pad Variable-Length Sequences
Use PyTorch DataLoader, collate_fn and pad_sequence to batch variable-length text. Trace token shapes, class labels and a padding mask in a runnable example.
Pass a custom collate_fn to DataLoader when your dataset returns sequences of different lengths. Inside that function, split each batch into sequences and labels, use pad_sequence(..., batch_first=True) to pad the sequences to the longest item in that batch, and return the labels in the same order. If the model needs a padding mask, build it from the original sequence lengths so you can distinguish padding from real tokens.
Why default collation fails on variable-length tensors
A dataset can return each example as a one-dimensional token tensor and one integer class label. DataLoader fetches a list of these examples when automatic batching is enabled. Default collation tries to stack the corresponding tensors along a new batch dimension. With sequences of lengths 3, 1, and 2, that stack fails because the tensors have different sizes.
The custom collate function runs after DataLoader has selected the examples for a batch. That lets you pad only to the longest sequence in this group. Class labels are one value per example, so they go into a one-dimensional tensor in the original batch order.
Source: PyTorch DataLoader: Automatic batching and collate_fn ↗
Work through a three-row padded batch
Suppose a text classifier receives three token lists with class labels 2, 1, and 0. The longest list has three tokens, so batch-first padding gives a token tensor of shape [3, 3]. The labels have shape [3]. The second row is extended by two positions, and the third by one. Every padded position lies after the last real token in its row.
The first sequence contains a real token with ID 0. That means tokens == 0 would mark this real token as padding as well. A length-based mask marks only the positions added by padding. The assertions check the rows, labels, and mask together so an accidental reorder or false mask entry is visible.
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
def collate_text(batch):
sequences, labels = zip(*batch)
lengths = torch.tensor([len(seq) for seq in sequences])
tokens = pad_sequence(sequences, batch_first=True, padding_value=0)
positions = torch.arange(tokens.size(1))
padding_mask = positions[None, :] >= lengths[:, None]
return tokens, torch.tensor(labels, dtype=torch.long), padding_mask
examples = [
(torch.tensor([9, 0, 4]), 2),
(torch.tensor([6]), 1),
(torch.tensor([3, 8]), 0),
]
tokens, labels, padding_mask = next(iter(
DataLoader(examples, batch_size=3, shuffle=False, collate_fn=collate_text)
))
assert tokens.tolist() == [[9, 0, 4], [6, 0, 0], [3, 8, 0]]
assert labels.tolist() == [2, 1, 0]
assert padding_mask.tolist() == [
[False, False, False], [False, True, True], [False, False, True]
]Source: PyTorch pad_sequence: Layout, padding value, and padding side ↗
Check shapes on a non-square batch
The three-row example produces a square tensor, so its shape alone cannot reveal a swapped batch and time axis. Change batch_size to 2 and inspect the first batch. Its two examples have lengths 3 and 1. With batch_first=True, the token shape should now be [2, 3]. With the default layout of pad_sequence, those axes would be reversed. The labels should still contain [2, 1].
This example uses right padding. If you change to left padding, the length comparison must mark positions at the start of each row instead. Before passing the mask to a model, check what True means for that API. For example, a Boolean key_padding_mask in PyTorch MultiheadAttention treats True as an ignored key position.
Source: PyTorch MultiheadAttention: Boolean key padding masks ↗
Predict the batch before you run the code
In a code-reading question, write down the number of examples and their lengths first. Then trace the padded token rows and the label order separately. If the code calls pad_sequence without batch_first=True, check the axis convention before deciding what any printed shape means.
Try the free PTCA sample below in Study mode. Its data-handling question asks you to follow a custom collate function and predict what the padded batch and class targets will print. Work out the result before checking the explanation.
Your next steps
- Use a custom collate_fn when example tensors need batch-dependent padding.
- With batch_first=True, read the padded token dimensions as batch size by maximum sequence length.
- Build right-padding masks from lengths and confirm the model’s mask convention.
Sources & official resources
Linked resources checked on 2026-11-25. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →