Sub topic 9
Moving batches to the GPU: pinned memory and asynchronous copies
This chapter assumes you can write a PyTorch Dataset and DataLoader, know what a uint8 (B, 3, H, W) batch looks like, and have a CUDA GPU available. Earlier chapters covered decoding, resizing, worker processes and collation. Here we follow the batch after the workers finish, across the bus to the GPU.
Why the copy matters
A batch is built in the CPU's main memory, called host memory. The model runs in the GPU's own memory, called device memory. Every batch has to cross the PCIe bus (or a similar link) between them. The cost is simple to estimate: bytes divided by bandwidth.
A batch of 64 images at 3 x 224 x 224 takes these sizes:
| Data type | Bytes per batch | Size |
|---|---|---|
| uint8 | 64 x 3 x 224 x 224 | about 9.6 MB |
| float32 | 4 x the uint8 size | about 38.5 MB |
At a practical 12 GB/s, the uint8 batch takes under 1 ms and the float32 batch takes about 3 ms. That looks small. It becomes large when the GPU is fast, when the images are bigger, or when the copy blocks the CPU and the GPU sits idle. Two tools reduce this cost: pinned memory and asynchronous copies. Sending uint8 instead of float32, as shown in the earlier chapter on operation order, is the third.
Pageable and pinned memory
Ordinary host memory is pageable. The operating system may move pageable memory to disk or relocate it at any time. The GPU's copy engine, which is the hardware unit that does DMA (direct memory access) transfers, needs a fixed physical address. So when you copy from pageable memory, the CUDA driver does extra work:
- It allocates a temporary pinned staging buffer.
- It copies your data from pageable memory into that buffer.
- It starts the DMA transfer from the staging buffer to the GPU.
Pinned memory (also called page-locked memory) is host memory that the operating system promises not to move. The GPU can read it directly, so step 2 disappears. Pinned memory also allows truly asynchronous copies, as the next section shows.
Pinned memory has a price. It is a limited resource, because the operating system cannot swap it out. Allocating it is also slower than allocating ordinary memory. If you pin too much, other programs on the machine run short of memory. This is why you should not pin every tensor, only the batches that you copy to the GPU repeatedly.
pin_memory in DataLoader
The simplest way to get pinned batches is pin_memory=True in the DataLoader. PyTorch then starts a separate thread in the main process. The thread takes each finished batch from the worker queue, copies it into pinned memory, and puts it in a second queue for your training loop.
import torch
from torch.utils.data import DataLoader, Dataset
class RandomImages(Dataset):
def __len__(self):
return 1024
def __getitem__(self, i):
return torch.randint(0, 256, (3, 224, 224), dtype=torch.uint8)
if __name__ == "__main__":
loader = DataLoader(
RandomImages(),
batch_size=64,
num_workers=2,
pin_memory=True,
persistent_workers=True,
)
batch = next(iter(loader))
print(batch.is_pinned()) # TrueWorkers cannot return pinned tensors themselves, because pinned memory does not carry over to another process in a useful way. The pin thread in the main process does the copy. This is one extra memcpy per batch, but it runs on a background thread while your GPU computes the previous step.
If your collate_fn returns a custom object, such as a dataclass or a tuple subclass, pin_memory=True may not pin its tensors. PyTorch pins tensors, and tuples, lists and dicts of tensors. For any other type, give the class a pin_memory() method. The loader calls it for you.
import torch
class Batch:
def __init__(self, images, sizes):
self.images = images
self.sizes = sizes
def pin_memory(self):
self.images = self.images.pin_memory()
self.sizes = self.sizes.pin_memory()
return selfAsynchronous copies with non_blocking
A call to tensor.to("cuda") is synchronous with respect to the host by default. Python waits until the copy has finished before it runs the next line. With non_blocking=True, the call returns as soon as the copy is queued on the GPU's current CUDA stream. A stream is an ordered queue of GPU work.
x = batch.to("cuda", non_blocking=True)Two facts make this safe and useful:
- Work on one stream runs in order. A kernel launched after the copy on the same stream waits for the copy to finish, so you do not need to synchronise before
model(x). - The copy is only truly asynchronous when the source is pinned. From pageable memory,
non_blocking=Truedoes not give you overlap, because the driver still has to stage the data first.
So pin_memory=True and non_blocking=True belong together. Either one alone gives little benefit.
Overlap in time
With both settings, the CPU can queue the copy for batch N+1 while the GPU is still computing on batch N. The copy engine and the compute units are separate hardware, so they can work at the same time.
For this overlap to happen, the loop must not call anything that forces the host to wait. Common culprits are loss.item(), print(loss), and .cpu() on every step. Each one blocks until the GPU finishes, which empties the queue and removes the overlap.
A prefetching loop
DataLoader only prefetches on the CPU side. You can go further and copy the next batch to the GPU while the current one is computing. This version uses a separate stream for the copy and makes the compute stream wait for it correctly.
import torch
class CudaPrefetcher:
def __init__(self, loader, device="cuda"):
self.loader = loader
self.device = device
self.stream = torch.cuda.Stream()
def __iter__(self):
it = iter(self.loader)
nxt = self._load(it)
while nxt is not None:
# The compute stream must wait for the copy stream.
torch.cuda.current_stream().wait_stream(self.stream)
batch = nxt
# Tell the allocator the tensor is used on the compute stream.
batch.record_stream(torch.cuda.current_stream())
nxt = self._load(it)
yield batch
def _load(self, it):
try:
cpu_batch = next(it)
except StopIteration:
return None
with torch.cuda.stream(self.stream):
return cpu_batch.to(self.device, non_blocking=True)Three details in this code matter:
wait_streammakes the compute stream wait until the copy stream has finished its queued work. Without it, the model could read a half-copied batch.record_streamtells PyTorch's caching allocator that the tensor is also used on the compute stream. Without it, the allocator could reuse the memory while the compute stream still reads it, because the tensor was allocated on the copy stream.- The loader must yield a single tensor here. For tuples, apply the same calls to each tensor.
Many pipelines do not need this class. If the GPU step is long compared with the copy, the simple non_blocking=True loop already hides the transfer. Add a prefetcher only after profiling shows the copy on the critical path.
Common mistakes
- Pinning float32 batches. Pinned memory speeds the copy but does not shrink it. Keep batches in uint8 and convert on the GPU.
- Reusing a pinned buffer too early. If you write to a pinned tensor while an asynchronous copy from it is still in flight, the GPU may copy the new data. The
DataLoaderallocates a new pinned batch each time, so it avoids this. If you manage your own reusable buffers, record a CUDA event after the copy and wait on it before you overwrite the buffer. - Calling
.pin_memory()inside__getitem__. This pins one image at a time in the worker, which is slow and wasted, since the batch is rebuilt in the main process anyway. - Using too many workers and too much prefetch. Each queued batch holds memory. With
num_workers=8andprefetch_factor=4there can be 32 batches waiting, plus the pinned queue. - Expecting a speed-up on a CPU-only run or on a slow loader. If workers cannot produce batches fast enough, the GPU waits for data and the copy is not the bottleneck.
Measuring the copy
Time GPU work with CUDA events, not with time.perf_counter() alone, because GPU calls return before the work is done.
import torch
def time_copy(batch, pinned, repeats=50):
src = batch.pin_memory() if pinned else batch
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
torch.cuda.synchronize()
start.record()
for _ in range(repeats):
src.to("cuda", non_blocking=True)
end.record()
torch.cuda.synchronize()
return start.elapsed_time(end) / repeats # milliseconds
if __name__ == "__main__":
data = torch.randint(0, 256, (64, 3, 224, 224), dtype=torch.uint8)
print(f"pageable: {time_copy(data, False):.3f} ms")
print(f"pinned: {time_copy(data, True):.3f} ms")On most machines the pinned copy is clearly faster, often by a factor of two or more. The exact numbers depend on the bus and the driver. Run it on your own hardware before you decide how much effort the copy deserves.
For a full view, use torch.profiler and look at whether Memcpy HtoD operations overlap with kernels in the trace. If the copy shows up as a gap before every forward pass, the loop is still blocking.
Decision guide
| Situation | Action |
|---|---|
| Training from a `DataLoader` on a CUDA GPU | `pin_memory=True` and `.to(device, non_blocking=True)` |
| Batches are float32 | Move conversion to the GPU and send uint8 |
| Profile shows the copy before each step | Try a prefetcher with a separate stream |
| Custom batch class | Add a `pin_memory()` method |
| Host memory is tight | Lower `num_workers`, `prefetch_factor`, or batch size before you stop pinning |
| CPU inference of a single image | Skip pinning, there is no GPU copy to hide |
Exercise
A training loop calls x = batch.to("cuda", non_blocking=True), but the DataLoader was created with pin_memory=False. The profiler shows no overlap between the copy and the GPU compute. Why, and what two changes would you make to get the overlap?
Show answer
The source tensor is pageable, so the driver first copies it to a staging buffer and the transfer cannot run asynchronously, even though non_blocking=True is set. Set pin_memory=True in the DataLoader so batches are pinned, and keep non_blocking=True on the .to() call. Also remove calls such as loss.item() from every step, because they make the host wait for the GPU and remove the overlap. Check the result with batch.is_pinned().
Exercise
In the CudaPrefetcher, you remove the batch.record_stream(torch.cuda.current_stream()) line. The code still runs and the loss looks normal. What risk have you introduced?
Show answer
The batch was allocated while the copy stream was active, so PyTorch's caching allocator associates its memory with that stream only. Once the tensor is freed on the compute stream's side, the allocator may reuse the memory for a new copy while an earlier kernel still reads it. This can corrupt data silently, and it appears at random, which is why the loss can still look normal. record_stream marks the tensor as in use on the compute stream.