CUDA 合并访问二维块



对于一维情况,我已经非常了解 CUDA 中全局内存的整个合并访问要求。

但是,我对二维情况有点卡住了(也就是说,我们有一个由 2D 块组成的 2D 网格(。

假设我有一个向量in_vector,在我的内核中,我想以合并的方式访问它。这样:

__global__ void my_kernel(float* out_matrix, float* in_vector, int size)
{
   int i = blockIdx.x * blockDim.x + threadIdx.x;
   int j = blockIdx.y * blockDim.y + threadIdx.y;
   // ...
   float vx = in_vector[i]; // This is good. Here we have coalesced access
   float vy = in_vector[j]; // Not sure about this. All threads in my warp access the same global address. (See explanation)
   // ...
   // Do some calculations... Obtain result
}

根据我对这种 2D 情况的理解,块内的线程以列为主的方式"排列"。例如:假设一个(threadIdx.x,threadIdx.y(表示法:

    第一个翘曲将是:(0, 0(, (1, 0(, (2, 0(,
  • ..., (31, 0(,
  • 第二个翘曲是:(0, 1(, (1, 1(, (2, 1(,
  • ..., (31, 1(,
  • 等等...

在这种情况下,调用in_vector[i]为我们提供了合并的访问权限,因为同一 warp 中的每个连续线程都将访问连续的地址。然而,调用in_vector[j]似乎是一个糟糕的想法,因为每个连续的线程将访问全局内存中的相同地址(例如,warp 0 中的所有线程都将访问 in_vector[0],这将给我们 32 个不同的全局内存请求(

我理解正确吗?如果是这样,如何使用in_vector[j]对全局内存进行合并访问?

您在问题中显示的内容仅适用于某些块大小。您的"合并"访问权限:

int i = blockIdx.x * blockDim.x + threadIdx.x;
float vx = in_vector[i];

仅当blockDim.x大于或等于 32 时,才会导致从全局内存合并访问in_vector。即使在合并的情况下,共享相同threadIdx.x值的块中的每个线程也会从全局内存中读取相同的单词,这似乎是违反直觉和浪费的。

确保每个线程的读取是唯一且合并的正确方法是计算块内的线程数和网格内的偏移量,可能如下所示:

int tid = threadIdx.x + blockDim.x * threadIdx.y; // must use column major order
int bid = blockIdx.x + gridDim.x * blockDim.y; // can either use column or row major
int offset = (blockDim.x * blockDim.y) * bid; // block id * threads per block
float vx = in_vector[tid + offset];

如果你的意图真的不是读取每个线程的唯一值,那么你可以节省大量的内存带宽,并使用共享内存实现合并如下所示:

__shared__ float vx[32], vy[32]; 
int tid = threadIdx.x + blockDim.x * threadIdx.y;
if (tid < 32) {
    vx[tid] = in_vector[blockIdx.x * blockDim.x + tid];
    vy[tid] = in_vector[blockIdx.y * blockDim.y + tid];
}
__syncthread();

您将获得一次将唯一值读取到共享内存中的单个 warp。然后,其他线程可以从共享内存中读取值,而无需任何进一步的全局内存访问。请注意,在上面的示例中,我遵循了代码的约定,即使以这种方式读取in_vector两次不一定有多大意义。

最新更新