Lab: Profile a Slow Training Loop and Fix It
Measure the throughput of a slow image-training loop, profile it with torch.profiler to find that it is data-bound, fix the input pipeline with workers and then a one-off preprocessing cache, prove the fix leaves the training batches unchanged, and measure whether a larger batch or torch.compile helps the now compute-bound loop.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: The data and the slow loop
- Step 2: Measure the baseline
- Step 3: Profile five steps
- Step 4: Fix the input pipeline
- Step 5: Check that the fix changed speed, not results
- Step 6: Try the compute fixes, and measure them
- Check your understanding
- Apply it
- Review prompt
Lessons of Efficient PyTorch Training
- Lab: Feeding the GPU with Custom Datasets and DataLoaders Lab · 25 min
- Fitting More in Memory: Mixed Precision and Gradient Accumulation Concept · 20 min
- Worked Example: Checkpoint, Crash, Resume Worked example · 20 min
- Lab: Profile a Slow Training Loop and Fix It Lab · 30 min
- Lab: From One GPU to Several with DistributedDataParallel Lab · 25 min
- Check: Speed, Memory and Repeatability Knowledge check · 10 questions
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.
- Profile a training step to locate the bottleneck (data, compute or memory) and measure the speed-up from a fix such as torch.compile or a larger batch.
Prerequisites: Deep Learning Fundamentals
01. Goal and setup
A training loop is slow for one of three reasons. It is data-bound when the model waits for the next batch, compute-bound when the forward and backward passes themselves take the time, or memory-bound when the batch you can fit is too small to keep the hardware busy (here: memory capacity; profilers also call a kernel memory-bound when bandwidth limits it). The fixes differ for each, so guessing wastes time: adding torch.compile to a data-bound loop only makes the model wait faster. A profiler records how long every operation takes and settles the question with measurements.
In this lab you measure a slow loop, profile it, fix what the profile points at, check that the fix did not change the training, and measure the next candidates. The data are 512 PNG images of 256 × 256 pixels that the loop decodes and resizes every time it uses them. The model is deliberately tiny, so that on a laptop CPU it plays the part of a fast GPU that is easy to starve.
You need: Python 3.12, PyTorch 2 and torchvision (CPU builds), a C++ compiler for torch.compile in step 6 (gcc on Linux, the Xcode command-line tools on macOS), and about 100 MB of disk. All timings depend on your machine and on what else is running, so every timing block below is illustrative: compare the ratios, not the numbers. The scripts fix the thread count and keep the best of three timing windows to reduce noise.
profile-lab/
├── make_data.py step 1: writes data/0000.png … and data/labels.npy
├── data.py step 1: PngDataset (slow) and CachedDataset (fixed)
├── model.py step 1: a small CNN
├── train.py step 1: timed training loop with options
├── profile_step.py step 3: torch.profiler around 5 steps
├── prepare_cache.py step 4: decode and resize once, save cache.pt
└── check_same.py step 5: same batches, same losses?mkdir profile-lab && cd profile-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "torch==2.15.*" "torchvision==0.29.*" \
--index-url https://download.pytorch.org/whl/cpu02. Step 1: The data and the slow loop
The data script draws stripe patterns whose frequency depends on the class, with random angle, colour and noise, and saves them as PNG files.
"""Write 512 RGB images of 256 x 256 pixels (four classes of colour patterns) as PNG."""
from pathlib import Path
import numpy as np
from PIL import Image
rng = np.random.default_rng(0)
out = Path("data")
out.mkdir(exist_ok=True)
yy, xx = np.mgrid[0:256, 0:256] / 256.0
labels = []
for i in range(512):
label = i % 4
freq = 2 + label * 2 # each class is a stripe pattern with its own frequency
angle = rng.uniform(0, np.pi)
wave = np.sin(2 * np.pi * freq * (xx * np.cos(angle) + yy * np.sin(angle)))
rgb = np.stack([wave * rng.uniform(0.5, 1) for _ in range(3)], axis=-1)
rgb += rng.normal(0, 0.3, size=rgb.shape)
pixels = ((rgb + 2) / 4 * 255).clip(0, 255).astype(np.uint8)
Image.fromarray(pixels).save(out / f"{i:04d}.png")
labels.append(label)
np.save(out / "labels.npy", np.array(labels))
print(f"wrote {len(labels)} images, class counts {np.bincount(labels).tolist()}")python make_data.pywrote 512 images, class counts [128, 128, 128, 128]PngDataset opens, decodes and resizes an image inside __getitem__, every epoch, as many real pipelines do. CachedDataset is the fix you will build in step 4; it is here so that train.py can switch between them. train.py times the loop in two parts: a few warm-up steps, which include one-off costs such as starting worker processes or compiling, and the steady state, the throughput a long run actually gets. It reports samples per second, the number to compare between versions.
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision.transforms import v2
preprocess = v2.Compose([
v2.ToImage(),
v2.Resize(64, antialias=True), # 256 x 256 -> 64 x 64
v2.ToDtype(torch.float32, scale=True),
v2.Normalize([0.5] * 3, [0.25] * 3),
])
class PngDataset(Dataset):
"""Decodes and resizes every image again, every time it is requested."""
def __init__(self, root="data"):
self.files = sorted(Path(root).glob("*.png"))
self.labels = torch.from_numpy(np.load(Path(root) / "labels.npy"))
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
return preprocess(Image.open(self.files[idx]).convert("RGB")), self.labels[idx]
class CachedDataset(Dataset):
"""Serves tensors that were preprocessed once and saved to cache.pt."""
def __init__(self, path="cache.pt"):
cache = torch.load(path, weights_only=True)
self.images, self.labels = cache["images"], cache["labels"]
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
return self.images[idx], self.labels[idx]from torch import nn
def make_model():
# Deliberately small, so that on a CPU it plays the part of a fast GPU
return nn.Sequential(
nn.Conv2d(3, 16, 5, stride=2, padding=2), nn.BatchNorm2d(16), nn.ReLU(),
nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(32, 4),
)"""Train for a fixed number of steps and report steady-state throughput."""
import argparse
import time
import torch
from torch import nn
from torch.utils.data import DataLoader
from data import CachedDataset, PngDataset
from model import make_model
def build(args):
torch.set_num_threads(2) # a fixed thread count keeps timings comparable
torch.manual_seed(0)
ds = PngDataset() if args.data == "png" else CachedDataset()
loader = DataLoader(ds, batch_size=args.batch_size, shuffle=True, drop_last=True,
num_workers=args.workers, persistent_workers=args.workers > 0,
generator=torch.Generator().manual_seed(0))
model = make_model()
opt = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9)
step_fn = train_step
if args.compile:
step_fn = torch.compile(train_step)
return loader, model, opt, step_fn
def train_step(model, opt, x, y):
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
return loss.detach()
def batches(loader):
while True: # loop over epochs until the caller stops
yield from loader
def main(args):
loader, model, opt, step_fn = build(args)
it = batches(loader)
start = time.perf_counter()
for _ in range(args.warmup): # timed apart: worker start-up, compilation
x, y = next(it)
step_fn(model, opt, x, y)
warmup = time.perf_counter() - start
best = float("inf")
for _ in range(3): # three timed windows; keep the fastest (least disturbed)
start = time.perf_counter()
for _ in range(args.steps):
x, y = next(it)
step_fn(model, opt, x, y)
best = min(best, time.perf_counter() - start)
print(f"data={args.data} workers={args.workers} batch={args.batch_size} "
f"compile={args.compile}: warm-up {warmup:4.1f} s, "
f"{args.steps * args.batch_size / best:5.0f} samples/s")
def parse(argv=None):
p = argparse.ArgumentParser()
p.add_argument("--data", choices=["png", "cache"], default="png")
p.add_argument("--workers", type=int, default=0)
p.add_argument("--batch-size", type=int, default=32)
p.add_argument("--compile", action="store_true")
p.add_argument("--warmup", type=int, default=3)
p.add_argument("--steps", type=int, default=20)
return p.parse_args(argv)
if __name__ == "__main__":
main(parse())03. Step 2: Measure the baseline
python train.pydata=png workers=0 batch=32 compile=False: warm-up 1.3 s, 131 samples/sEvery later change is judged against this number, on the same machine and with the same command. It does not say why the loop is slow; that is the profiler's job.
04. Step 3: Profile five steps
torch.profiler.profile records every PyTorch operation (an operator, such as a convolution or a copy) with its duration. Two details make the result readable. record_function("data") and its siblings wrap each phase of the step in a labelled range, so you can see the share of time per phase and not only per operator. The schedule skips the first step, records two warm-up steps that are thrown away and then records five, because the first steps include one-off work and the profiler itself needs a moment to settle; prof.step() tells it where each step ends. On a GPU you would add ProfilerActivity.CUDA, which the script does automatically, to record the GPU kernels as well.
The script prints a compact summary and writes trace.json, a timeline you can open in Perfetto or chrome://tracing to see the phases of each step side by side.
"""Profile 5 training steps and print where the time goes."""
import sys
import torch
from torch import nn
from torch.profiler import ProfilerActivity, profile, record_function, schedule
from train import batches, build, parse
args = parse(sys.argv[1:])
loader, model, opt, _ = build(args)
it = batches(loader)
activities = [ProfilerActivity.CPU]
if torch.cuda.is_available():
activities.append(ProfilerActivity.CUDA)
# skip 1 step, warm up for 2 (recorded but discarded), then record 5
with profile(activities=activities,
schedule=schedule(wait=1, warmup=2, active=5)) as prof:
for _ in range(8):
with record_function("data"):
x, y = next(it)
with record_function("forward"):
loss = nn.functional.cross_entropy(model(x), y)
with record_function("backward"):
opt.zero_grad(set_to_none=True)
loss.backward()
with record_function("optimizer"):
opt.step()
prof.step() # tells the schedule that one step has finished
events = prof.key_averages()
phases = {e.key: e.cpu_time_total for e in events
if e.key in ("data", "forward", "backward", "optimizer")}
total = sum(phases.values())
shares = ", ".join(f"{k} {v / total:.0%}" for k, v in phases.items())
print("share of step time:", shares)
print(f"{'top 6 by self CPU time':38} {'self ms':>8} {'calls':>6}")
ops = sorted((e for e in events if e.key not in phases),
key=lambda e: e.self_cpu_time_total, reverse=True)
for e in ops[:6]:
print(f"{e.key[:38]:38} {e.self_cpu_time_total / 1000:8.1f} {e.count:6d}")
prof.export_chrome_trace("trace.json") # open in https://ui.perfetto.devpython profile_step.pyshare of step time: data 84%, forward 4%, backward 12%, optimizer 0%
top 6 by self CPU time self ms calls
enumerate(DataLoader)#_SingleProcessDa 882.9 5
aten::copy_ 278.7 705
aten::_upsample_bilinear2d_aa 259.8 160
aten::convolution_backward 180.2 10
aten::round_ 115.8 160
aten::mkldnn_convolution 59.1 10The verdict is clear: most of each step is spent in the data range, and only a small share in the forward and backward passes. The loop is data-bound. The operator list says where inside the data phase the time goes. enumerate(DataLoader) is the profiler's own entry for fetching batches. aten::_upsample_bilinear2d_aa is the antialiased resize, and its call count gives it away: 160 calls in 5 steps is once per image (5 × 32), so it runs per item inside the Dataset, not in the model. PNG decoding by Pillow does not appear as an operator because it is not PyTorch code, but it is part of the data range. The convolutions, the only real model work, are far down the list.
05. Step 4: Fix the input pipeline
The first fix to try is parallel loading: four worker processes decode and resize while the main process trains, as in the DataLoader lab.
python train.py --workers 4data=png workers=4 batch=32 compile=False: warm-up 0.6 s, 541 samples/sWorkers help, but they still repeat the same work every epoch: this preprocessing has no randomness, so each image gives the same 64 × 64 tensor every time. The bigger fix is to do it once. prepare_cache.py decodes and resizes all images with the same preprocess function and saves them in one tensor file, 24 MiB, instead of decoding roughly 85 MB of PNG files every epoch. Random augmentations, if you had them, would stay in the loader and run on the cached tensors, which is much cheaper than running them on full-size images.
"""Decode and resize every image once, and save the result as one tensor file."""
import torch
from data import PngDataset
ds = PngDataset()
images = torch.stack([ds[i][0] for i in range(len(ds))])
torch.save({"images": images, "labels": ds.labels}, "cache.pt")
print("cached", tuple(images.shape), images.dtype,
f"= {images.numel() * images.element_size() / 2**20:.0f} MiB")
same = torch.equal(images[7], ds[7][0])
print("item 7 identical to the PNG pipeline:", same)python prepare_cache.pycached (512, 3, 64, 64) torch.float32 = 24 MiB
item 7 identical to the PNG pipeline: Truepython train.py --data cache
python train.py --data cache --workers 2data=cache workers=0 batch=32 compile=False: warm-up 0.1 s, 874 samples/s
data=cache workers=2 batch=32 compile=False: warm-up 0.2 s, 849 samples/sThe cached loop is several times faster than the PNG baseline. Note the second line: with the data already in memory, workers no longer help, because each batch now has to be pickled and passed between processes, which costs about as much as reading it directly. Workers pay off when __getitem__ does real work. Profile again to see what limits the loop now.
python profile_step.py --data cacheshare of step time: data 4%, forward 27%, backward 66%, optimizer 3%
top 6 by self CPU time self ms calls
aten::convolution_backward 65.5 10
aten::mkldnn_convolution 21.7 10
aten::threshold_backward 11.4 10
aten::native_batch_norm 6.3 10
aten::native_batch_norm_backward 4.7 10
aten::clamp_min 2.9 10The data share has fallen to a few per cent, and the backward pass, led by aten::convolution_backward, now takes most of the step. The loop has become compute-bound, which is where a training loop should be.
06. Step 5: Check that the fix changed speed, not results
A performance fix must not change what the model learns from, unless you intend it to. Caching could silently do that, for example by using a different resize setting. The check is cheap: train ten steps with each pipeline from the same seed and compare the losses. Exact equality is a strong test, and it is possible here because the preprocessing is deterministic and the loader order comes from the same seeded generator.
"""Do the slow and the fixed pipeline train on exactly the same batches?"""
from train import batches, build, parse, train_step
configs = (["--data", "png"], ["--data", "cache"],
["--data", "cache", "--workers", "2"])
for cli in configs:
args = parse(cli)
loader, model, opt, _ = build(args)
it = batches(loader)
losses = [train_step(model, opt, *next(it)).item() for _ in range(10)]
print(f"{' '.join(cli):26} losses after 1, 5, 10 steps:",
", ".join(f"{losses[i]:.6f}" for i in (0, 4, 9)))python check_same.py--data png losses after 1, 5, 10 steps: 1.448584, 1.141802, 0.795633
--data cache losses after 1, 5, 10 steps: 1.448584, 1.141802, 0.795633
--data cache --workers 2 losses after 1, 5, 10 steps: 1.448584, 1.141802, 0.795633All three pipelines give the same losses to six decimals, so the speed-up came for free. If a fix does change the numbers (mixed precision or torch.compile can, slightly), compare validation metrics within a tolerance instead.
07. Step 6: Try the compute fixes, and measure them
For a compute-bound loop, two common candidates are a larger batch, which gives each operator more work per call and so spreads fixed per-call overheads over more samples, and torch.compile, which traces the step into a graph and generates fused kernels, for example combining several element-wise operations into one pass over memory. Measure both against the cached baseline from step 4.
python train.py --data cache --batch-size 128
python train.py --data cache --compiledata=cache workers=0 batch=128 compile=False: warm-up 0.3 s, 1434 samples/s
data=cache workers=0 batch=32 compile=True: warm-up 23.8 s, 731 samples/sCompare each line with the cached baseline of step 4, and run each command twice before you trust a difference: on a busy laptop, two runs of the same command can differ by more than 20%. Two things hold whatever your numbers are. First, the compiled run pays a warm-up of many seconds while it generates code, so compilation only pays off when the run is long enough to earn it back. Second, on a CPU neither change comes close to the gain from the data fix. The second profile explains why: the time sits in convolution kernels that are already optimised library code, which compilation does not replace, and whether a larger batch helps depends on how well the bigger activations still fit in the processor caches.
On a GPU the balance is different. GPUs need much more parallel work per kernel to be busy, so larger batches, often made possible by mixed precision, commonly raise samples per second, and torch.compile can remove many small kernel launches. When you time on a GPU, call torch.cuda.synchronize() before reading the clock, because CUDA calls return before the GPU has finished, and record peak memory with torch.cuda.max_memory_allocated(); a memory-bound loop shows up as a batch size you cannot raise. Whatever the hardware, the method is the same as in this lab: profile, change one thing, measure it the same way, and keep only what helps.
08. Check your understanding
09. Apply it
For your practice package:
- Add a
profilecommand that wraps 5 steps of your real loop intorch.profilerwith labelled phases and saves a trace. - Classify your loop as data-, compute- or memory-bound from the profile, and write down the evidence.
- Apply one fix, show with a
check_same-style test that training is unchanged (or within tolerance), and report samples per second and, on a GPU, peak memory before and after.
10. Review prompt
Without looking back, describe the three kinds of bottleneck and one fix for each; explain what record_function, the profiler schedule and prof.step() do; explain how a call count can locate work in the pipeline; say when DataLoader workers help and when they do not; explain why warm-up time is reported separately from steady-state throughput; and give two rules for timing code on a GPU.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.