GPU by Example
7 / 16

Moving data

7 min readChapter 7 of 16

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:

CUDA C++
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);                                                 // release

Here is a complete vector addition, with checks and no magic:

vector_add.cuCUDA C++
#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;
}
Outputreference run
n = 1048576
c[0] = 3.0
c[1048575] = 3.0

The copy directions#

KindMeaning
cudaMemcpyHostToDeviceSystem RAM → GPU DRAM
cudaMemcpyDeviceToHostGPU DRAM → system RAM
cudaMemcpyDeviceToDeviceGPU DRAM → GPU DRAM
cudaMemcpyDefaultInfer 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.

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:

managed.cuCUDA C++
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.
CUDA C++
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:

CUDA C++
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:

pinned.cuCUDA C++
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));
APIUse
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:

CUDA C++
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#

SituationUse
One-off script, simple datacudaMallocManaged
Performance-sensitive, known access patterncudaMalloc + cudaMemcpy
Overlapping copy and computepinned memory + cudaMemcpyAsync + streams
Existing buffer from another librarycudaHostRegister or a device pointer
Multi-GPUexplicit 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. cudaFree synchronises, so it is safe — but freeing before the kernel has been enqueued is not.
  • Copying the wrong direction. cudaMemcpyHostToDevice with swapped arguments produces an error at best and nonsense at worst. Use cudaMemcpyDefault if 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 cudaMemcpy is asynchronous. It is not, for host transfers.
  • Pinning everything. Page-locked memory is scarce.

Exercises#

  • Replace the three cudaMalloc/cudaMemcpy pairs in vector_add.cu with one cudaMallocManaged. 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 cudaMemcpyHostToDevice to cudaMemcpyDeviceToHost in one call and run. What error do you get?
  • Use cudaPointerGetAttributes on a malloc pointer, a cudaMalloc pointer, and a cudaMallocManaged pointer. Compare attr.type.