Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Lab · 25 min · revision 2

Lab: Feeding the GPU with Custom Datasets and DataLoaders

Build an input pipeline for image files on disk: a map-style Dataset that decodes and transforms each image, a seeded DataLoader, correct randomness inside worker processes, a measurement of how long the training loop waits for data with 0, 2 and 4 workers, and a training loop that places batches on the device with pinned memory when a GPU is present.

Contentsand lesson path

What you will learn

  • Write custom Dataset and DataLoader pipelines with transforms, worker processes and pinned memory so that data loading does not starve the GPU.

Prerequisites: Deep Learning Fundamentals

01. Goal and setup

A GPU can only work as fast as data arrives. If every batch is read from disk, decoded and augmented in the same process that runs the model, the GPU sits idle while the CPU prepares the next batch. This is called data starvation, and it is a common reason why training is slower than it should be.

In this lab you build an input pipeline for images stored as files with a CSV of labels: a Dataset that decodes one image at a time, a DataLoader that groups images into shuffled batches, correct randomness in worker processes, a measurement of how long the loop waits for data, and a training loop that moves batches to the device. Everything runs on a laptop CPU; the GPU-only settings switch on automatically when a GPU is present.

You need: Python 3.12, PyTorch 2 and torchvision (CPU builds are fine). The lab builds on your first PyTorch training loop. Seeds are fixed, so on PyTorch 2.15 your numbers should match the expected outputs; another version or CPU can change the last digit. Timings in step 5 depend on your machine.

Project layout at the end of the lab
loader-lab/
├── make_data.py      step 1: draws 600 PNG images and labels.csv
├── data/             created by step 1
├── shapes.py         step 2: the Dataset and its transforms
├── check_dataset.py  step 2: reads one item
├── loader.py         step 3: train and validation DataLoaders
├── rng_bug.py        step 4: randomness inside workers
├── bench_workers.py  step 5: how long the loop waits for data
└── train.py          step 6: device placement and a training loop
Terminal
mkdir loader-lab && cd loader-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" "torchvision==0.29.*" \
  --index-url https://download.pytorch.org/whl/cpu

02. Step 1: Create a small image dataset on disk

The script draws 600 greyscale 32 × 32 images of a circle, square or triangle at a random size, position and brightness, and writes labels.csv. A seeded generator makes the images identical on every machine.

Python · make_data.py
"""Draw 600 small shape images (circle, square, triangle) and write labels.csv."""
import csv
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw

rng = np.random.default_rng(0)
out = Path("data/images")
out.mkdir(parents=True, exist_ok=True)
classes = ["circle", "square", "triangle"]
rows = []
for i in range(600):
    label = i % 3
    img = Image.new("L", (32, 32), color=int(rng.integers(0, 60)))
    draw = ImageDraw.Draw(img)
    size = int(rng.integers(10, 20))
    x, y = (int(v) for v in rng.integers(2, 30 - size, size=2))
    shade = int(rng.integers(150, 256))
    box = [x, y, x + size, y + size]
    if label == 0:
        draw.ellipse(box, fill=shade)
    elif label == 1:
        draw.rectangle(box, fill=shade)
    else:
        corners = [(x, y + size), (x + size, y + size), (x + size // 2, y)]
        draw.polygon(corners, fill=shade)
    name = f"img_{i:04d}.png"
    img.save(out / name)
    rows.append((name, classes[label]))
with open("data/labels.csv", "w", newline="") as f:
    csv.writer(f).writerows([("file", "label"), *rows])
print(f"wrote {len(rows)} images to {out}/")
print("first rows:", *rows[:2])
Terminal
python make_data.py
Expected output
wrote 600 images to data/images/
first rows: ('img_0000.png', 'circle') ('img_0001.png', 'square')

03. Step 2: A map-style Dataset that decodes on demand

A map-style Dataset has two methods: __len__ returns the number of examples and __getitem__(idx) returns example idx. Because examples are reachable by index, the DataLoader shuffles them by shuffling indices. An IterableDataset implements __iter__ instead and suits streams with no index, such as rows from a message queue.

ShapesDataset keeps only file names and labels in memory and decodes an image inside __getitem__, so memory stays small however many images there are, and the decoding happens wherever __getitem__ is called, which matters in step 5.

A transform is applied to each example as it is loaded. From torchvision transforms.v2: ToImage makes a (channels, height, width) tensor, ToDtype(..., scale=True) turns 0–255 integers into floats from 0 to 1, and Normalize([0.5], [0.5]) maps them to about −1 to 1. The training transform also flips images left to right at random, a data augmentation that is safe here because a flipped shape keeps its label. The validation transform has no randomness, so its scores are comparable between epochs, and a seeded torch.randperm holds out the same 120 images every time.

Python · shapes.py
"""A map-style Dataset that reads the PNG files listed in labels.csv."""
import csv
from pathlib import Path

import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision.transforms import v2

CLASSES = ["circle", "square", "triangle"]


class ShapesDataset(Dataset):
    def __init__(self, root, rows, transform=None):
        self.root = Path(root)
        self.rows = rows  # list of (file name, class name)
        self.transform = transform

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, idx):
        name, label = self.rows[idx]
        image = Image.open(self.root / "images" / name)  # decoded here, per item
        if self.transform is not None:
            image = self.transform(image)
        return image, CLASSES.index(label)


def read_rows(root):
    with open(Path(root) / "labels.csv") as f:
        return [(r["file"], r["label"]) for r in csv.DictReader(f)]


def split_rows(rows, n_val=120, seed=0):
    order = torch.randperm(len(rows), generator=torch.Generator().manual_seed(seed))
    val = [rows[i] for i in order[:n_val].tolist()]
    train = [rows[i] for i in order[n_val:].tolist()]
    return train, val


to_tensor = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])
train_tf = v2.Compose([
    to_tensor, v2.RandomHorizontalFlip(), v2.Normalize([0.5], [0.5])
])
eval_tf = v2.Compose([to_tensor, v2.Normalize([0.5], [0.5])])
Python · check_dataset.py
from shapes import ShapesDataset, eval_tf, read_rows, split_rows

rows = read_rows("data")
train_rows, val_rows = split_rows(rows)
train_ds = ShapesDataset("data", train_rows, transform=eval_tf)
print("train/val sizes:", len(train_ds), len(val_rows))
image, label = train_ds[0]
print("one item:", tuple(image.shape), image.dtype, "label", label)
print(f"pixel range: {image.min():.2f} to {image.max():.2f}")
Terminal
python check_dataset.py
Expected output
train/val sizes: 480 120
one item: (1, 32, 32) torch.float32 label 0
pixel range: -0.91 to 0.21

One item is a (1, 32, 32) float tensor and an integer label. Checking a single item before any batching catches most shape and type mistakes early.

04. Step 3: Batches, shuffling and a seeded order

The DataLoader asks a sampler for indices, calls __getitem__ for each, and stacks the results into a batch with its collate function, which by default stacks equal-shaped tensors along a new first dimension. With shuffle=True the sampler draws a new order each epoch; a generator with a fixed seed makes that sequence of orders repeatable, which you need to reproduce a result or a bug.

make_loaders sets pin_memory only when a GPU is present (step 6) and persistent_workers when there are workers, so they survive between epochs instead of restarting.

Python · loader.py
import torch
from torch.utils.data import DataLoader

from shapes import ShapesDataset, eval_tf, read_rows, split_rows, train_tf


def make_loaders(batch_size=64, num_workers=0, seed=0):
    train_rows, val_rows = split_rows(read_rows("data"))
    train_ds = ShapesDataset("data", train_rows, transform=train_tf)
    val_ds = ShapesDataset("data", val_rows, transform=eval_tf)
    gpu = torch.cuda.is_available()
    common = dict(batch_size=batch_size, num_workers=num_workers, pin_memory=gpu,
                  persistent_workers=num_workers > 0)
    train = DataLoader(train_ds, shuffle=True,
                       generator=torch.Generator().manual_seed(seed), **common)
    val = DataLoader(val_ds, shuffle=False, **common)
    return train, val


def first_labels_per_epoch(loader, epochs=2):
    firsts = []
    for _ in range(epochs):
        batches = [y for _, y in loader]  # a full pass over the data = one epoch
        firsts.append(batches[0][:8].tolist())
    return firsts


if __name__ == "__main__":
    train, val = make_loaders()
    print("batches per epoch:", len(train), "train,", len(val), "val")
    print("train batch sizes:", [len(y) for _, y in train])
    x, y = next(iter(train))
    print("images:", tuple(x.shape), x.dtype, "| labels:", tuple(y.shape), y.dtype)
    for run in (1, 2):
        e1, e2 = first_labels_per_epoch(make_loaders()[0])
        print(f"run {run}: epoch 1 starts {e1}, epoch 2 starts {e2}")
Terminal
python loader.py
Expected output
batches per epoch: 8 train, 2 val
train batch sizes: [64, 64, 64, 64, 64, 64, 64, 32]
images: (64, 1, 32, 32) torch.float32 | labels: (64,) torch.int64
run 1: epoch 1 starts [0, 0, 1, 0, 2, 1, 2, 1], epoch 2 starts [2, 1, 1, 2, 2, 0, 2, 0]
run 2: epoch 1 starts [0, 0, 1, 0, 2, 1, 2, 1], epoch 2 starts [2, 1, 1, 2, 2, 0, 2, 0]

480 images in batches of 64 give seven full batches and a last one of 32 (drop_last=True removes it). Labels are torch.int64, as cross_entropy expects. Both runs print the same starting labels per epoch, while epoch 2 differs from epoch 1: a new shuffle every epoch, the same sequence of shuffles every run.

05. Step 4: Random augmentation inside worker processes

With num_workers above zero, the DataLoader starts that many worker processes, each building whole batches in parallel from its own copy of the Dataset. The copy is made by forking on Linux or by pickling on macOS and Windows; either way everything in the object is duplicated, including the state of any random-number generator it holds.

PyTorch gives each worker its own seed for Python's random, NumPy's global np.random functions and PyTorch's generator, so torch.rand and torchvision transforms differ between workers. A NumPy Generator object created in the Dataset's __init__ is not reseeded. The script shows the effect with a stand-in augmentation, a random shift per item.

Python · rng_bug.py
"""Random augmentation inside DataLoader workers: a copied NumPy generator."""
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset, get_worker_info


class NoisyIndex(Dataset):
    """Returns (index, random shift) as a stand-in for a random augmentation."""

    def __init__(self):
        self.rng = np.random.default_rng(0)  # created once, in the main process

    def __len__(self):
        return 8

    def __getitem__(self, idx):
        return idx, int(self.rng.integers(0, 100))


def reseed_worker(worker_id):
    info = get_worker_info()  # this worker's id, seed and copy of the dataset
    info.dataset.rng = np.random.default_rng(info.seed)


if __name__ == "__main__":
    for name, init in (("copied", None), ("reseeded", reseed_worker)):
        torch.manual_seed(0)
        loader = DataLoader(NoisyIndex(), batch_size=2, num_workers=2,
                            worker_init_fn=init)
        for idx, shift in loader:
            print(f"{name:8}  items {idx.tolist()}  shifts {shift.tolist()}")
Terminal
python rng_bug.py
Expected output
copied    items [0, 1]  shifts [85, 63]
copied    items [2, 3]  shifts [85, 63]
copied    items [4, 5]  shifts [51, 26]
copied    items [6, 7]  shifts [51, 26]
reseeded  items [0, 1]  shifts [52, 77]
reseeded  items [2, 3]  shifts [24, 65]
reseeded  items [4, 5]  shifts [52, 64]
reseeded  items [6, 7]  shifts [8, 26]

With the copied generator, worker 0 (items 0 and 1) and worker 1 (items 2 and 3) produce the same shifts, 85 and 63; with 8 workers, eight batches in a row would get the same "random" crops. The fix is a worker_init_fn, which runs once inside each worker: get_worker_info() returns that worker's seed (the base seed plus the worker id), and a fresh generator is built from it. The simpler alternative is to draw randomness with torch or torchvision transforms.

06. Step 5: Measure how long the loop waits for data

Decoding and augmenting real photos is often the most expensive part of a step. As a stand-in, this script uses a heavy transform that upscales each image to 160 × 160, crops, rotates and blurs it. A small model trains for one epoch with 0, 2 and 4 workers, and the loop measures waiting (from the end of one step until the next batch arrives) separately from computing (forward, backward and update). A warm-up epoch first starts the workers, a one-off cost, and each process uses one CPU thread for a fair comparison.

Python · bench_workers.py
"""How long does the training loop wait for data with 0, 2 or 4 loader workers?"""
import time

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision.transforms import v2

from shapes import ShapesDataset, read_rows, split_rows

# Stands in for decoding and augmenting full-size photos: upscale, crop, rotate, blur.
heavy_tf = v2.Compose([
    v2.ToImage(),
    v2.RandomResizedCrop(160, scale=(0.6, 1.0), antialias=True),
    v2.RandomRotation(15),
    v2.ToDtype(torch.float32, scale=True),
    v2.GaussianBlur(9),
    v2.Normalize([0.5], [0.5]),
])


def one_epoch(loader, model, opt):
    wait = compute = 0.0
    t0 = time.perf_counter()
    for x, y in loader:
        t1 = time.perf_counter()
        wait += t1 - t0  # time spent getting this batch from the loader
        loss = nn.functional.cross_entropy(model(x), y)
        opt.zero_grad()
        loss.backward()
        opt.step()
        t0 = time.perf_counter()
        compute += t0 - t1  # time spent on forward, backward and the update
    return wait, compute


if __name__ == "__main__":
    torch.set_num_threads(1)  # one CPU thread per process, so the comparison is fair
    torch.manual_seed(0)
    train_rows, _ = split_rows(read_rows("data"))
    ds = ShapesDataset("data", train_rows, transform=heavy_tf)
    model = nn.Sequential(nn.Conv2d(1, 16, 5, stride=4), nn.ReLU(),
                          nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(16, 3))
    opt = torch.optim.SGD(model.parameters(), lr=0.1)
    for workers in (0, 2, 4):
        loader = DataLoader(ds, batch_size=64, shuffle=True, num_workers=workers,
                            persistent_workers=workers > 0,
                            generator=torch.Generator().manual_seed(0))
        one_epoch(loader, model, opt)  # warm-up epoch: starts the worker processes
        wait, compute = one_epoch(loader, model, opt)
        share = wait / (wait + compute)
        print(f"workers={workers}: waiting {wait:5.2f} s, "
              f"computing {compute:4.2f} s -> {share:.0%} of the epoch waiting")
Terminal
python bench_workers.py
Illustrative output
workers=0: waiting  3.68 s, computing 0.28 s -> 93% of the epoch waiting
workers=2: waiting  1.89 s, computing 0.30 s -> 86% of the epoch waiting
workers=4: waiting  0.99 s, computing 0.30 s -> 77% of the epoch waiting

Your times will differ; the pattern should not. With num_workers=0, every image is transformed in the main process while the model waits, here over 90% of the epoch. Workers prepare batches in parallel with each other and with the training step, and four cut the waiting about fourfold on this machine. The loop still mostly waits because the model is tiny next to the transform; next would come cheaper transforms (resize once, offline) or augmentation on the GPU. Workers beyond the free CPU cores stop helping.

The profiling lab makes the same split with torch.profiler, in more detail.

07. Step 6: Put batches on the device and train

The model and each batch must be on the same device. The script picks cuda when a GPU is present, else cpu, moves the model once before building the optimizer, and moves every batch in the loop.

Two settings matter only on a GPU. Pinned memory (page-locked memory) is host RAM that the operating system will not move or swap out, so the GPU can copy from it directly by DMA, without an extra staging copy. With pin_memory=True the DataLoader puts each batch there, and .to(device, non_blocking=True) starts the copy and returns at once, so the CPU can queue more work during the transfer. Without a GPU, PyTorch ignores pin_memory=True with a warning.

The if __name__ == "__main__": guard matters with workers on macOS and Windows: there each worker starts a fresh interpreter that imports your script, and unguarded code would start loaders again inside it.

Python · train.py
import torch
from torch import nn

from loader import make_loaders


def main():
    torch.manual_seed(0)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    train, val = make_loaders(batch_size=64, num_workers=2)
    model = nn.Sequential(
        nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
        nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
        nn.Flatten(), nn.Linear(32 * 8 * 8, 3),
    ).to(device)  # move the weights once, before the optimizer is built
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    print("device:", device, "| pin_memory:", train.pin_memory)
    for epoch in range(1, 6):
        model.train()
        total = 0.0
        for x, y in train:
            # non_blocking only helps from pinned memory to a GPU; on CPU it is a no-op
            x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
            loss = nn.functional.cross_entropy(model(x), y)
            opt.zero_grad()
            loss.backward()
            opt.step()
            total += loss.item() * len(y)
        model.eval()
        correct = 0
        with torch.no_grad():
            for x, y in val:
                x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
                correct += (model(x).argmax(1) == y).sum().item()
        print(f"epoch {epoch}: train loss {total / len(train.dataset):.3f}, "
              f"val accuracy {correct / len(val.dataset):.3f}")


if __name__ == "__main__":  # required: worker processes may re-import this file
    main()
Terminal
python train.py
Expected output
device: cpu | pin_memory: False
epoch 1: train loss 1.082, val accuracy 0.442
epoch 2: train loss 0.914, val accuracy 0.625
epoch 3: train loss 0.709, val accuracy 0.725
epoch 4: train loss 0.526, val accuracy 0.825
epoch 5: train loss 0.369, val accuracy 0.867

Validation accuracy reaches 0.867 after five epochs. The numbers repeat run after run, even with two workers and random flips, because the loader generator fixes both the shuffle and the seeds handed to the workers. Change num_workers and the flips change, so the worker count is part of what makes a run repeatable.

08. Check your understanding

Practice check · 3 questions

Datasets, loaders and workers

Use the scripts and outputs of this lab.

Q1. In step 4, without `reseed_worker`, the batch with items 0 and 1 and the batch with items 2 and 3 both get the shifts 85 and 63. What causes the repeat?
Q2. In step 3, both runs print the same starting labels for epoch 1 and for epoch 2, but epoch 2 starts differently from epoch 1. What produces this pattern?
Q3. A colleague on macOS removes the `if __name__ == "__main__":` guard from `train.py` and gets "An attempt has been made to start a new process before the current process has finished its bootstrapping phase". Why?
Practice only: not graded, not saved, not evidence.

09. Apply it

Start the practice project for this skill: turn a training notebook into a small package.

  1. Move the Dataset and transforms into data.py and make_loaders into the same module, with the batch size, worker count and seed read from a config file.
  2. Add a --bench option that runs the measurement from step 5 on your own data and prints the waiting share for 0, 2, 4 and 8 workers.
  3. Pick the worker count from that measurement, and write down the waiting share before and after in your project notes.

10. Review prompt

Without looking back, explain the two methods a map-style Dataset implements and what the DataLoader does with them; why decoding inside __getitem__ keeps memory low; how a seeded generator makes shuffling repeatable; why a generator stored in the Dataset repeats across workers and two ways to fix it; how to measure whether a loop is waiting for data; and what pinned memory and non_blocking=True do on a GPU.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check