在内核内部调用 cublas 函数时编译 CUDA 代码

Compiling CUDA code when a cublas function is called inside the kernel

我正在尝试 运行 一个调用 cublassgemm 函数的非常简单的内核。我的代码是:

__global__ void cor (float * dev_mat,float * dev_cor,int n,cublasHandle_t handle)
{
        const float alpha = 1.0;
        const float beta = 0;
        cublasStatus_t stat;
        stat = cublasSgemm(handle, CUBLAS_OP_N,  CUBLAS_OP_N, n, n, n,  &alpha, dev_mat, n, dev_mat,n,&beta, dev_cor, n);
        if(stat != CUBLAS_STATUS_SUCCESS)
                {
                        cout<<"error in cublas sgemm \n";
                }
}
int main()
{
int  m =1000,n = 1000;
float * h_mat = new float[m*n];
float * h_cor = new float[m*n];
float * dev_mat,*dev_cor;
cudaMalloc(&dev_mat,m*n*sizeof(float));
cudaMalloc(&dev_cor,m*n*sizeof(float));
for (int i = 0; i< m; i++)
        for(int j = 0; j <n;j++)
                {
                        h_mat[i*n+j]=rand()%10;
                }
cudaError_t cudaStat;
cublasStatus_t stat;
cublasHandle_t handle;
stat = cublasSetMatrix(m, n, sizeof(float), h_mat, m, dev_mat, m);
if(stat !=CUBLAS_STATUS_SUCCESS)
        {
                cout<<"error in cublassetmatrix   \n";
                return stat;
        }
stat = cublasCreate (&handle);
if(stat != CUBLAS_STATUS_SUCCESS)
        {
                cout<<"error in cublas create handle \n";
                return stat;
        }

cor<<<1,1>>>(dev_mat,dev_cor,n,handle);
cudaFree(dev_mat);
delete []h_mat;
delete []h_cor;
return 0;
}

我尝试使用以下命令编译此代码:

nvcc -lcublas cublassegmm_inside_kernel.cu -o cublassegmm_inside_kernel

但是我得到了以下错误:

calling a host function("std::operator << > ") from a global function("cor") is not allowed

我看了This link但是我不明白我应该如何编译!任何人都可以向我解释或建议来源。非常感谢

有 2 个问题(至少):

  1. 您不能在 CUDA 内核中使用 cout。将其更改为等效的 printf 语句,您应该没问题:

    printf("error in cublas sgemm \n");
    
  2. 你的编译命令不正确。您提供的 link 显示了必要的组件。你应该使用这样的东西:

    nvcc -arch=sm_35 -rdc=true -o cublassgemm_inside_kernel cublassgemm_inside_kernel.cu -lcublas -lcublas_device -lcudadevrt
    

当然这只适用于 cc3.5 或更高版本的 GPU。