Sub topic 2
Measure first: profiling stages and throughput
This chapter assumes you know basic Python, NumPy arrays, and PyTorch's Dataset and DataLoader. You should also know what a JPEG file is. By the end you will be able to find which stage of an image pipeline limits your training or inference speed, and to tell whether the data pipeline or the model is the bottleneck.
Why measure before optimising
Most slow vision pipelines are slow in one place. If decoding takes 8 ms per image and resizing takes 1 ms, a faster resize function saves almost nothing. Optimising the wrong stage costs time and adds complexity without improving speed.
A pipeline runs as a chain of stages. The slowest stage sets the throughput of the whole chain. Throughput is the number of images processed per second. Latency is the time one image takes from file to model input. Training cares about throughput. An interactive service cares about latency as well.
The pipeline from the previous chapter has these stages:
- Read the file bytes from disk or network.
- Decode the compressed bytes into pixels.
- Resize to the model's input size.
- Convert, normalise, and batch.
- Copy the batch to the GPU.
- Run the model.
You need a number for each of these before you change anything.
Timing each stage on one process
Start with a single process and no DataLoader workers. This isolates the cost of the work itself from scheduling effects. The function below times file reading, decoding, and resizing separately and prints the average per image.
import io
import time
from PIL import Image
def time_stages(paths, size=(224, 224)):
t_read = t_decode = t_resize = 0.0
for p in paths:
t0 = time.perf_counter()
with open(p, "rb") as f:
data = f.read()
t1 = time.perf_counter()
im = Image.open(io.BytesIO(data)).convert("RGB") # decode happens here
t2 = time.perf_counter()
im = im.resize(size, Image.Resampling.BILINEAR)
t3 = time.perf_counter()
t_read += t1 - t0
t_decode += t2 - t1
t_resize += t3 - t2
n = len(paths)
print(f"read {t_read/n*1e3:.2f} ms, decode {t_decode/n*1e3:.2f} ms, resize {t_resize/n*1e3:.2f} ms per image")Three details in this code matter.
time.perf_counter()is the right clock. It is monotonic and has high resolution.time.time()can jump if the system clock changes.- Decoding happens at
.convert("RGB"), not atImage.open. Pillow loads lazily.Image.openreads only the header. If you timed onlyopen, decode would look free and the cost would land in the next stage. - Reading from
BytesIOseparates I/O from decode. Without it, Pillow would read from the file during decode and the two costs would blur together.
Warm-up and the page cache
The first run over a set of files is usually slower than later runs. The operating system keeps recently read files in memory, called the page cache. On the second pass, "read" may drop from several milliseconds to a few microseconds because no disk is touched.
This creates two common mistakes:
- Benchmarking on a small set that fits in the page cache, then training on a dataset far larger than memory. Your real read cost is much higher than measured.
- Comparing two variants where the first one paid the cold-disk cost and the second one did not.
Decide which case you care about. For a dataset that fits in RAM, measure the warm case. For a large dataset on network storage, measure the cold case, for example by using files you have not yet touched or by running on a fresh machine. Run a warm-up pass and discard it when you want warm numbers.
Use enough samples and a representative set
Image cost depends on resolution, JPEG quality, and content. A 4000x3000 photo costs far more to decode than a 500x375 thumbnail. Time a random sample of at least a few hundred files from your real dataset, not a handful of convenient ones. Also report more than the mean. A few huge images can dominate the mean while the typical image is cheap, so keep per-image times and look at the median and the 95th percentile.
import statistics
def summarise(times_ms):
ordered = sorted(times_ms)
p95 = ordered[int(0.95 * (len(ordered) - 1))]
return {
"mean": statistics.fmean(ordered),
"median": statistics.median(ordered),
"p95": p95,
}
print(summarise([4.1, 4.3, 4.0, 4.4, 4.2, 19.8, 4.1, 4.3, 4.2, 4.0]))The output shows a mean near 5.7 ms but a median of 4.2 ms. The one slow image pulls the mean up. A long tail like this matters in training, because a batch waits for its slowest image.
Reading the result
Suppose the function prints this for 224x224 targets on photos of about 1000x750 pixels:
| Stage | Time per image |
|---|---|
| read | 0.3 ms |
| decode | 6.0 ms |
| resize | 1.2 ms |
Total CPU time is 7.5 ms per image, so one process produces about 133 images per second. Decode is 80% of the work. Two consequences follow.
- Speeding up resize by a factor of two saves 0.6 ms, about 8% of the total.
- Anything that reduces decode cost, such as decoding at reduced size, has far more room to help.
This arithmetic is the reason to measure first. The chapters on decoding and draft mode follow from this table.
Measuring end-to-end throughput
Per-stage timing tells you where CPU time goes. It does not tell you whether the GPU waits for data. For that, measure the whole loop. Time how long the training loop spends waiting for the next batch, separately from how long it spends computing.
import time
import torch
def profile_loop(loader, step_fn, max_batches=50, device="cuda"):
wait = compute = 0.0
n_images = 0
it = iter(loader)
for _ in range(max_batches):
t0 = time.perf_counter()
try:
batch = next(it)
except StopIteration:
break
t1 = time.perf_counter()
step_fn(batch)
if device == "cuda":
torch.cuda.synchronize() # wait for queued GPU work to finish
t2 = time.perf_counter()
wait += t1 - t0
compute += t2 - t1
n_images += len(batch)
total = wait + compute
print(f"wait {wait:.2f}s, compute {compute:.2f}s, "
f"{n_images/total:.0f} images/s, data wait {wait/total:.0%}")Here step_fn is your function that moves a batch to the device and runs the model. Two points make this measurement valid.
torch.cuda.synchronize()is required. CUDA calls are asynchronous: Python returns as soon as work is queued, not when it finishes. Without the synchronize call, the compute time looks near zero and the nextnext(it)absorbs the real GPU time as apparent wait.- Wait time is the signal. If the loop spends most of its time inside
next(it), the model is starved and the data pipeline is the bottleneck. If wait is near zero, the model is the bottleneck and data work is already hidden.
Discard the first few batches. Worker start-up, CUDA initialisation, and cuDNN autotuning inflate early iterations. The simplest approach is to run profile_loop once as warm-up, then run it again and keep the second result.
A decision table
| Observation | Likely bottleneck | Where to look next |
|---|---|---|
| Data wait above 20%, GPU idle often | Input pipeline | Per-stage timing, then decoding and workers |
| Data wait near 0%, GPU fully busy | Model or GPU | Batch size, mixed precision, model code |
| Wait is high at the start of each epoch only | Worker start-up | Persistent workers |
| Wait spikes irregularly | Slow storage or very large images | Cold-cache timing, caching, p95 image cost |
| Throughput does not rise with more workers | Disk, memory bandwidth, or the main process | Storage speed, transfer, collation |
The 20% threshold is a rule of thumb, not a law. Any consistent wait that you could remove by overlapping work is worth a look.
Checking the GPU directly
You can confirm the loop measurement from outside Python. While training runs, nvidia-smi shows GPU utilisation. A GPU that alternates between 100% and 0% is starved in bursts, which usually means the pipeline cannot keep up. Be careful with reading a single number, though. Utilisation reports the share of time at least one kernel was running, not how efficiently the GPU was used, so a small kernel can show high utilisation while using little of the hardware.
For deeper detail, PyTorch ships a profiler that records CPU and GPU activity on one timeline.
import torch
from torch.profiler import profile, ProfilerActivity
def run_profiled(loader, step_fn, n=10):
activities = [ProfilerActivity.CPU]
if torch.cuda.is_available():
activities.append(ProfilerActivity.CUDA)
with profile(activities=activities) as prof:
for i, batch in enumerate(loader):
if i >= n:
break
step_fn(batch)
print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10))Use the profiler after the simple timers have narrowed the question. It produces a lot of output, and it slows the run while recording. It also sees only the main process by default, so worker-side decode time will not appear in it. That is why the manual per-stage timer above stays useful.
Common errors
- Timing lazy operations. Timing
Image.openalone, or timing a CUDA call without synchronising, measures almost nothing. - Measuring once. A single run is affected by cache state and background load. Repeat and compare medians.
- Changing two things at once. If you add workers and switch to draft decoding together, you cannot say which one helped. Change one factor per experiment.
- Benchmarking with workers when profiling stages. Workers hide per-stage costs behind parallelism. Profile stages on one process, then scale up.
- Ignoring the CPU count. If your machine has 8 cores, 16 workers will not give twice the throughput of 8. Record the core count with each result.
- Trusting a synthetic dataset. Generated images of uniform size and content decode unusually fast or slow. Use real files.
A measurement log
Keep a short table of results as you work. It shows whether each change helped and by how much, and it gives you a baseline for the parity checks later in the tutorial.
| Change | Images/s | Data wait | Note |
|---|---|---|---|
| Baseline, 0 workers | 130 | 85% | Decode is 80% of CPU time |
| 4 workers | 480 | 40% | Near-linear scaling |
| 4 workers plus draft decode | 900 | 5% | Model now limits speed |
Once data wait drops near zero, stop optimising the pipeline. Further gains must come from the model side.
Exercise
A loop measurement shows 70% data wait. Per-stage timing on one process shows read 0.2 ms, decode 3 ms, resize 3 ms per image, and the machine has 8 cores. Which stage would you attack first, what extra measurement would you take before trusting the result, and why would timing Image.open alone have misled you?
Show answer
Decode and resize each take about 46% of the 6.2 ms total, so both are candidates, and reducing decode size through draft mode would also shrink the resize input and help both. Before trusting the numbers, check the image size distribution and the median and p95 per-image times, and confirm whether the files were read warm or cold. Timing Image.open alone would have misled you because Pillow decodes lazily: open reads only the header, and the real decode cost appears later at convert or load. The decode cost would have been missing from the table and would have shown up in the resize stage, which would then look much more expensive than it really is.
Exercise
Your profiling loop reports compute time of 0.01 s per step on a GPU, but nvidia-smi shows the GPU busy for most of the epoch. What is the likely mistake in the loop, and how do you fix it?
Show answer
The loop probably does not call torch.cuda.synchronize() after the step. CUDA work is queued asynchronously, so the timer stops before the GPU finishes, and the remaining GPU time is charged to the next next(it) call as data wait. Add torch.cuda.synchronize() before reading the end time of the compute section.