【问题标题】:two consecutive "cudaMallocPitch" make the code failed两个连续的“cudaMallocPitch”使代码失败
【发布时间】:2012-10-12 16:29:41
【问题描述】:

我写了一个简单的CUDA代码如下:

//Allocate the first 2d array "deviceArray2DInput"
if(cudaMallocPitch((Float32**) &deviceArray2DInput, &devicePitch, sizeof(Float32)*deviceColNumber,deviceRowNumber) == cudaErrorMemoryAllocation){
    return -1;
}

//Allocate the second 2d array "deviceArray2DOutput". It was suppose to hold the output of some process.
if(cudaMallocPitch((Float32**) &deviceArray2DOutput, &devicePitch,sizeof(Float32)*deviceRowNumber,deviceColNumber) == cudaErrorMemoryAllocation){
    return -1;
}

//Copy data from "hostArrayR" to "deviceArray2DInput" (#1)
cudaMemcpy2D(deviceArray2DInput,devicePitch,hostArrayR,sizeof(Float32)*colNumber,sizeof(Float32)*deviceColNumber,deviceRowNumber,cudaMemcpyHostToDevice);

//Clean the top 10000 elements in "hostArrayR" for verification. 
for(int i = 0; i < 10000; ++i){
    hostArrayR[i] = 0;
}

//Copy data back from "deviceArray2DInput" to "hostArrayR"(#2)
cudaMemcpy2D(hostArrayR,sizeof(Float32)*colNumber,deviceArray2DInput,devicePitch,sizeof(Float32)*deviceColNumber,deviceRowNumber,cudaMemcpyDeviceToHost);

我注释掉了第二个分配块,代码运行良好。它将数据从主机数组“hostArrayR”复制到设备数组“deviceArray2DInput”并复制回来。 但是,如果两个分配块都存在,则复制回的“hostArrayR”为空(没有从设备复制回数据)。

我确定数据在 (#1) 行的“hostArrayR”中,但在 (#2) 行没有数据。我清理了前 10000 个元素(远小于数组的大小)以验证数据没有返回。

我在 Visual Studio 2010 上使用 Nvidia Nsight 2.2。数组大小为 1024x768,我使用的是浮动 32 位数据。我的显卡是 GTX570。似乎没有内存分配错误(或者代码会在复制之前返回)。

我没有尝试“cudaMalloc()”,因为我更喜欢使用“cudaMallocPitch()”进行内存对齐。

【问题讨论】:

  • 您的错误检查在我看来相当脆弱。如果返回cudaErrorMemoryAllocation以外的错误怎么办? cudaMemcpy2D()s 根本没有错误检查。我建议始终检查所有返回码是否等于cudaSuccess

标签: visual-studio-2010 cuda nsight


【解决方案1】:
  • 您应该根据 cudaSuccess 而不是一个检查 API 调用 具体错误。
  • 您应该检查 memcpys 返回的错误值。
  • 您将在第二次 cudaMallocPitch() 调用中覆盖 devicePitch,数组具有不同的形状,因此可能具有不同的间距。

【讨论】:

  • 我重写了代码:(1)反对“cudaSuccess”(2)使用两个单独的“devicePitch”(我认为你是对的,“devicePitch”被第二个分配块覆盖,它导致内存复制失败,我的原始代码中没有检查)。现在它运作良好。谢谢。
猜你喜欢
  • 2015-04-15
  • 2012-03-04
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多