Sub topic 13
Hardware-accelerated decoding and when it helps
This chapter assumes you have read the earlier chapters on decoding cost, draft-mode decoding, and parallel loading. It also assumes you know basic PyTorch and have a CUDA GPU if you want to run the code. The question here is whether you should move JPEG decoding off the CPU, and what it costs you if you do.
Why decoding moves to the GPU
On a typical training machine the CPU decodes JPEGs with libjpeg or libjpeg-turbo. Each DataLoader worker decodes one image at a time. When your GPU is fast and your CPU core count is limited, the workers can't keep up. The model then waits for data, and you can see this in the profiling numbers from the earlier chapter: data-wait time is high and GPU utilisation is low.
Hardware-accelerated decoding moves part or all of the JPEG decode to the GPU. NVIDIA's nvJPEG library is the usual route. It has several backends:
| Backend | Where the work runs | Notes |
|---|---|---|
| Hybrid | Huffman decoding on the CPU, the rest on GPU CUDA cores | Still uses CPU time for entropy decoding |
| GPU (CUDA) | Huffman decoding and the rest on CUDA cores | Best for large images and batches |
| Hardware engine | Dedicated JPEG decoder block on the chip | Present on A100 and H100 class data-centre GPUs. It leaves CUDA cores free for the model |
You rarely pick the backend by hand. The libraries below choose one based on image size, batch size, and the GPU you have.
What happens inside a JPEG decode
JPEG decoding has three main steps.
- Entropy decoding. Huffman-coded bits become quantised coefficients. This step is serial, because each symbol's position depends on the one before it.
- Inverse transform. The inverse discrete cosine transform (IDCT) turns coefficients into pixel blocks. This is highly parallel.
- Colour conversion and upsampling. YCbCr becomes RGB, and subsampled chroma planes are expanded. This is also parallel.
GPUs are good at steps 2 and 3, and weak at step 1 for a single image. That explains the pattern in practice: GPU decoding pays off for large images and for batches, and it pays off less for small images, where launch overhead and the serial step dominate.
The diagram shows a point that matters for bandwidth. In the GPU path you copy compressed bytes, which are typically 5 to 15 times smaller than decoded pixels. You also skip a full-resolution intermediate on the CPU. But the GPU must then hold the full-resolution decoded image in memory before you resize it.
Decoding on the GPU with torchvision
torchvision.io.decode_jpeg accepts device="cuda". It takes the raw file bytes as a one-dimensional uint8 tensor and returns a 3 x H x W uint8 tensor on the GPU. Recent torchvision versions also accept a list of byte tensors and decode them as a batch, which is faster than a loop of single calls because nvJPEG can overlap the work.
import time
import torch
import torch.nn.functional as F
from torchvision.io import ImageReadMode, decode_jpeg, read_file
def gpu_load_batch(paths, size=(224, 224)):
"""Decode a list of JPEG files on the GPU and resize to a fixed size.
Returns a uint8 tensor of shape (B, 3, H, W) on the CUDA device.
"""
datas = [read_file(p) for p in paths] # raw bytes only, no decoding yet
images = decode_jpeg(datas, device="cuda", mode=ImageReadMode.RGB)
out = []
for im in images:
x = im.unsqueeze(0).float()
x = F.interpolate(
x, size=size, mode="bilinear", align_corners=False, antialias=True
)
out.append(x.round().clamp(0, 255).to(torch.uint8))
return torch.cat(out)
def time_gpu_load(paths, repeats=5):
gpu_load_batch(paths) # warm-up: loads nvJPEG and allocates buffers
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(repeats):
gpu_load_batch(paths)
torch.cuda.synchronize() # GPU work is asynchronous; wait before stopping the clock
dt = (time.perf_counter() - t0) / repeats
print(f"{len(paths) / dt:.0f} images/s")Three details in this code are easy to get wrong.
- Warm up first. The first call initialises nvJPEG and allocates memory, so it is far slower than later calls. Timing it gives a misleading result.
- Synchronise before reading the clock. CUDA calls return before the work finishes. Without
torch.cuda.synchronize()you measure only the launch time. - Pass
mode=ImageReadMode.RGB. Greyscale and CMYK files otherwise come back with a different channel count, and your batch stack fails.
Another route: NVIDIA DALI
NVIDIA DALI is a data-loading library that builds the whole pipeline (read, decode, resize, normalise) as a graph and runs it with its own scheduler and prefetch queues. It uses the hardware decoder engine when the GPU has one. You get overlap between reading, decoding, and training without writing the threading yourself. The cost is that your preprocessing is now expressed in DALI operators rather than PIL or torchvision, so you need to re-check that the results match. DALI is worth considering when you have a heavy CPU-bound pipeline and a data-centre GPU. It is less attractive for a small project where the plain DataLoader is already fast enough.
When it helps and when it does not
GPU decoding is not an automatic win. Use these criteria.
| Situation | Likely outcome |
|---|---|
| Few CPU cores per GPU, large JPEGs (for example, 12-megapixel photos) | Large gain. The CPU cannot decode fast enough |
| Data-centre GPU with a hardware decoder engine, large batches | Large gain, and CUDA cores stay free for the model |
| Small images (for example, 256 pixels on a side) | Small gain or a loss. Launch overhead dominates |
| CPU draft-mode decoding already shrinks work by 4x to 8x | The CPU path may match or beat the GPU path |
| Training is already GPU-bound | No gain. Decoding competes with the model for the same chip |
| Mostly PNG, WebP, or TIFF files | Not supported by nvJPEG. Convert the files or stay on the CPU |
| Inference server with latency targets and small batches | Mixed. Measure with the real batch size |
The draft-mode row deserves attention. Draft decoding reduces the work in the IDCT stage by decoding at 1/2, 1/4, or 1/8 scale. GPU decoding generally produces the full-resolution image first. For a dataset with large photos that you resize to 224 pixels, a tuned CPU pipeline with Image.draft and several workers can be competitive. Compare them on your data.
Failure modes and edge cases
- GPU memory pressure. A 24-megapixel image decodes to about 72 MB as
uint8RGB. A batch of 64 such images needs over 4 GB before resizing. Decode and resize in smaller groups if memory is tight. - Unsupported files. Progressive JPEGs, unusual subsampling, CMYK, and corrupt files can fail on the GPU path even when PIL reads them. Catch the exception and fall back to the CPU decoder for that file instead of aborting the epoch.
- Compute contention. On a GPU without a hardware decoder engine, the decode kernels share CUDA cores with the model. If training is already saturating the GPU, you move the bottleneck instead of removing it.
- Output differences. The IDCT implementation and the chroma upsampling method differ between libjpeg-turbo and nvJPEG. Pixel values can differ by a few intensity levels. This is usually harmless for training, but it matters if you compare against a model that was validated with CPU-decoded inputs. The parity chapter covers how to measure this.
- Resize semantics.
F.interpolatewithantialias=Trueapproximates PIL's behaviour but is not bit-identical. Without antialiasing, a large downscale produces aliasing that PIL's resize avoids.
A practical decision procedure
- Profile the pipeline and confirm that decoding is the dominant stage, and that the GPU is waiting for data.
- Apply the cheaper CPU measures first: draft mode, more workers, persistent workers, and prefetching.
- If the GPU still waits, try batched GPU decoding on a sample of your real files, with warm-up and synchronisation in the timing.
- Check peak GPU memory with
torch.cuda.max_memory_allocated(). - Run the parity checks against the reference pipeline before you adopt it.
Exercise
Your training job runs on a GPU with no hardware JPEG engine. The model already keeps the GPU at 95% utilisation, and the dataset is 256x256 JPEGs. A colleague proposes moving decoding to the GPU to "free the CPU". Should you adopt it? Give two reasons.
Show answer
Probably not. First, at 95% utilisation the GPU is the bottleneck, and nvJPEG decode kernels would compete with the model for the same CUDA cores, so total throughput would not improve and could drop. Second, 256x256 images are small, so the serial entropy-decoding step and per-call launch overhead dominate, and the CPU workers decode them cheaply anyway. Measure first, but the evidence points to staying on the CPU.
Exercise
Why must you call torch.cuda.synchronize() before stopping the timer when you benchmark GPU decoding, and why should the first call be excluded from the measurement?
Show answer
CUDA operations are asynchronous: the Python call returns once the work is queued, so without synchronize() the timer measures only launch time rather than completion. The first call is excluded because it initialises nvJPEG and allocates device buffers, which makes it much slower than steady-state calls.