accelerator.cu(8): error: attribute "managed" does not apply here?

accelerator.cu(8): error: attribute "managed" does not apply here?

我正在编写的程序 (Accelerator.cu) 无法在 NVCC 8.0.61 和 nvcc -std=c++11 -o accelerator accelerator.cu 下编译。 __device____global____shared__ 失败的原因还有其他答案,但 none 揭示了自定义代码中此错误的原因。我正在尝试遵循指南 https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#um-global-scope。但是,在尝试以下代码时:

#include <cuda_runtime_api.h>
#include <cuda.h>

// CUDA Acceleration Adapter.
class Accelerator {
public:
    __device__ __managed__  float**  A;
    __device__ __managed__  float*  B;
    __device__ __managed__  int  N;
    __device__ __managed__  int  C;

    Accelerator () {}

    Accelerator (int N, int C) {
        // initialize variables (unified memory).
        N = records;

        // are "inputs"
        this->C = C;
    }

    void setData (vector<vector<float>>& A, vector<float>& B) {
        // convert vectors to arrays that the GPU can address.
    }

    void accelerate (vector<float>& results) {
        // run kernel.
        // convert results back to vector.
    }

    __global__ void evaluate (float **A, float *B, int N, int C) {
        // do stuff.
    }

};

void main () {
    Accelerator testAcc();
}

但是,我收到所有 A

的错误
accelerator.cu(8): error: attribute "device" does not apply here
accelerator.cu(8): error: attribute "managed" does not apply here

其余3个成员变量出现类似错误。

这是我第一次尝试编写自己的 GPU 加速程序。如果有人知道出了什么问题,将不胜感激。

您可能 运行 遇到许多问题。我将主要关注尝试让您展示的内容进行编译的内容,而不会深入探讨您可能会在此处触及的 CUDA 编程的各个方面。

您引用的问题(例如 __device__ 在 class 成员变量上的用法)是 explicitly forbidden

__managed__ 的用法同样是不允许的(因为它是 implicitly a __device__ scoped static allocation)。在这种情况下,您应该使用普通的 class 成员变量,并根据需要为它们动态分配,也许在构造函数中,也许使用动态托管分配器 (cudaMallocManaged)。使用指针变量作为 class 成员变量肯定表明了这种方法。

您所概述的可能还有其他挑战。例如,__global__ 函数 may not be a class member function.

您可能在 CUDA 编程方面有相当多的学习要做,但这里仍然是您所展示内容的破解版本,它没有涉及任何明显的问题:

#include <vector>
using namespace std;
// CUDA Acceleration Adapter.
    __global__ void evaluate (float *a, float *b, int n, int c) {
        for (int i = 0; i < n; i++) a[i]++;
        for (int i = 0; i < c; i++) b[i]++;
    }
class Accelerator {
public:
  float*  A;
  float*  B;
  int  N;
  int  C;

    Accelerator () {}

    Accelerator (int N, int C) {
        // initialize variables (unified memory).
        this->N = N;

        // are "inputs"
        this->C = C;
        cudaMallocManaged(&A, N*sizeof(float));
        cudaMallocManaged(&B, C*sizeof(float));
    }

    void setData (vector<float>& A, vector<float>& B) {
        for (int i=0; i < N; i++) (this->A)[i] = A[i];
        for (int i=0; i < C; i++) (this->B)[i] = B[i];
    }

    void accelerate (vector<float>& results) {
        evaluate<<<1,1>>>(A, B, N, C);
        cudaDeviceSynchronize();
        for (int i = 0; i<N; i++) results[i] = A[i];
    }

};
int  main () {
    Accelerator testAcc(5,3);
}