cudaMemcpy

Copy memory between the CPU and the GPU

Syntax

cpp
1
cudaError_t cudaMemcpy(void *dst, const void *src, size_t count, cudaMemcpyKind kind);

Parameters

dst
Destination address (device or host).
src
Source address (device or host).
count
Number of bytes to copy, not elements.
kind
Direction of the copy, one of the cudaMemcpyKind values below.

Returns

cudaSuccess
The copy finished.
cudaErrorInvalidValue
"invalid argument": for example count larger than the device allocation, or kind not matching the pointers.
cudaErrorInvalidMemcpyDirection
kind is not a valid cudaMemcpyKind value.
errors from earlier launches
Like most runtime calls, it can also return an error left by an earlier asynchronous kernel, such as cudaErrorIllegalAddress.
cudaMemcpyKind values
KindValueCopies
cudaMemcpyHostToHost0CPU memory to CPU memory
cudaMemcpyHostToDevice1CPU memory to GPU memory (upload inputs)
cudaMemcpyDeviceToHost2GPU memory to CPU memory (download results)
cudaMemcpyDeviceToDevice3GPU memory to GPU memory
cudaMemcpyDefault4Direction inferred from the pointers (needs unified addressing, which every 64-bit system has)

How it works

It waits for earlier kernels

A copy on the default stream starts only after the kernels launched before it finish. A device-to-host copy after a kernel therefore always sees the finished result, without an explicit cudaDeviceSynchronize().

Copy part of a buffer with pointer arithmetic

cudaMemcpy(h + 10, d + 10, 5 * sizeof(float), cudaMemcpyDeviceToHost) copies elements 10 to 14. The offset is in elements because the pointers are typed; count is still in bytes.

Overlapping copies with work needs cudaMemcpyAsync

To copy while a kernel runs, use cudaMemcpyAsync on a non-default stream with pinned host memory from cudaMallocHost.

Example

Press Run to execute this on a real NVIDIA GPU in the playground.

Example: upload, compute, download
main.cu
123456789101112131415161718192021222324252627282930313233343536373839
#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 (%s)\n", __FILE__, __LINE__,       \
                    cudaGetErrorString(err_), cudaGetErrorName(err_));    \
            exit(1);                                                      \
        }                                                                 \
    } while (0)

__global__ void square(float *x, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) x[i] = x[i] * x[i];
}

int main() {
    const int n = 8;
    const size_t bytes = n * sizeof(float);
    float h[n] = {1, 2, 3, 4, 5, 6, 7, 8};

    float *d;
    CUDA_CHECK(cudaMalloc(&d, bytes));
    CUDA_CHECK(cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice));   // dst first

    square<<<1, 32>>>(d, n);
    CUDA_CHECK(cudaGetLastError());

    // Waits for square() to finish, then copies the results back.
    CUDA_CHECK(cudaMemcpy(h, d, bytes, cudaMemcpyDeviceToHost));
    for (int i = 0; i < n; i++) printf("%.0f ", h[i]);
    printf("\n");

    CUDA_CHECK(cudaFree(d));
    return 0;
}
Output on an NVIDIA T4
1 4 9 16 25 36 49 64

Common mistakes

Source and destination swapped

cudaMemcpy(h, d, bytes, cudaMemcpyHostToDevice) has the direction and the pointers disagreeing. On our T4 this returns "invalid argument" and copies nothing.

Elements instead of bytes

cudaMemcpy(d, h, n, ...) copies n bytes, a quarter of a float array. The rest of the buffer stays uninitialised.

Copying a struct that contains device pointers

Copying a struct copies the pointer values, not what they point to. Each array inside it needs its own cudaMalloc and cudaMemcpy, or use cudaMallocManaged.

FAQ

Is cudaMemcpy blocking?

Yes, in normal use. It returns after the copy completes, and it does not start until earlier work on the default stream is done. Use cudaMemcpyAsync with pinned memory and a stream for non-blocking copies.

Do I need cudaDeviceSynchronize before cudaMemcpy?

Not on the default stream: the copy already waits for earlier kernels. Synchronizing first is still useful while debugging, because it reports kernel errors separately from copy errors.

What does cudaMemcpyDefault do?

It lets the runtime work out the direction from the pointer values. It requires unified virtual addressing, which every 64-bit platform supported by current CUDA has.