Reaching 99% GPU Utilization

Understanding and improving the data-loading pipeline.

The GPU utilization column in nvidia-smi.
The GPU utilization column in nvidia-smi.

If you study deep learning, you'll soon encounter nvidia-smi. On the right is GPU-Util, an indication of whether the GPU is busy. The higher it is, the more consistently our worker is being given computation. At university I didn't think much about it, because nobody had explained its importance. Making good use of the GPU is a starting point for an efficient training pipeline.

A cartoon dismissing optimization.
“As long as it trains, that’s enough, right?”

I thought that way myself only a month ago. This post explains why I changed my mind and some methods I tried. I'm grateful to the mentor who taught me things I hadn't learned at school.


Why improve utilization?

An illustration accompanying the question of model quality.

Why not just train a good model? Fair enough, but what counts as good?

We can compare models with classification accuracy, SQuAD or GLUE for NLP, and Fréchet Inception Distance for GANs. These compare existing models; they don't tell us we've found the best possible one. The solution space is far more complex than we can visualize.

An illustrative optimization landscape.

There are many local minima in that high-dimensional space. An optimizer doesn't guarantee the best solution. We should begin by accepting that the model we trained is probably not the best possible model.

An illustration of repeated analysis and experimentation.

We can increase our chances through analysis, trial, and error: find what is wrong with a result, understand why, and try again. Here, error means a reason the result is poor, not a syntax error. We have to keep trying. Perhaps that's why hyperparameter tuning sometimes feels like human labor. If AI gets better at that, what will we do?

Whoever conducts the experiments, more attempts require less time per training run. An efficient pipeline keeps the GPU from waiting.

The growth of language-model parameter counts at the time of the original post.

The cost of wasted time grows with the model and dataset. In January 2021, GPT-3's 175 billion parameters stood out, setting aside the recently announced trillion-parameter Switch model. At that scale, poor utilization is expensive. As an idealized illustration, if productive computation alone determines the schedule, halving useful GPU time could turn one month into two. Utilization is not, by itself, a universal throughput formula.

A busy GPU during training.

And honestly, seeing the GPU busy makes me happy. Perhaps that's an engineer's idea of fun.


The training pipeline

Prepare on the CPU. Train on the GPU.
01CPU · prepareRead → preprocess → assemble a batch
02GPU · trainForward pass → loss → backpropagation
A simplified division of work, not a measured timing diagram. Original source image ↗

There are two broad parts:

  1. Data work on the CPU: read from disk, preprocess, form a batch.
  2. Training on the GPU: forward pass, loss, backpropagation.

Both need attention for a fully busy GPU. This post focuses on the first. For GPU-side work, see this PyTorch multi-GPU article.

A reference illustration about multi-GPU training.

PyTorch multi-GPU training

A reference article about training with multiple GPUs in PyTorch.

medium.com


How data reaches the GPU

We're optimizing everything before the batch reaches the device. How does it get there?

From a read request to a GPU batch
01User codeRequest a file read
02Kernel / filesystemRead data from storage into memory
03Memory → GPUReturn to user code; prepare and transfer the batch
Simplified read path. User mode and kernel mode describe CPU execution; they are not separate hardware devices. Original source image ↗

User and kernel modes describe CPU execution states. File-system I/O handles the read, involving transitions between them. In the simplified diagram:

  1. Code requests a read in user mode.
  2. Execution enters kernel mode.
  3. The system requests the disk data.
  4. The result becomes available in memory and execution returns to user mode.
  5. Data in memory is transferred to the GPU.

Two cases matter:

  • The whole dataset fits in memory.
  • It doesn't.

Disk-to-memory work can be much slower than preparing an already resident batch. It can therefore become the bottleneck.

CPU statistics with a memory-resident dataset and with repeated disk loading.
Left: the dataset fits in memory. Right: it does not. The labels say “all data loaded into memory” and “not all data loaded into memory.” In this example, repeated loading corresponds to more kernel time (sy); us denotes user-mode time.

In these experiments, the second case showed much more system time. Repeatedly bringing data from disk left the GPU waiting. That observation helped me locate the bottleneck in this setup.


How a batch is trained

The three stages of a batch: disk read, CPU preparation, and GPU training.

A batch goes through three stages:

  1. Disk to memory.
  2. CPU preprocessing and batch construction.
  3. GPU training and a weight update.

Durations vary by setup. The original diagram leaves out memory-to-GPU transfer, treating PCIe as relatively fast, around 15 GB/s in the example.

Without overlap, training waits for preparation
Batch AReadPrepareTrain
Batch BReadPrepareTrain
The GPU is idle during each batch’s Read and Prepare stages.
Schematic sequence only. Block widths do not represent measured durations. Original source image ↗

If all three happen serially, the GPU waits through stages one and two after finishing each update. The objective becomes simple:

Have the next batch ready before the current GPU update ends

Now we can look at ways to achieve that.


Improving data loading

1. Multiprocess loading and prefetching

Different batches can occupy the pipeline at the same time
CPU workers

Prepare

Batch CBatch DBatch E
Ready queue

Hold next batch

Batch BBatch CBatch D
GPU

Train

Batch ABatch BBatch C
Preparation can overlap with training.
Schematic batches. The animation shows progression, not measured timings or a speedup.

While one batch is on the GPU, another process prepares the next. In practice, workers put prepared batches into a shared queue, and the training process takes them out. Preparing them ahead of time is prefetching.

from torch.utils.data.dataloader import DataLoader

train_loader = DataLoader(dataset=train_set,
                              num_workers=4,  # 사용할 Process의 수
                              batch_size=512,
                              persistent_workers=True)

PyTorch's DataLoader makes this easy through num_workers. Tune the worker count to the machine rather than assuming more is always better. My machine had twelve cores available, so I could try counts up to twelve.

2. Keep data in a compact type

A comparison of compact image data and floating-point input.
Float32 occupies four times the bytes of uint8. That is a storage-size comparison, not a measured fourfold transfer-speed improvement.

The model in this example uses float32, while ordinary image values can be stored as uint8, integers from 0 to 255. Float32 uses four times the bytes. Keeping images compact until near the model input can reduce memory and transfer work; normalize and convert when needed. The byte ratio does not establish a fixed time ratio.

With a dataset that fit in memory, these methods let me reach 99% utilization in a CIFAR-10 experiment. For a larger dataset that didn't fit, they weren't enough, because disk-to-memory loading remained slow.

CPU statistics under the larger-than-memory workload.

The high system-time proportion accompanied the repeated loading requests. The next batch wasn't ready before the GPU finished. To reduce disk work, we could keep part of the data in memory and reuse it. HDF5 chunks offer one way.

3. Chunk-cache hits

The hierarchical organization of an HDF5 file.

HDF5 is a format for storing large, hierarchically organized datasets. It can look rather like a directory tree.

Contiguous and chunked HDF5 dataset layouts.

A layout maps a multidimensional dataset onto a file:

  • Contiguous: flatten the dataset into one continuous region, similar to an array's memory layout.
  • Chunked: divide it into blocks that can be read and written independently.
import h5py

celebA = h5py.File(DATA_DIR, 'w', rdcc_nslots=11213, rdcc_nbytes=1024**3, rdcc_w0=1)

celebA.create_dataset('images',
                       data=batch_images,
                       dtype=np.uint8,
                       chunks=(100, 3, 217, 178),  # 11 MB : Chunk Size
                       maxshape=(None, 3, 218, 178))
                                      
celebA.create_dataset('labels',
                       data=labels_h5[:size],
                       dtype=np.uint8,
                       chunks=(20000,))

Python's h5py library supports this. See its file documentation.

File Objects — h5py 3.1.0 documentation

Parameters: name – Name of file (bytes or str), or an instance of h5f.FileID to bind to an existing file identifier, or a file-like object (see Python file-like objects). mode – Mode in which to open file; one of (“w”, “r”, “r+”, “a”,

docs.h5py.org

A later access finding data in an already cached chunk.

The idea is:

  1. Accessing an item brings its chunk into the cache.
  2. If a later item is in a cached chunk, it can be read there instead of loading from disk again.

I call this a chunk hit because it resembles a cache hit. Tuning the chunk cache can substantially improve utilization in a suitable workload.

4. Batch echoing

Batch echoing reuses a loaded batch for more than one update.

Batch echoing uses a batch on the GPU more than once. Does that reduce randomness? Yes. That's the tradeoff: less loading and potentially faster updates, but more reuse of the same examples.

I tried to preserve some variation by:

  1. Loading 512 examples onto the GPU.
  2. Splitting them into batches A and B of 256.
  3. Updating on each.
  4. Shuffling the same 512 examples.
  5. Splitting them into new batches C and D.
  6. Updating on each again.

That reuses the large batch twice with different groupings. It doesn't create new independent data, but I hoped it would retain some randomness. There are likely more creative approaches.


The lesson

The most important part isn't a particular trick. It's learning to diagnose and resolve a bottleneck:

  1. Develop a feel for hardware speed and recognize something is slow.
  2. Form a hypothesis and locate the cause.
  3. Find a method that addresses that cause.
  4. Try it.

Tools such as top, htop, and atop can help. Don't inspect aimlessly: a hypothesis narrows the search. That problem-solving process is the lesson I want readers to take away.

My internship had kept me too busy to write recently. I hope to post more often. Happy building!