Moving data
The GPU cannot see your std::vector. Getting data across the PCIe/NVLink link — and back — is half of writing a real CUDA program. This chapter shows the explicit path, then the shortcuts.
The explicit path#
Four calls do all the work:
cudaMalloc(&d_ptr, bytes); // device allocation
cudaMemcpy(d_ptr, h_ptr, bytes, cudaMemcpyHostToDevice); // copy in
cudaMemcpy(h_ptr, d_ptr, bytes, cudaMemcpyDeviceToHost); // copy out
cudaFree(d_ptr); // releaseHere is a complete vector addition, with checks and no magic:
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>
#define CUDA_CHECK(call) \
do { \
cudaError_t err_ = (call); \
if (err_ != cudaSuccess) { \
fprintf(stderr, "%s:%d: %s\n -> %s\n", __FILE__, __LINE__, \
#call, cudaGetErrorString(err_)); \
exit(EXIT_FAILURE); \
} \
} while (0)
__global__ void vectorAdd(const float* a, const float* b, float* c, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) c[i] = a[i] + b[i];
}
int main() {
const int n = 1 << 20;
const size_t bytes = n * sizeof(float);
// Host memory
float* h_a = (float*)malloc(bytes);
float* h_b = (float*)malloc(bytes);
float* h_c = (float*)malloc(bytes);
for (int i = 0; i < n; ++i) {
h_a[i] = 1.0f;
h_b[i] = 2.0f;
}
// Device memory
float *d_a, *d_b, *d_c;
CUDA_CHECK(cudaMalloc(&d_a, bytes));
CUDA_CHECK(cudaMalloc(&d_b, bytes));
CUDA_CHECK(cudaMalloc(&d_c, bytes));
// Host -> device
CUDA_CHECK(cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice));
CUDA_CHECK(cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice));
// Launch
int threads = 256;
int blocks = (n + threads - 1) / threads;
vectorAdd<<<blocks, threads>>>(d_a, d_b, d_c, n);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaDeviceSynchronize());
// Device -> host
CUDA_CHECK(cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost));
printf("n = %d\n", n);
printf("c[0] = %.1f\n", h_c[0]);
printf("c[%d] = %.1f\n", n - 1, h_c[n - 1]);
CUDA_CHECK(cudaFree(d_a));
CUDA_CHECK(cudaFree(d_b));
CUDA_CHECK(cudaFree(d_c));
free(h_a); free(h_b); free(h_c);
return 0;
}n = 1048576 c[0] = 3.0 c[1048575] = 3.0
The copy directions#
| Kind | Meaning |
|---|---|
cudaMemcpyHostToDevice | System RAM → GPU DRAM |
cudaMemcpyDeviceToHost | GPU DRAM → system RAM |
cudaMemcpyDeviceToDevice | GPU DRAM → GPU DRAM |
cudaMemcpyDefault | Infer from the pointers (requires unified addressing) |
cudaMemcpyDefault is the sane default on all modern systems: every allocation lives in one unified virtual address space, so the runtime can tell where a pointer belongs. It is not slower; it just has to look.
How fast is the link?#
Order-of-magnitude numbers for a desktop GPU:
- PCIe 4.0 ×16: ~25 GB/s each direction.
- PCIe 5.0 ×16: ~50 GB/s each direction.
- HBM on the GPU: ~1–3 TB/s.
- NVLink C2C (Grace Hopper/Blackwell): ~450 GB/s or more.
That gap is why data movement dominates many kernels. A kernel that reads 1 GB over PCIe spends about 40 ms just waiting for the copy, no matter how fast the math is. Keep data on the GPU across many kernels when you can.
Unified memory#
cudaMallocManaged allocates memory with a single pointer valid on both CPU and GPU:
float* data;
CUDA_CHECK(cudaMallocManaged(&data, bytes));
for (int i = 0; i < n; ++i) data[i] = 1.0f; // host touches pages first
vectorAdd<<<blocks, threads>>>(data, data, data, n);
CUDA_CHECK(cudaDeviceSynchronize());
printf("%f\n", data[0]); // host reads the result
CUDA_CHECK(cudaFree(data));No explicit copies. The driver migrates pages on demand: when the GPU touches a page, it moves to GPU memory; when the CPU touches it again, it moves back. This is unified memory, and it is available on every CUDA-capable system (with different levels of hardware support).
It is not free. On a PCIe system each migration is a page-sized copy, and a badly behaved kernel that bounces between CPU and GPU can be much slower than explicit copies. The usual pattern is:
- Allocate managed memory once.
- Initialise on the host.
- Prefetch to the GPU before the kernel.
- Run kernels.
- Prefetch back before the host reads.
int device = 0;
CUDA_CHECK(cudaMemPrefetchAsync(data, bytes, device)); // to GPU 0
kernel<<<blocks, threads>>>(data, n);
CUDA_CHECK(cudaMemPrefetchAsync(data, bytes, cudaCpuDeviceId)); // back to CPU
CUDA_CHECK(cudaDeviceSynchronize());cudaMemAdvise adds hints that survive migrations:
cudaMemAdvise(data, bytes, cudaMemAdviseSetReadMostly, device);
cudaMemAdvise(data, bytes, cudaMemAdviseSetPreferredLocation, device);On systems with full unified memory support, oversubscription is allowed: allocate more managed memory than the GPU has, and pages evict to the host as needed. Performance falls off a cliff when you rely on it, but the program does not crash.
Pinned host memory#
Ordinary malloc memory is pageable: the OS may move it or swap it out. The GPU's DMA engine cannot safely read pageable memory asynchronously, so cudaMemcpyAsync from pageable memory silently falls back to synchronous behaviour.
Pinned (page-locked) memory fixes that:
float* h_in;
CUDA_CHECK(cudaMallocHost((void**)&h_in, bytes)); // pinned, page-locked
CUDA_CHECK(cudaMemcpyAsync(d_in, h_in, bytes,
cudaMemcpyHostToDevice, stream));
// ...
CUDA_CHECK(cudaFreeHost(h_in));| API | Use |
|---|---|
cudaMallocHost((void**)&p, bytes) | Allocate pinned host memory |
cudaHostAlloc(&p, bytes, flags) | Pinned with options (mapped, portable, write-combined) |
cudaHostRegister(p, bytes, flags) | Pin an existing allocation |
cudaFreeHost(p) | Release pinned memory |
Pinned memory is a finite resource. Allocating gigabytes of it can starve the OS and slow the whole machine. Pin buffers you actually stream, not everything.
When the pointer could be anywhere#
With unified virtual addressing, you can ask the runtime what a pointer points at:
cudaPointerAttributes attr;
CUDA_CHECK(cudaPointerGetAttributes(&attr, ptr));
printf("type=%d device=%d host_ptr=%p device_ptr=%p\n",
attr.type, attr.device, attr.hostPointer, attr.devicePointer);This is how libraries accept "a pointer" without knowing whether it came from malloc, cudaMalloc, or cudaMallocManaged. You will also see cudaMemcpyDefault used for the same reason.
Choosing a path#
| Situation | Use |
|---|---|
| One-off script, simple data | cudaMallocManaged |
| Performance-sensitive, known access pattern | cudaMalloc + cudaMemcpy |
| Overlapping copy and compute | pinned memory + cudaMemcpyAsync + streams |
| Existing buffer from another library | cudaHostRegister or a device pointer |
| Multi-GPU | explicit device pointers + peer copies (Chapter 15) |
The mistakes everyone makes#
- Forgetting
cudaFree. Device memory is not reclaimed when a pointer goes out of scope. Long-running services leak until the GPU is out of memory. - Freeing too early.
cudaFreesynchronises, so it is safe — but freeing before the kernel has been enqueued is not. - Copying the wrong direction.
cudaMemcpyHostToDevicewith swapped arguments produces an error at best and nonsense at worst. UsecudaMemcpyDefaultif you are unsure. - Reading host memory in a kernel. Without unified memory or mapped/pinned memory, a host pointer is not valid on the device. The kernel may fault or read garbage.
- Assuming
cudaMemcpyis asynchronous. It is not, for host transfers. - Pinning everything. Page-locked memory is scarce.
Exercises#
- Replace the three
cudaMalloc/cudaMemcpypairs invector_add.cuwith onecudaMallocManaged. Delete the copy calls. Does the output change? - Time the explicit version with
cudaEvent(Chapter 12). How much of the total is the two host-device copies? - Allocate 1 GB of managed memory on a GPU with 8 GB and touch it from the host. What happens? Try the same with
cudaMalloc. - Change
cudaMemcpyHostToDevicetocudaMemcpyDeviceToHostin one call and run. What error do you get? - Use
cudaPointerGetAttributeson amallocpointer, acudaMallocpointer, and acudaMallocManagedpointer. Compareattr.type.