在ubuntu上运行cuda -它是否需要一个本地设备驱动程序(使用nvidia显卡)

run cuda on ubuntu - does it need a native device driver (with nvidia graphics card)?

本文关键字:一个 ubuntu 设备驱动程序 显卡 nvidia 使用 cuda 运行 是否      更新时间:2023-10-16

我正在使用GeForce GTX 660M显卡在Ubuntu 14上运行cuda/opencl GPU计算的基本入门示例。

尽管我设法编译和运行示例代码,但似乎GPU没有计算任何东西或cudamemcpy操作不起作用,因为我的结果值在调用内核并执行devicetohost复制操作后没有更新。

我想知道,为了使用cuda或opencl,我是否需要在Ubuntu上安装某个来自nvidia的本地驱动程序。

这是我的基本入门代码(用于cuda):

#include <iostream>
using namespace std;
// global constants
#define THREADS 4
const int N = 100;
int fill_content = 1;
__global__ void sum(int* a, int* b, int* c)
{
    int i = blockIdx.x * blockDim.x * threadIdx.x;
    c[i] = a[i] + b[i];
}
void check( int* a, int N )
{
    cout << endl;
    for(int i = 0; i < N; ++i)
    {
        int num = a[i];
        cout << i << ": " << num << endl;
    }
    cout << endl;
}
void fill_vectors(int*p , int size)
{
    for(int i = 0; i < size; ++i)
    {
        p[i] = fill_content;
    }
}
int main(int argc, char **argv)
{
    int host_a[N], host_b[N], host_c[N];
    size_t s_a,s_b,s_c;
    s_a = s_b = s_c = sizeof(int) * N;
    int *dev_a, *dev_b, *dev_c;

    // allocate memory on the device for calculation input and results
    cudaMalloc(&dev_a, s_a);
    cudaMalloc(&dev_b, s_b);
    cudaMalloc(&dev_c, s_c);
    fill_content = 1;
    fill_vectors(host_a, N);
    fill_content = 2;
    fill_vectors(host_b, N);
    fill_content = 0;
    fill_vectors(host_c, N);
    // copy the input values to the gpu-memory
    cudaMemcpy(dev_a, host_a, s_a, cudaMemcpyHostToDevice);
    cudaMemcpy(dev_b, host_b, s_b, cudaMemcpyHostToDevice);
    // invokes kernel-method sum on device using device-memory dev_a, dev_b, dev_c
    //sum<<<N/THREADS, THREADS,1>>>(dev_a, dev_b, dev_c);
    // copy the result values back from the device_memory to the host-memory
    cudaMemcpy(host_c, dev_c, s_c, cudaMemcpyDeviceToHost);
    // free memory allocated on device (for input and result values)
    cudaFree(dev_a); cudaFree(dev_b); cudaFree(dev_c);
    // expected to print out 3
    check(host_c,N);
}

我用:

nvcc -o vector-sum2 vector-sum2.cu

安装了nvidia-cuda-toolkit:

就像上面解释的那样,它只为每个数组元素输出0

0: 0
1: 0
2: 0
3: 0
4: 0
5: 0

…继续。

你知道我需要改变什么才能使这个例子工作吗?

首先,你的内核调用被注释掉了:

//sum<<<N/THREADS, THREADS,1>>>(dev_a, dev_b, dev_c);

所以你的输出都是零,因为你没有实际运行内核。

如果取消对内核的注释,就会出现问题。任何时候你遇到CUDA代码的问题,你应该使用适当的CUDA错误检查和运行你的代码与cuda-memcheck

取消内核注释并使用cuda-memcheck运行会发现内核有大量的越界访问。这些最终是由于这行代码:

int i = blockIdx.x * blockDim.x * threadIdx.x;

这不是创建唯一线程索引的正确方法。相反,我们想要:

int i = blockIdx.x * blockDim.x + threadIdx.x;

有了这些改变,你的代码就可以为我正确运行了。如果它仍然不适合你,你可能是有问题的机器设置,在这种情况下,适当的cuda错误检查可能会给你一些线索。

相关文章: