gpt4 book ai didi

cuda - 正确使用 cudaMalloc3D 和 cudaMemcpy

转载 作者:行者123 更新时间:2023-12-04 04:57:37 27 4
gpt4 key购买 nike

我想发送一个 3D 数组 src尺寸size在每个维度中,展平为大小为 length = size * size * size 的一维数组, 进入内核,计算结果并将其存储在 dst 中.然而,最后,dst不正确地包含全 0。这是我的代码:

int size = 256;
int length = size * size * size;
int bytes = length * sizeof(float);

// Allocate source and destination arrays on the host and initialize source array

float *src, *dst;
cudaMallocHost(&src, bytes);
cudaMallocHost(&dst, bytes);
for (int i = 0; i < length; i++) {
src[i] = i;
}

// Allocate source and destination arrays on the device

struct cudaPitchedPtr srcGPU, dstGPU;
struct cudaExtent extent = make_cudaExtent(size*sizeof(float), size, size);
cudaMalloc3D(&srcGPU, extent);
cudaMalloc3D(&dstGPU, extent);

// Copy to the device, execute kernel, and copy back to the host

cudaMemcpy(srcGPU.ptr, src, bytes, cudaMemcpyHostToDevice);
myKernel<<<numBlocks, blockSize>>>((float *)srcGPU.ptr, (float *)dstGPU.ptr);
cudaMemcpy(dst, dstGPU.ptr, bytes, cudaMemcpyDeviceToHost);

我忽略了对 cudaMallocHost() 的错误检查, cudaMalloc()cudaMemcpy()为了清楚起见。在任何情况下,此代码都不会触发任何错误。
cudaMalloc3D()的正确用法是什么?与 cudaMemcpy() ?

请让我知道我是否也应该为内核发布一个最小的测试用例,或者是否可以在上面的代码中找到问题。

最佳答案

编辑:如果使用 CUDA 数组,则范围采用元素数,但如果不使用 CUDA 数组,则有效地采用字节数(例如,使用 cudaMalloc 的某些非数组变体分配的内存)

来自 the Runtime API CUDA documentation :

The extent field defines the dimensions of the transferred area in elements. If a CUDA array is participating in the copy, the extent is defined in terms of that array's elements. If no CUDA array is participating in the copy then the extents are defined in elements of unsigned char



另外, cudaMalloc3D返回一个倾斜的指针,这意味着它至少具有您提供的范围的尺寸,但由于对齐原因可能更多。在访问和复制设备内存时,您必须考虑到这一点。见 here有关 cudaPitchedPtr 的文档结构

至于使用 cudaMalloc3DcudaMemcpy ,你可能想看看使用 cudaMemcpy3D ( documentation here ),将主机和设备内存的间距考虑在内可能会让您的生活更轻松。使用 cudaMemcpy3D你必须创建一个 cudaMemcpy3DParms结构与适当的信息。它的成员是:
cudaArray_t dstArray
struct cudaPos dstPos
struct cudaPitchedPtr dstPtr
struct cudaExtent extent
enumcudaMemcpyKind kind
cudaArray_t srcArray
struct cudaPos srcPos
struct cudaPitchedPtr srcPtr

并且您必须指定 srcArray 之一 srcPtrdstArray 之一 dstPtr .此外,文档建议在使用之前将结构初始化为 0,例如 cudaMemcpy3DParms myParms = {0};
此外,您可能有兴趣查看此 other SO question

关于cuda - 正确使用 cudaMalloc3D 和 cudaMemcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16571896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com