Sub topic 8
Batching and Collation
Assume you know basic Python classes and iterators, NumPy array shapes, and PyTorch tensors, Dataset, and DataLoader. This chapter focuses on how individual image samples become a batch.
Why collation matters
A model usually expects one tensor with shape:
(batch, channels, height, width)A dataset usually returns one sample at a time:
(channels, height, width)The DataLoader collects several samples and passes them to a collation function. Collation means combining separate samples into one batch.
For fixed-size images, PyTorch's default collation is usually enough. It stacks tensors along a new first dimension:
| Samples | Batch |
|---|---|
| 4 tensors shaped `(3, 224, 224)` | One tensor shaped `(4, 3, 224, 224)` |
The samples must have compatible shapes. If one image is (3, 224, 224) and another is (3, 300, 400), default collation cannot stack them.
Fixed-size images
Resize images before they reach the DataLoader when the model requires a fixed input shape. The default collation function can then stack the samples without extra code.
For example, a batch of 64 RGB images resized to 224 by 224 contains:
(64, 3, 224, 224)Keep the sample representation consistent. Returning NumPy arrays, tensors, and differently shaped labels from different dataset branches can cause collation errors or unexpected conversions.
Variable-size images
Some tasks should preserve the original image size. Object detection, instance segmentation, and some vision transformers may accept variable dimensions. In that case, write a custom collate_fn.
Padding adds empty pixels so every sample in a batch has the largest height and width in that batch. The function should also return the original sizes. Later model code can use those sizes to ignore padded regions.
import torch
from torch.utils.data import Dataset, DataLoader
class VariableImageDataset(Dataset):
def __init__(self):
self.shapes = [(3, 120, 160), (3, 96, 200), (3, 140, 128)]
def __len__(self):
return len(self.shapes)
def __getitem__(self, index):
return torch.randint(0, 256, self.shapes[index], dtype=torch.uint8)
def pad_collate(images):
height = max(image.shape[1] for image in images)
width = max(image.shape[2] for image in images)
batch = torch.zeros(
len(images), 3, height, width, dtype=images[0].dtype
)
sizes = torch.tensor(
[[image.shape[1], image.shape[2]] for image in images]
)
for index, image in enumerate(images):
h, w = image.shape[1:]
batch[index, :, :h, :w] = image
return batch, sizes
loader = DataLoader(
VariableImageDataset(),
batch_size=3,
collate_fn=pad_collate,
)
batch, sizes = next(iter(loader))
print(batch.shape) # torch.Size([3, 3, 140, 200])
print(sizes) # original height and width of each imagePadding and batching choices
Padding is simple, but excessive padding wastes memory and computation. If image sizes vary widely, group images with similar dimensions into the same batch. This practice is called bucketing.
Alternatively, resize or crop every image to a fixed shape. This improves throughput, but can distort objects or remove important content. Choose based on the model's accuracy requirements.
Exercise
A batch contains images sized 3×100×120 and 3×150×80. What padded batch shape does a channel-first collate function produce, and what metadata should it return?
Show answer
It produces (2, 3, 150, 120). It should return the original sizes [(100, 120), (150, 80)] so later code can distinguish image data from padding.