Sub topic 2
Decoding at reduced size with JPEG draft mode
Decoding a JPEG is often the most expensive CPU step in a vision pipeline. A camera photo may be 4000 by 3000 pixels, while a model usually takes 224 by 224. Decoding the full image and then shrinking it wastes most of that work.
JPEG draft mode lets the decoder produce a smaller image directly. The decoder can scale by 1/2, 1/4, or 1/8 during decoding. Pillow exposes this through Image.draft(), which must be called before the pixels load.
from PIL import Image
def load_small(path, size=(224, 224)):
with Image.open(path) as im:
im.draft("RGB", (size[0] * 2, size[1] * 2))
im = im.convert("RGB")
return im.resize(size, Image.Resampling.BILINEAR)Draft mode keeps the result at least twice the target size, and the final resize sets the exact dimensions. For formats other than JPEG, draft() does nothing.
Operation order and data types
Keep images as uint8 for as long as possible. One uint8 value takes 1 byte, and one float32 value takes 4. Resize while the data is still uint8, and convert to float only on the GPU.
| Stage | Data type | Reason |
|---|---|---|
| Decode and resize | uint8 | 1 byte per value |
| Transfer to GPU | uint8 | 4 times fewer bytes than float32 |
| Normalise | float32 | Done on the GPU after transfer |
Parallel loading with workers
DataLoader calls __getitem__ in worker processes when num_workers is above 0. Workers decode and resize the next images while the GPU processes the current batch. prefetch_factor sets how many batches each worker prepares ahead. persistent_workers=True keeps workers alive between epochs, so they do not restart each time.
import numpy as np
import torch
from torch.utils.data import Dataset
class ImageDataset(Dataset):
def __init__(self, paths, size=(224, 224)):
self.paths = paths
self.size = size
def __len__(self):
return len(self.paths)
def __getitem__(self, i):
im = load_small(self.paths[i], self.size)
arr = np.array(im, dtype=np.uint8)
return torch.from_numpy(arr).permute(2, 0, 1)Batching and collation
The default collate function stacks same-shape tensors into one batch of shape (B, 3, H, W). Because every image is resized to the same size, the default collate works without a custom function. Larger batches use the GPU more efficiently but need more memory.
import glob
from torch.utils.data import DataLoader
if __name__ == "__main__":
paths = sorted(glob.glob("images/*.jpg"))
loader = DataLoader(
ImageDataset(paths),
batch_size=64,
shuffle=True,
num_workers=4,
pin_memory=True,
persistent_workers=True,
prefetch_factor=2,
)Moving batches to the GPU
pin_memory=True places batches in page-locked host memory, which allows asynchronous copies. Pass non_blocking=True to .to() to use that. Then convert to float and normalise on the GPU.
import torch
mean = torch.tensor([0.485, 0.456, 0.406], device="cuda").view(1, 3, 1, 1) * 255
std = torch.tensor([0.229, 0.224, 0.225], device="cuda").view(1, 3, 1, 1) * 255
for batch in loader:
x = batch.to("cuda", non_blocking=True).float()
x = (x - mean) / stdExercise
Why must im.draft() be called before the image pixels are loaded, and what happens when you call it on a PNG file?
Show answer
The decoder applies the scale while it reads the JPEG, so the call must come before decoding starts. On a PNG file, draft() does nothing, and the full image is decoded and then resized.