Sub topic 1
Where an Image Goes: The Stages of a Vision Pipeline
Prerequisites
You should know basic Python, NumPy array shapes, and PyTorch Dataset and DataLoader objects. You should also know that an image can be represented as height × width × channels, or as channels × height × width in PyTorch.
The pipeline from disk to model
A vision input pipeline turns stored image files into model inputs. Each image usually passes through these stages:
- Read: The operating system reads compressed bytes from storage.
- Decode: An image library turns bytes such as JPEG data into pixel values.
- Resize: The image is changed to the spatial size expected by the model.
- Transform: The pipeline may crop, flip, rotate, or change colors.
- Collate: Individual samples are combined into a batch tensor.
- Transfer: The batch moves from host memory, usually system RAM, to device memory on a GPU.
- Normalise: Pixel values are converted to the numeric range and distribution expected by the model.
The stages can run on different resources. Reading, decoding, and resizing commonly use CPU time. Batch computation uses the GPU. If the CPU cannot prepare batches fast enough, the GPU waits. If the GPU is busy and the CPU has idle time, adding workers will not improve throughput.
Why stage boundaries matter
An image file is normally compressed. JPEG compression stores a compact representation, not a ready-to-use pixel matrix. Decoding reconstructs every pixel, so a small file can still require substantial CPU work. PNG decoding can also be expensive, especially for large images.
Resizing reads and writes many pixels. Its cost depends on the source and target dimensions and on the interpolation method. Bilinear interpolation uses nearby pixels and is usually faster than higher-quality methods. The best choice depends on the model and the accuracy required.
After preprocessing, samples must have compatible shapes before they can form a regular tensor. For example, four images shaped (3, 224, 224) can become one batch shaped (4, 3, 224, 224). Images with different dimensions need resizing, padding, or a custom collation strategy.
| Stage | Typical resource | Common symptom when slow |
|---|---|---|
| Decode | CPU | Workers use high CPU and the GPU is idle |
| Resize | CPU | Larger source images reduce samples per second |
| Transfer | PCIe or device link | CPU batches are ready but copies take time |
| Model computation | GPU | GPU utilisation stays high |
Measure before optimising
Measure each stage separately instead of assuming that storage or GPU transfer is the bottleneck. This example reports average read, decode, and resize times for image paths passed on the command line.
import io
import sys
import time
from PIL import Image
def measure(paths, size=(224, 224)):
totals = [0.0, 0.0, 0.0]
for path in paths:
start = time.perf_counter()
with open(path, "rb") as file:
data = file.read()
after_read = time.perf_counter()
with Image.open(io.BytesIO(data)) as image:
image = image.convert("RGB")
after_decode = time.perf_counter()
image.resize(size, Image.Resampling.BILINEAR)
after_resize = time.perf_counter()
totals[0] += after_read - start
totals[1] += after_decode - after_read
totals[2] += after_resize - after_decode
count = len(paths)
for name, total in zip(("read", "decode", "resize"), totals):
print(f"{name}: {total / count * 1000:.2f} ms/image")
if __name__ == "__main__":
if len(sys.argv) < 2:
raise SystemExit("Usage: python measure.py IMAGE ...")
measure(sys.argv[1:])Run the script on a representative sample. Include images with the same variety of formats, dimensions, and storage locations as the real workload. Then measure complete pipeline throughput in images per second. Per-stage timings explain where time goes; throughput shows whether the full system improved.
A working mental model
Think of the pipeline as a sequence of queues. Storage feeds decoding, decoding feeds transforms, transforms feed collation, and collation feeds the device. Worker processes can prepare several future batches while the model processes the current one. The goal is not to minimise every individual operation. The goal is to keep the model supplied with correct batches without wasting CPU, memory, or transfer bandwidth.
Exercise
A training run shows low GPU utilisation while all data-loader workers use one CPU core heavily. Which pipeline stages should you measure first, and why?
Show answer
Measure decoding and resizing first. They run for every image and can prevent complete batches from reaching the GPU. Also measure batch transfer to confirm that the delay is not caused by host-to-device copies.