使用cudaMalloc分配矩阵
我正在使用 cudaMalloc 和 cudaMemcpy 分配一个矩阵并将向量数组复制到其中,如下所示:
float **pa;
cudaMalloc((void***)&pa, N*sizeof(float*)); //this seems to be ok
for(i=0; i<N; i++) {
cudaMalloc((void**) &(pa[i]), N*sizeof(float)); //this gives seg fault
cudaMemcpy (pa[i], A[i], N*sizeof(float), cudaMemcpyHostToDevice); // also i am not sure about this
}
我的指令有什么问题吗? 预先
感谢A[i] 是一个向量
现在我试图将一个矩阵从设备复制到主机的矩阵:
假设我在设备中有 **pc,并且 **pgpu 在主机中:
cudaMemcpy (pgpu, pc, N*sizeof(float*), cudaMemcpyDeviceToHost);
for (i=0; i<N; i++)
cudaMemcpy(pgpu[i], pc[i], N*sizeof(float), cudaMemcpyDeviceToHost);
= 是错误的.. ..
I am using cudaMalloc and cudaMemcpy to allocate a matrix and copy into it arrays of vectors , like this:
float **pa;
cudaMalloc((void***)&pa, N*sizeof(float*)); //this seems to be ok
for(i=0; i<N; i++) {
cudaMalloc((void**) &(pa[i]), N*sizeof(float)); //this gives seg fault
cudaMemcpy (pa[i], A[i], N*sizeof(float), cudaMemcpyHostToDevice); // also i am not sure about this
}
What is wrong with my instructions?
Thanks in advance
P.S. A[i] is a vector
Now i'm trying to copy a matrix from the Device to a matrix from the host:
Supposing I have **pc in the device, and **pgpu is in the host:
cudaMemcpy (pgpu, pc, N*sizeof(float*), cudaMemcpyDeviceToHost);
for (i=0; i<N; i++)
cudaMemcpy(pgpu[i], pc[i], N*sizeof(float), cudaMemcpyDeviceToHost);
= is wrong....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
pa
位于设备内存中,因此&(pa[i])
不会执行您期望的操作。这会起作用,即。在主机内存中构建指针数组,然后将其复制到设备。
我不确定您希望从A
中读取什么,但我怀疑内部cudaMemcpy
可能没有按照您所写的方式执行操作。预先警告,从性能角度来看,指针数组在 GPU 上并不是一个好主意。
pa
is in device memory, so&(pa[i])
does not do what you are expecting it will. This will workie. build the array of pointers in host memory and then copy it to the device.
I am not sure what you are hoping to read fromA
, but I suspect that the innercudaMemcpy
probably isn't doing what you want as written.Be forewarned that from a performance point of view, arrays of pointers are not a good idea on the GPU.
这段代码的最终目标是什么?正如上面所暗示的,将 pa 展平为一维数组以便在 GPU 上使用可能符合您的最佳利益。类似这样的:
不幸的是,你必须调整 A[i] 才能以这种方式进行内存复制。
What is your eventual goal of this code? As hinted at above, it would probably be in your best interest to flatten pa into a 1-dimensional array for usage on the GPU. Something like:
Unfortunately you'd have to adjust A[i] to do your memory copy this way though.