如何为cudaMemAdviseSetPreferredLocation指定GPU ID

时间:2016-12-09 10:52:45

标签: cuda

尝试将托管内存的首选位置设置为GPU#0时,我一直收到“无效设备序号”:

CUDA_ERR_CHECK(cudaMemAdvise(deviceMemoryHeap.pool, size,
    cudaMemAdviseSetPreferredLocation, 0));

唯一有效的是cudaCpuDeviceId。那么,如何指定GPU ID?

编辑添加一个简单示例:

#define CUDA_ERR_CHECK(x)                                  \
    do { cudaError_t err = x; if (err != cudaSuccess) {    \
        fprintf(stderr, "CUDA error %d \"%s\" at %s:%d\n", \
        (int)err, cudaGetErrorString(err),                 \
        __FILE__, __LINE__);                               \
        exit(1);                                           \
    }} while (0);

#include <cstdio>

template<typename T>
__global__ void kernel(size_t* value)
{
    *value = sizeof(T);
}

int main()
{
    size_t size = 1024 * 1024 * 1024;

    size_t* managed = NULL;
    CUDA_ERR_CHECK(cudaMallocManaged(&managed, size, cudaMemAttachGlobal));
    CUDA_ERR_CHECK(cudaMemAdvise(managed, size,
        cudaMemAdviseSetPreferredLocation, 0));
    kernel<double><<<1, 1>>>(managed);
    CUDA_ERR_CHECK(cudaGetLastError());
    CUDA_ERR_CHECK(cudaDeviceSynchronize());
    CUDA_ERR_CHECK(cudaFree(managed));
    size_t* memory = NULL;
    CUDA_ERR_CHECK(cudaMalloc(&memory, size));
    kernel<double><<<1, 1>>>(memory);
    CUDA_ERR_CHECK(cudaGetLastError());
    CUDA_ERR_CHECK(cudaDeviceSynchronize());
    CUDA_ERR_CHECK(cudaFree(memory));

    return 0;
}

引发错误:

$ make
nvcc -arch=sm_30 managed.cu -o managed
$ ./managed 
CUDA error 10 "invalid device ordinal" at managed.cu:24

CUDA 8.0

我的目标是摆脱巨大的cudaLaunch调用延迟,这只发生在托管内存内核的情况下:

cudaLaunch latency in case of argument in managed memory

1 个答案:

答案 0 :(得分:4)

错误似乎源于缺少设备功能。正如cudaMemAdvise函数的CUDA文档所述:

  

如果设备是GPU,则设备属性cudaDevAttrConcurrentManagedAccess必须具有非零值。

您应该调用以下代码以确保设备可以并发管理使用:

int device_id = 0, result = 0;
cudaDeviceGetAttribute (&result, cudaDevAttrConcurrentManagedAccess, device_id);
if (result) {
    // Call cudaMemAdvise
}