Sub topic 8
Batching and Collation
This chapter explains how a DataLoader turns individual samples into a batch. It covers the default collate function, what a custom one can do, and the mistakes that cost time or memory. It assumes you know basic PyTorch (Dataset, DataLoader, tensors), NumPy image arrays in height, width, channel order, and the worker-process setup from the previous chapter.
What collation does
A Dataset returns one sample at a time. The model wants a batch: one tensor with a leading batch dimension. Collation is the step that merges a list of samples into that batch. The DataLoader does it inside the worker process, after the workers have called __getitem__ once per index in the batch.
The data flow for one batch looks like this:
Two consequences follow:
- Collation runs in the workers, so its cost is parallelised along with decoding. A slow collate function is hidden only if you have enough workers.
- The batch crosses a process boundary. PyTorch sends tensors from workers to the main process through shared memory, so the size and number of tensors in a batch matter.
The default collate function
The default collate_fn (default_collate) looks at the type of the first sample and acts on it:
| Sample type | Result |
|---|---|
| Tensor | `torch.stack` along a new dimension 0 |
| NumPy array | Converted to a tensor, then stacked |
| Number | A 1-D tensor |
| Dict or tuple | Collated recursively, key by key or position by position |
| String | A list of strings |
The important rule is that torch.stack needs every tensor to have the same shape. If your dataset returns images of different sizes, the default collate raises an error such as stack expects each tensor to be equal size. For fixed-size pipelines (resize everything to 224 by 224 in __getitem__), the default is correct and fast. You do not need a custom function.
The default also preserves the dtype. If __getitem__ returns uint8, the batch is uint8. This matters for the next stages: a uint8 batch of 64 images at 224 by 224 is about 9.6 MB, while the same batch as float32 is about 38.5 MB. Keep samples as uint8 through collation and the inter-process copy, and convert later on the GPU.
Memory cost of a batch
The size of a batch in bytes is B × C × H × W × bytes_per_element. A quick helper makes the numbers concrete:
import torch
def batch_bytes(batch_size, height, width, channels=3, dtype=torch.uint8):
element = torch.empty((), dtype=dtype).element_size()
return batch_size * channels * height * width * element
for dtype in (torch.uint8, torch.float16, torch.float32):
mb = batch_bytes(64, 224, 224, dtype=dtype) / 1e6
print(f"{str(dtype):15s} {mb:6.1f} MB")This prints roughly 9.6 MB, 19.3 MB, and 38.5 MB. The main process can hold num_workers × prefetch_factor batches in flight at once. With 4 workers and a prefetch factor of 2, that is 8 batches, so the float32 choice costs about 308 MB of shared memory against 77 MB for uint8. At larger resolutions the difference decides whether training fits in the machine's shared memory (/dev/shm on Linux, which is small by default in some containers).
Writing a custom collate function
You need a custom collate_fn when the default stacking is wrong for your data. Typical reasons are variable-size images, extra per-sample fields such as masks or boxes with varying counts, or a wish to build the batch in a specific layout.
A collate function receives a list of whatever __getitem__ returned, and it returns the batch. This one pads images to the largest height and width in the batch and returns the original sizes, so the model or loss can ignore the padding:
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, sizesYou pass it with DataLoader(dataset, batch_size=32, collate_fn=pad_collate). Three details are easy to get wrong:
- Allocate once, then copy in. The function creates the output with
torch.zerosand fills slices. Building a list of padded tensors and then stacking them copies the data twice. - Keep the dtype. The code uses
images[0].dtype. Hard-codingtorch.float32would quadruple the batch size without anyone noticing. - Padding value. Zero is correct for
uint8data that you will normalise later only if the model treats padded area as background. If you normalise on the GPU after padding, padded pixels become-mean/stdrather than zero. Use the returnedsizesto mask them when it matters. The chapter on variable-size images covers the policy choices.
Samples that are not just images
Most real datasets return a label with each image. If __getitem__ returns (image, label), the default collate handles it: it stacks the images and turns the labels into a tensor. When the second item has variable length, such as a list of bounding boxes, the default fails or produces a surprising result. A custom function keeps the ragged part as a list:
import torch
def detection_collate(samples):
# samples: list of (image_tensor, boxes_tensor) pairs
images = torch.stack([img for img, _ in samples]) # fixed-size images
boxes = [b for _, b in samples] # each N_i x 4, ragged
return images, boxesThe batch is then a tensor and a list of tensors. Moving it to the GPU needs a loop over the list, which is a reason to prefer a padded tensor plus a count when boxes are numerous.
Where collation goes wrong
These problems come up repeatedly in practice.
- Collating in the main process. If
num_workers=0, collation, decoding, and training share one process, and nothing overlaps. Profile before blaming the collate function. - Per-sample Python loops. Collate functions that convert each sample with
torch.tensor(...)ornp.array(...)on already-converted data add overhead that grows with batch size. Convert once, in__getitem__. - Non-contiguous tensors. A
permutefrom HWC to CHW returns a view whose memory is not contiguous.torch.stackhandles it, but it forces a strided copy. This is fine for one copy, and a problem if you repeat the pattern in several places. - Unwritable NumPy arrays.
torch.from_numpyon a read-only array triggers a warning. Create the array withnp.array(im, dtype=np.uint8), which copies and returns a writable array. - Mixed dtypes inside a batch. If some samples are
uint8and othersfloat32,stackmay fail or silently promote. Fix the dtype in the dataset. - The last partial batch. With
drop_last=False, the final batch is smaller. This breaks code that assumes a fixed batch size, such as compiled graphs with static shapes or batch-norm statistics on a batch of one. Usedrop_last=Truefor training when it matters.
Batch-level shortcuts
Sometimes the cheapest approach is to avoid per-sample overhead altogether. Setting batch_size=None disables automatic batching, and the dataset then returns whole batches. Combined with an IterableDataset or a batch_sampler, this suits formats that read many records at once, such as sharded files. The cost is that you take over shuffling and per-batch assembly yourself.
For ordinary map-style datasets, stay with batch_size and let the loader handle indexing.
Checking your collate function
A collate function is small enough to test directly, without a loader or any files. Build fake samples of different sizes and check the output shape, dtype, and padding:
import torch
def test_pad_collate():
imgs = [
torch.full((3, 4, 6), 7, dtype=torch.uint8),
torch.full((3, 5, 3), 9, dtype=torch.uint8),
]
batch, sizes = pad_collate(imgs)
assert batch.shape == (2, 3, 5, 6)
assert batch.dtype == torch.uint8
assert sizes.tolist() == [[4, 6], [5, 3]]
assert batch[0, :, 4:, :].sum() == 0 # padded rows are zero
assert batch[1, :, :, 3:].sum() == 0 # padded columns are zero
assert (batch[0, :, :4, :6] == 7).all()
test_pad_collate()
print("ok")This test needs pad_collate from earlier in the chapter in the same file. Tests like this catch shape and dtype errors in seconds, before they appear as a crash in the third hour of a training run.
Summary of decisions
| Situation | Choice |
|---|---|
| All images resized to one size | Default collate, `uint8` samples |
| Variable-size images, model accepts padding | `pad_collate` with returned sizes |
| Ragged annotations such as boxes | Custom collate returning a tensor and a list |
| Batch shapes must be static | `drop_last=True` |
| Shared memory errors in a container | Smaller dtype, fewer workers or prefetch, or a larger `/dev/shm` |
Exercise
A training job uses 6 workers, prefetch_factor=2, a batch size of 128, and 3 x 256 x 256 images. How much shared memory do the in-flight batches need if samples are uint8, and how much if a dataset bug returns float32? What does this tell you about where to convert dtype?
Show answer
In-flight batches = 6 × 2 = 12. One uint8 batch = 128 × 3 × 256 × 256 = 25,165,824 bytes, about 25.2 MB, so 12 batches need about 302 MB. A float32 batch is four times larger, about 100.7 MB, so 12 batches need about 1.2 GB. This shows that you should keep samples as uint8 through collation and the worker-to-main-process copy, and convert to float on the GPU after the transfer.
Exercise
You write DataLoader(ds, batch_size=16, num_workers=4, collate_fn=lambda b: pad_collate(b)) and it fails on Windows with a pickling error. What is the cause and the fix?
Show answer
Windows starts worker processes by spawning, which pickles the arguments, including collatefn. A lambda cannot be pickled. Pass the module-level function directly: `collatefn=pad_collate`.