Sub topic 1
Where an image goes: the stages of a vision pipeline
An image takes a long path before a model sees it. It starts as a compressed file on disk and ends as a normalised floating-point tensor in GPU memory. Every step on that path costs time, and the model's speed does not fix a slow step. This chapter names the stages, shows what data looks like at each one, and explains why the order matters. Later chapters cover measuring and optimising each stage.
Prerequisites
This chapter assumes you have:
- Basic Python, including classes and iterators.
- Familiarity with NumPy arrays and image tensors laid out as height, width, channels.
- Basic PyTorch: tensors,
Dataset, andDataLoader. - Some awareness of image formats such as JPEG and PNG.
You do not need a GPU to run the code here. The example runs on the CPU and creates its own test image.
The pipeline as a chain of stages
A vision input pipeline turns a file path into a batch the model can consume. Training and inference both use it. The stages are the same in both cases, though training adds random augmentation.
The first five stages normally run on the CPU, in worker processes. The last stages run on the accelerator, so the pipeline crosses a hardware boundary partway through. Where you put that boundary is one of the main design choices.
What each stage does
Each stage has its own input, output, and cost driver. The cost driver matters because it tells you which change will help.
| Stage | Input | Output | Main cost driver |
|---|---|---|---|
| Read bytes | Path | Compressed bytes in memory | Disk or network throughput, file size |
| Decode | Compressed bytes | Pixel array, uint8, H x W x 3 | Pixel count, format, codec |
| Resize and crop | Full-size pixels | Fixed-size pixels | Source pixel count, interpolation method |
| To tensor | Pixel array | Tensor, 3 x H x W | Memory copies, data type |
| Collate | List of tensors | One batched tensor | Batch size, memory allocation |
| Copy to GPU | Host tensor | Device tensor | Bytes moved, pinned or pageable memory |
| Normalise | uint8 batch | float32 batch | Element count, device used |
Read bytes
Reading moves the compressed file from storage into memory. A typical photo JPEG is a few hundred kilobytes. Reading is rarely the problem on a local SSD. It can dominate on network storage, on a spinning disk, or with millions of small files, where per-file overhead outweighs transfer time.
Decode
Decoding turns compressed bytes into a pixel array. JPEG decoding is real computation: it undoes entropy coding, applies an inverse discrete cosine transform per block, and converts colour space. Its cost grows with the number of pixels in the source image, not with the size you want in the end. A 4000 x 3000 photo costs about the same to decode whether you want a 224 x 224 result or a 1024 x 1024 one.
Resize and crop
Models usually need a fixed input size. Resizing computes each output pixel from several input pixels. The method (nearest, bilinear, bicubic, area averaging) changes both the cost and the result. When shrinking by a large factor, a method without antialiasing can skip pixels and produce aliasing artefacts. Different libraries also implement the same-named method differently, which becomes a correctness problem when you move work between libraries.
To tensor
Conversion wraps or copies the pixel array as a tensor and reorders axes from height, width, channels (the layout most image libraries use) to channels, height, width (the layout most PyTorch models expect). The reorder is often a view and costs nothing, but a later operation may force a copy.
Collate
The DataLoader gathers several samples and stacks them into one tensor with a leading batch dimension. This needs every sample to have the same shape, or a custom collate function that handles the difference.
Copy to GPU
The batch moves across the bus between host memory and device memory. The cost is bytes divided by bandwidth, so the data type you send matters a great deal.
Normalise
Normalisation subtracts a per-channel mean and divides by a per-channel standard deviation. It is element-wise arithmetic that is cheap on a GPU and relatively expensive on a busy CPU.
Data size changes at every stage
The same image takes very different amounts of memory as it moves along. This explains most optimisation advice, so it is worth seeing the numbers. The following script builds a synthetic JPEG, pushes it through the stages, and prints the size at each one.
import io
import numpy as np
import torch
from PIL import Image
# Build a synthetic 640 x 480 JPEG so the example needs no files on disk.
rng = np.random.default_rng(0)
pixels = rng.integers(0, 256, size=(480, 640, 3), dtype=np.uint8)
buf = io.BytesIO()
Image.fromarray(pixels).save(buf, format="JPEG", quality=90)
data = buf.getvalue()
print(f"1. compressed file : {len(data):>9,} bytes")
# Decode: compressed bytes -> pixels.
im = Image.open(io.BytesIO(data)).convert("RGB")
decoded = np.asarray(im)
print(f"2. decoded uint8 : {decoded.nbytes:>9,} bytes, shape {decoded.shape}")
# Resize to the model's input size.
small = im.resize((224, 224), Image.Resampling.BILINEAR)
arr = np.array(small, dtype=np.uint8) # np.array copies, so the result is writable
print(f"3. resized uint8 : {arr.nbytes:>9,} bytes, shape {arr.shape}")
# To tensor: H x W x C -> C x H x W, still uint8.
t = torch.from_numpy(arr).permute(2, 0, 1)
batch = torch.stack([t, t, t, t]) # collate four samples
print(f"4. batch uint8 : {batch.numel() * batch.element_size():>9,} bytes, "
f"shape {tuple(batch.shape)}")
# Normalise in float32.
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) * 255
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1) * 255
x = (batch.float() - mean) / std
print(f"5. batch float32 : {x.numel() * x.element_size():>9,} bytes, "
f"dtype {x.dtype}")The compressed size depends on the content and quality setting, so the first number will vary. The other numbers are fixed by the shapes. The decoded image is 921,600 bytes. The resized image is 150,528 bytes. The batch of four is 602,112 bytes as uint8 and 2,408,448 bytes as float32. Converting to float32 multiplies the volume by four, which is why the order of operations (a later chapter) pushes that conversion as late as possible.
Where the stages run
A DataLoader with num_workers set above zero runs the dataset's __getitem__ in separate worker processes. That covers reading, decoding, resizing, and conversion to a tensor. Each worker then sends its finished sample to the main process, which collates it (or the worker collates it, depending on the setup) and copies the batch to the GPU. The main process also runs the training loop, so any work left to it competes with the loop for the Python interpreter.
This gives two rules of thumb for where each stage belongs:
- Work that is variable in cost and CPU-bound, such as decoding, goes in the workers so that it overlaps with GPU compute.
- Work that is the same for every element and cheap on a GPU, such as normalisation, is a candidate to move to the device.
With num_workers=0, everything runs serially in the main process. The GPU then sits idle while the CPU decodes the next batch, and the CPU sits idle while the GPU computes. Overlapping the two is the central goal of the optimisations in this tutorial.
Throughput is set by the slowest stage
Stages that run in parallel and feed each other behave like a production line. The rate of the whole line is the rate of its slowest stage. If decoding yields 400 images per second across all workers and the GPU can process 1,200, the pipeline delivers 400, and making the model faster changes nothing.
This has two consequences:
- Optimising a stage that is not the bottleneck gives no gain. Halving resize time does nothing if decoding is the limit.
- Once you fix the bottleneck, the next stage becomes the limit. You repeat until the GPU is the slowest component, which is the goal. At that point you have a compute-bound job rather than an input-bound one.
The next chapter shows how to measure each stage so you know which one is the bottleneck before you change anything.
Training and inference differ in the details
The stage list is the same in both modes, but the settings differ:
- Training shuffles samples, applies random augmentation (random crops, flips, colour jitter), and favours throughput. Randomness means a given image yields a different tensor on each epoch.
- Inference uses a deterministic path, with a fixed resize and centre crop, and often cares more about latency for a single image than throughput for many.
Keep the deterministic path identical between training-time validation and deployment. Differences in resize method, crop policy, or normalisation constants between those two are a common source of accuracy loss that is hard to trace.
Common mistakes at this level
- Assuming the model is the slow part. Without measurement, teams often buy faster GPUs for a job that is limited by JPEG decoding.
- Normalising early on the CPU. Converting to float32 before the copy to the GPU quadruples the bytes in every later step.
- Forgetting that decode cost follows source size. Shrinking the target size does not make decoding faster by itself.
- Mixing libraries without checking. Two libraries can give different pixels for the same resize call.
Exercise
A pipeline decodes 3000 x 4000 JPEGs and resizes them to 224 x 224. Using the sizes from this chapter, how many bytes does one decoded image occupy as uint8 RGB, how many does one resized image occupy, and why does shrinking the target to 112 x 112 not make decoding faster?
Show answer
One decoded image is 3000 x 4000 x 3 = 36,000,000 bytes. One resized 224 x 224 image is 224 x 224 x 3 = 150,528 bytes. Decoding must reconstruct every pixel of the source image before any resize happens, so its cost follows the source pixel count (12 million pixels), not the target size. Shrinking the target to 112 x 112 only reduces the later resize work and the data moved afterwards.
Exercise
Name the stage at which a uint8 batch should be converted to float32 to keep transfer volume low, and say by what factor converting earlier would increase the bytes copied to the GPU.
Show answer
Convert on the GPU, after the copy. Converting on the CPU before the copy sends float32 values, which take 4 bytes each instead of 1, so the transfer carries four times as many bytes.