【发布时间】:2021-01-07 01:25:16
【问题描述】:
如何在 CUDA 中自动确定二维数组(例如图像处理)的块大小和网格大小?
CUDA 具有 cudaOccupancyMaxPotentialBlockSize() 函数,可以自动计算 cuda 内核函数的块大小。见here。在这种情况下,它适用于一维数组。
就我而言,我有一张 640x480 的图片。
如何确定块/网格大小? 我用:
////image size: 640x480
int x_min_grid_size, x_grid_size, x_block_size;
int y_min_grid_size, y_grid_size, y_block_size;
cudaOccupancyMaxPotentialBlockSize
(
&x_min_grid_size, &x_block_size,
my_cuda_kernel,
0, image.width()
);
cudaOccupancyMaxPotentialBlockSize
(
&y_min_grid_size, &y_block_size,
my_cuda_kernel,
0, image.height()
);
x_grid_size = (image.width() + x_block_size - 1) / x_block_size;
y_grid_size = (image.height() + y_block_size - 1) / y_block_size;
dim3 grid_dim(x_grid_size, y_grid_size);
dim3 block_dim(x_block_size, y_block_size);
my_cuda_kernel<<<grid_dim, block_dim>>>(<arguments...>)
////check cuda kernel function launch error
cudaError_t error = cudaGetLastError();
if(cudaSuccess != error)
{
std::cout<<"CUDA Error! "<<cudaGetErrorString(error)<<std::endl;
exit(1);
}
cudaDeviceSynchronize();
问题 1 我可以使用这种方法计算块/网格大小吗?
对于这段代码,内核函数启动后出现错误。
CUDA Error! invalid configuration arguments
如果我手动设置x_block_size = 32; y_block_size = 32,它可以工作并且没有错误。
我能问一下为什么 CUDA 得到invalid configuration arguments 错误消息吗?二维数组好像不能直接用cudaOccupancyMaxPotentialBlockSize()?
潜在解决方案 我对潜在的解决方案有了一个想法:
如果我先计算线程数,然后使用cudaOccupancyMaxPotentialBlockSize() 计算二维数组的块大小:
////total_thread_num = 640x480 = 307200
int total_thread_num = image.width * image.height;
////compute block/grid size
int min_grid_size, grid_size, block_size;
cudaOccupancyMaxPotentialBlockSize
(
&min_grid_size, &block_size,
my_cuda_kernel,
0, total_thread_num
);
grid_size = (total_thread_num + block_size - 1) / block_size;
//launch CUDA kernel function
my_cuda_kernel<<<grid_size, block_size>>>(<arguments...>);
在my_cuda_kernel中,根据图片大小计算对应的索引:
__global__ void my_cuda_kernel()
{
//compute 2D index based on 1D index;
unsigned int idx = BlockIdx.x * blockDim.x + threadIdx.x;
unsigned int row_idx = idx / image.width;
unsigned int col_idx = idx % image_width;
/*kernel function code*/
}
问题 2 如果问题1中的方法不可行,我可以使用上面的方法吗?
【问题讨论】:
标签: c++ image-processing cuda