Sub topic 11
Variable-size images: padding, bucketing, and resizing policy
This chapter assumes you know basic PyTorch (Dataset, DataLoader, tensors), can read a 3 x H x W tensor shape, and have seen the collate_fn idea from the batching chapter. Here you will handle datasets whose images do not share one size.
Why variable sizes break batching
A batch is a single tensor, so every image in it needs the same height and width. The default collate function calls torch.stack, which raises an error when shapes differ:
import torch
a = torch.zeros(3, 480, 640, dtype=torch.uint8)
b = torch.zeros(3, 375, 500, dtype=torch.uint8)
try:
torch.stack([a, b])
except RuntimeError as e:
print("stack failed:", e)You have three policies for fixing this. Each trades accuracy, compute, and code complexity differently.
| Policy | What it does | Main cost |
|---|---|---|
| Resize everything | Scales each image to one fixed size | Distorts aspect ratio or discards content |
| Pad to the batch maximum | Places each image in a larger zero canvas | Wasted compute on padding pixels |
| Bucket by size | Groups similar-sized images into the same batch | More complex sampler, less random batches |
These can be combined. A common recipe is to resize to a size range, then bucket, then pad the small remainder.
Policy 1: a fixed resizing policy
Resizing to a fixed square size is the simplest option and is what most classification pipelines use. The question is how to treat the aspect ratio (width divided by height).
- Stretch. Resize directly to
(H, W). A 640x480 photo becomes 224x224, so objects look squashed. The model learns on distorted shapes, and it must see the same distortion at inference time. - Resize then center crop. Scale the short side to the target, then crop the middle. No distortion, but you lose the edges. This is the usual evaluation recipe for ImageNet-style models.
- Letterbox. Scale the long side to the target and pad the short side. No distortion and no lost content, but padding pixels enter the model.
The choice is part of the model's contract. If the model was trained with center crops, feeding it stretched images at inference changes the accuracy. Pick one policy and use it in both training and serving.
The letterbox function below keeps uint8 data and returns the scale and offsets, so you can map predictions such as bounding boxes back to the original image.
import numpy as np
from PIL import Image
def letterbox(im, size=(224, 224), fill=0):
"""Scale to fit inside size, pad the rest. Returns array, scale, (top, left)."""
th, tw = size
w, h = im.size
scale = min(tw / w, th / h)
nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
im = im.resize((nw, nh), Image.Resampling.BILINEAR)
canvas = np.full((th, tw, 3), fill, dtype=np.uint8)
top, left = (th - nh) // 2, (tw - nw) // 2
canvas[top:top + nh, left:left + nw] = np.asarray(im.convert("RGB"))
return canvas, scale, (top, left)
if __name__ == "__main__":
img = Image.new("RGB", (640, 480), (200, 50, 50))
out, scale, offset = letterbox(img)
print(out.shape, scale, offset) # (224, 224, 3) 0.35 (28, 0)Policy 2: padding inside the batch
Many tasks cannot discard pixels or change the scale freely. Detection, segmentation, and OCR often need images near their native resolution. For these, pad each batch to its largest image with the pad_collate function from the code examples:
import torch
def pad_collate(images):
# images: list of uint8 tensors, each 3 x H_i x W_i
h = max(im.shape[1] for im in images)
w = max(im.shape[2] for im in images)
batch = torch.zeros(len(images), 3, h, w, dtype=images[0].dtype)
sizes = torch.tensor([[im.shape[1], im.shape[2]] for im in images])
for k, im in enumerate(images):
batch[k, :, : im.shape[1], : im.shape[2]] = im
return batch, sizesThe function returns sizes alongside the batch. You need them for three reasons:
- Masks. Build a boolean mask that is true on real pixels. Transformer-based detectors use it to block attention to padding.
- Losses. Segmentation loss should skip padded positions, for example by labelling them with an ignore index.
- Coordinates. Predictions on a padded canvas must be mapped back to each original image.
Padding with zeros has a subtlety. If you normalise on the GPU after padding, the padded zeros become (0 - mean) / std, which is not zero. Either normalise before padding, or pad with the mean colour, or apply the mask afterwards. Pick one and keep it consistent between training and inference.
Padding also has a cost. Convolutions run over padded pixels as if they were real. If one image in a batch of 64 is 1000x1000 and the others are 300x300, the batch is padded to 1000x1000, and most of the compute is wasted. That motivates bucketing.
Policy 3: bucketing by size
Bucketing groups images of similar shape into the same batch, so each batch needs little padding. You sort or group by size, then shuffle at the batch level instead of the image level.
The waste can be measured. Define the padding overhead of a batch as the fraction of its pixels that are padding:
def padding_overhead(sizes):
"""sizes: list of (h, w). Returns the fraction of padded pixels in the batch."""
H = max(h for h, _ in sizes)
W = max(w for _, w in sizes)
real = sum(h * w for h, w in sizes)
return 1 - real / (len(sizes) * H * W)
print(padding_overhead([(1000, 1000), (300, 300), (300, 300), (300, 300)]))
# about 0.72A batch sampler can then build batches from images grouped by size. The version below sorts indices within random chunks. That keeps some randomness while limiting overhead.
import random
from torch.utils.data import Sampler
class BucketBatchSampler(Sampler):
def __init__(self, sizes, batch_size, chunk_factor=50, seed=0):
# sizes: list of (h, w) per dataset index
self.sizes = sizes
self.batch_size = batch_size
self.chunk = batch_size * chunk_factor
self.seed = seed
self.epoch = 0
def set_epoch(self, epoch):
self.epoch = epoch
def __iter__(self):
rng = random.Random(self.seed + self.epoch)
idx = list(range(len(self.sizes)))
rng.shuffle(idx)
batches = []
for s in range(0, len(idx), self.chunk):
chunk = sorted(idx[s:s + self.chunk],
key=lambda i: self.sizes[i][0] * self.sizes[i][1])
for b in range(0, len(chunk), self.batch_size):
batches.append(chunk[b:b + self.batch_size])
rng.shuffle(batches)
return iter(batches)
def __len__(self):
return (len(self.sizes) + self.batch_size - 1) // self.batch_sizeUse it through the batch_sampler argument, which replaces batch_size, shuffle, and drop_last:
loader = DataLoader(dataset, batch_sampler=BucketBatchSampler(sizes, 32),
collate_fn=pad_collate, num_workers=4)The chunk factor sets the trade-off. A small chunk gives random batches with more padding. A large chunk gives tight batches that are less random. Sorting the whole dataset by size is the extreme case, and it is risky for training because every batch in a stretch has similar content statistics. You can also sort by aspect ratio, since many datasets have two or three common ratios.
To get the sizes without decoding every image, read only the file header. Image.open reads the header lazily, so im.size is cheap:
from PIL import Image
def read_sizes(paths):
sizes = []
for p in paths:
with Image.open(p) as im:
sizes.append((im.height, im.width))
return sizesCompute this once and cache it, since opening thousands of files still costs disk reads.
Edge cases and common errors
- Bucketing changes training dynamics. Batches become correlated by image size, and size often correlates with content (for example, scans versus phone photos). Keep the chunk large enough to mix sources, and watch the loss curve for periodic patterns.
- Batch norm sees padding. Batch normalisation statistics include padded pixels. Heavy padding skews the statistics. Prefer group or layer normalisation, or keep overhead low through bucketing.
- Memory spikes. Memory scales with the largest batch. A single bucket of large images can cause an out-of-memory error late in an epoch. Cap the maximum image size by downscaling anything over a limit, or set a token or pixel budget per batch instead of a fixed count.
- Unstable shapes slow some backends. Compilers and cuDNN autotuning (
torch.backends.cudnn.benchmark = True) re-tune for each new input shape. With fully free sizes, this can slow things down. Round sizes up to a multiple such as 32, or use a small set of shapes. - Mismatched policy at inference. Training with letterbox and serving with stretch is a common source of silent accuracy loss.
- Shared worker state in the sampler. The sampler runs in the main process, so its random state is separate from the workers. Seed it explicitly, and call
set_epocheach epoch, as in the example, for reproducible shuffles.
Choosing between policies
Start from the model's requirements, not the pipeline. For image classification with a pretrained backbone, resize and crop to the size it was trained on. For detection, segmentation, or document tasks, keep native or moderately downscaled resolution, bucket by size, and pad. Measure padding overhead with the function above on your own dataset. If it is under about 10 percent for random batches, bucketing adds complexity without much gain. If it is above 30 percent, bucketing usually pays for itself in throughput.
Exercise
A dataset has 1,000 images: 900 are 300x300 and 100 are 1000x1000. With random batches of 10 and pad-to-maximum, what is the expected padding overhead of a typical batch, and why does bucketing help? (Hint: the chance that a batch of 10 contains at least one large image is 1 - 0.9^10, about 65 percent.)
Show answer
A batch with one large image is padded to 1000x1000, so with nine small images the overhead is 1 - (1,000,000 + 9 x 90,000) / (10 x 1,000,000) = 1 - 0.181 = about 82 percent. About 65 percent of random batches contain at least one large image, so a large share of compute goes to padding. Bucketing puts the 100 large images into about 10 batches of their own, which have no padding, and the 900 small images into 90 batches that are also unpadded. Overhead drops to nearly zero, at the cost of less random batches.
Exercise
You train a detector with a letterbox policy and it predicts a box at (x1, y1) = (60, 40) on the 224x224 canvas. The original image is 640x480, so the scale is 0.35 and the offset is (top 28, left 0). What are the coordinates in the original image?
Show answer
Remove the offset, then divide by the scale. x = (60 - 0) / 0.35 = about 171.4 and y = (40 - 28) / 0.35 = about 34.3. Always subtract the padding offset before undoing the scale.