0

我环顾了这个站点和其他站点,但没有任何效果。我正在为我的具体案例发布一个问题。

我有一堆矩阵,目标是使用内核让 GPU 对所有矩阵执行相同的操作。我很确定我可以让内核工作,但我不能让 cudaMalloc / cudaMemcpy 工作。

我有一个指向 Matrix 结构的指针,该结构有一个名为 elements 的成员,它指向一些浮点数。我可以很好地完成所有非 cuda malloc。

感谢您的任何/所有帮助。

代码:

typedef struct {
    int width;
    int height;
    float* elements;
} Matrix;

int main void() {
    int rows, cols, numMat = 2; // These are actually determined at run-time
    Matrix* data = (Matrix*)malloc(numMat * sizeof(Matrix));

    // ... Successfully read from file into "data" ...

    Matrix* d_data;
    cudaMalloc(&d_data, numMat*sizeof(Matrix)); 
    for (int i=0; i<numMat; i++){
        // The next line doesn't work
        cudaMalloc(&(d_data[i].elements), rows*cols*sizeof(float));

        // Don't know if this works
        cudaMemcpy(d_data[i].elements, data[i].elements,  rows*cols*sizeof(float)), cudaMemcpyHostToDevice);
    }

    // ... Do other things ...
}

谢谢!

4

1 回答 1

7

你必须知道你的记忆驻留在哪里。malloc 分配主机内存,cudaMalloc 在设备上分配内存并返回指向该内存的指针。但是,此指针仅在设备函数中有效。

您想要的可以如下实现:

typedef struct {
    int width;
    int height;
    float* elements;
} Matrix;

int main void() {
    int rows, cols, numMat = 2; // These are actually determined at run-time
    Matrix* data = (Matrix*)malloc(numMat * sizeof(Matrix));

    // ... Successfully read from file into "data" ...
    Matrix* h_data = (Matrix*)malloc(numMat * sizeof(Matrix));
    memcpy(h_data, data, numMat * sizeof(Matrix);

    for (int i=0; i<numMat; i++){

        cudaMalloc(&(h_data[i].elements), rows*cols*sizeof(float));
        cudaMemcpy(h_data[i].elements, data[i].elements,  rows*cols*sizeof(float)), cudaMemcpyHostToDevice);

     }// matrix data is now on the gpu, now copy the "meta" data to gpu
     Matrix* d_data;
     cudaMalloc(&d_data, numMat*sizeof(Matrix)); 
     cudaMemcpy(d_data, h_data, numMat*sizeof(Matrix));
     // ... Do other things ...
}

说清楚: Matrix* data包含主机上的数据。 Matrix* h_data在可以作为参数传递给内核的元素中包含指向设备内存的指针。内存在 GPU 上。 Matrix* d_data完全在 GPU 上,可以像主机上的数据一样使用。

在您的内核代码中,您现在可以访问矩阵值,例如,

__global__ void doThings(Matrix* matrices)
{
      matrices[i].elements[0] = 42;
}
于 2013-10-16T13:53:55.333 回答