Sub topic 9
Moving Batches to the GPU: Pinned Memory and Asynchronous Copies
Prerequisites and the transfer path
This chapter assumes that you know basic PyTorch tensors, Dataset, and DataLoader, and that your images already have a consistent tensor shape.
A training batch usually moves through these locations:
- Image files are decoded into ordinary host memory, which is the system RAM used by the CPU.
- The
DataLoaderassembles several samples into one CPU tensor. - The batch is copied from host memory to device memory, which is usually GPU memory.
- The model reads the batch from device memory.
The host-to-device copy can limit throughput even when decoding and batching are fast. The goal is to overlap this copy with GPU computation instead of making the GPU wait for every batch.
Pinned memory
Pinned memory, also called page-locked memory, is CPU memory that the operating system will not move to disk or remap while a transfer is in progress. A GPU can copy from pinned memory more efficiently than from ordinary pageable memory.
Set pin_memory=True on the DataLoader:
import torch
from torch.utils.data import DataLoader, TensorDataset
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
images = torch.randint(0, 256, (1024, 3, 224, 224), dtype=torch.uint8)
labels = torch.randint(0, 10, (1024,))
dataset = TensorDataset(images, labels)
loader = DataLoader(
dataset,
batch_size=64,
shuffle=True,
num_workers=2,
pin_memory=(device.type == "cuda"),
)
for cpu_images, cpu_labels in loader:
gpu_images = cpu_images.to(device, non_blocking=True)
gpu_labels = cpu_labels.to(device, non_blocking=True)
gpu_images = gpu_images.float().div_(255.0)
# Feed gpu_images and gpu_labels to the model.pin_memory=True asks the loader's memory-pinning thread to place returned tensors in pinned memory. It does not pin the image files, and it does not move data to the GPU.
Asynchronous copies and overlap
The non_blocking=True argument allows PyTorch to enqueue a transfer and return before the copy has finished when the source tensor is pinned and the destination supports asynchronous transfers. The GPU can then begin working on the current batch while the CPU prepares the next batch.
This flag does not make every copy asynchronous. Copies from ordinary CPU memory may still block. Also, using a tensor before its transfer has completed causes the relevant stream to wait. PyTorch normally manages this ordering for operations submitted to the same CUDA stream.
Use synchronization when measuring transfer time. Otherwise, the timer may stop before the GPU has completed the queued operation.
Choosing what to transfer
Keep image batches in compact uint8 form on the CPU when possible. Sending uint8 values transfers one quarter as many bytes as sending float32 values. Convert to floating point and normalise after the copy, preferably on the GPU.
For a batch with shape (B, 3, H, W), place channel-wise mean and standard deviation tensors on the GPU once. Then apply them to each transferred batch. Ensure the model and all preprocessing tensors use the same device and compatible data types.
Common errors
- Calling
.to("cuda")withoutnon_blocking=Trueprevents the requested asynchronous behavior. - Using
non_blocking=Truewithout pinned source memory often gives no useful overlap. - Pinning every intermediate tensor can increase CPU memory pressure.
- Timing without
torch.cuda.synchronize()produces misleading results. - Copying labels or metadata unnecessarily wastes transfer bandwidth.
Exercise
Why are pin_memory=True and non_blocking=True separate settings?
Show answer
pin_memory=True prepares CPU tensors for efficient asynchronous transfer. non_blocking=True asks the device copy to be enqueued without making the calling CPU thread wait when the hardware and memory allow it.