跳转至

Mapping2D⚓︎

类型定位⚓︎

二维映射类 kernel 把线程块中的二维坐标直接映射到矩阵、图像或二维网格中的 (row, col)。它与一维 elementwise 的区别不在计算一定更复杂,而在于 launch 和数据布局都需要同时处理行、列两个维度。

优化方法⚓︎

  • 使用 dim3 threads(x, y) 与 dim3 blocks(grid_x, grid_y) 表达二维工作区。
  • 让连续的 threadIdx.x 对应连续列,匹配 row-major 存储下的合并访问。
  • 对 transpose 这类重排问题,用 shared memory tile 把非连续写转换为更规整的写回路径。
  • 对 shared memory tile 增加 padding,降低列方向访问时的 bank conflict。
  • 对二维计数类问题,先做 block 内聚合,再减少全局 atomicAdd 次数。

题目索引⚓︎

  • count_array_element2d
  • matrix_transpose
  • rgb_to_grayscale
  • convolution_2d

Launch 方式⚓︎

二维线程坐标通常由下式恢复:

row = blockIdx.y \times blockDim.y + threadIdx.y
col = blockIdx.x \times blockDim.x + threadIdx.x

count_array_element2d⚓︎

count_array_element2d 在二维数组中统计满足条件的元素数量:

c = \sum_{r=0}^{H-1}\sum_{q=0}^{W-1} \mathbf{1}(x_{r,q} = target)

Basic 版本中,每个线程负责一个二维坐标,命中条件后直接使用 atomicAdd 累加。Advanced 版本先在 block 内做局部计数,再用更少的全局 atomic 合并结果。

count_array_element2d 实现
count_array_element2d_basic
#include <cuda_runtime.h>

__global__ void count_array_element2d_basic_kernel(const int *input, int *count, int rows, int cols, int target) {
    // 恢复二维线程的行坐标与列坐标
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;

    // 检查越界,如果命中目标值,使用原子加累加全局计数器
    if (row < rows && col < cols && input[row * cols + col] == target) {
        atomicAdd(count, 1);
    }
}

void launch_count_array_element2d_basic(const int *input, int *count, int rows, int cols, int target) {
    if (rows <= 0 || cols <= 0) {
        return;
    }

    dim3 threads(16, 16);
    dim3 blocks((cols + threads.x - 1) / threads.x,
                (rows + threads.y - 1) / threads.y);
    count_array_element2d_basic_kernel<<<blocks, threads>>>(input, count, rows, cols, target);
}
count_array_element2d_advanced
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void count_array_element2d_advanced_kernel(const int *input, int *count, int rows, int cols, int target) {
    // 采用 Shared Memory 在 Block 内局部累加
    __shared__ int shared_count[kBlockSize];

    // 将 2D thread 索引平铺为 1D 以访问 shared block
    int tid = threadIdx.y * blockDim.x + threadIdx.x;
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;

    // 初始化 shared memory,对越界或者不匹配的数据记 0
    shared_count[tid] = (row < rows && col < cols && input[row * cols + col] == target) ? 1 : 0;
    __syncthreads();

    // Block 内部对局部计数进行树状归约 (Parallel Reduction)
    for (int stride = kBlockSize / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            shared_count[tid] += shared_count[tid + stride];
        }
        __syncthreads();
    }

    // 由0号线程将 Block 的计算总结果合并进全局计数器
    if (tid == 0 && shared_count[0] > 0) {
        atomicAdd(count, shared_count[0]);
    }
}

void launch_count_array_element2d_advanced(const int *input, int *count, int rows, int cols, int target) {
    if (rows <= 0 || cols <= 0) {
        return;
    }

    dim3 threads(16, 16);
    dim3 blocks((cols + threads.x - 1) / threads.x,
                (rows + threads.y - 1) / threads.y);
    count_array_element2d_advanced_kernel<<<blocks, threads>>>(input, count, rows, cols, target);
}

matrix_transpose⚓︎

matrix_transpose 把输入矩阵按行列互换写入输出:

Y_{c,r} = X_{r,c}

Basic 版本直接从 (row, col) 读取并写到 (col, row)。Advanced 版本先把 tile 搬入 shared memory,再交换坐标写回,并通过 +1 padding 缓解 shared memory bank conflict。

matrix_transpose 实现
matrix_transpose_basic
#include <cuda_runtime.h>

__global__ void matrix_transpose_basic_kernel(const float *input, float *output, int rows, int cols) {
    // 恢复当前的行列坐标
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;

    // 检查越界
    if (row < rows && col < cols) {
        // 直接从输入矩阵读 (row, col) 的数据,写入输出矩阵的 (col, row) 的位置
        // 注意:这会导致对 output 的写入不能享受合并访存 (coalesced memory access)
        output[col * rows + row] = input[row * cols + col];
    }
}

void launch_matrix_transpose_basic(const float *input, float *output, int rows, int cols) {
    if (rows <= 0 || cols <= 0) {
        return;
    }

    dim3 threads(16, 16);
    dim3 blocks((cols + threads.x - 1) / threads.x,
                (rows + threads.y - 1) / threads.y);
    matrix_transpose_basic_kernel<<<blocks, threads>>>(input, output, rows, cols);
}
matrix_transpose_advanced
#include <cuda_runtime.h>

constexpr int kTileDim = 32;
constexpr int kBlockRows = 8;

__global__ void matrix_transpose_advanced_kernel(const float *__restrict__ input,
                                                 float *__restrict__ output,
                                                 int width,
                                                 int height) {
    // Shared Memory Tile + 1 进行 padding 预防 bank conflict
    __shared__ float tile[kTileDim][kTileDim + 1];

    int x = blockIdx.x * kTileDim + threadIdx.x;
    int y = blockIdx.y * kTileDim + threadIdx.y;

    // 分块(tile)方式加载数据到 shared memory
    // 读取 input 时按行合并访问(coalesced access)
    for (int i = 0; i < kTileDim; i += kBlockRows) {
        int current_y = y + i;
        if (x < width && current_y < height) {
            tile[threadIdx.y + i][threadIdx.x] = input[current_y * width + x];
        }
    }

    __syncthreads();

    // 计算转置后的写回目标坐标
    x = blockIdx.y * kTileDim + threadIdx.x;
    y = blockIdx.x * kTileDim + threadIdx.y;

    // 写回 output 时相邻 threadIdx.x 对应转置矩阵同一行的连续列。
    for (int i = 0; i < kTileDim; i += kBlockRows) {
        int current_y = y + i;
        if (x < height && current_y < width) {
            output[x * width + current_y] = tile[threadIdx.x][threadIdx.y + i];
        }
    }
}

void launch_matrix_transpose_advanced(const float *input, float *output, int rows, int cols) {
    if (rows <= 0 || cols <= 0) {
        return;
    }

    dim3 threads(kTileDim, kBlockRows);
    dim3 blocks((cols + kTileDim - 1) / kTileDim,
                (rows + kTileDim - 1) / kTileDim);
    matrix_transpose_advanced_kernel<<<blocks, threads>>>(input, output, cols, rows);
}

rgb_to_grayscale⚓︎

rgb_to_grayscale 是一种典型的图像处理二维映射,它将通道数为 3 的 RGB 图像转换为单通道灰度图:

Y_{r,c} = 0.299 \times R_{r,c} + 0.587 \times G_{r,c} + 0.114 \times B_{r,c}

每个线程处理一个具体的像素坐标 (row, col),读取对应的 RGB 连续分量进行加权后将结果输出到灰度通道:

rgb_to_grayscale 实现
rgb_to_grayscale_basic
#include <cuda_runtime.h>

__global__ void rgb_to_grayscale_basic_kernel(const unsigned char *rgb,
                                              unsigned char *gray,
                                              int width,
                                              int height) {
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    int row = blockIdx.y * blockDim.y + threadIdx.y;

    if (col < width && row < height) {
        int gray_idx = row * width + col;
        int rgb_idx = gray_idx * 3;
        unsigned char r = rgb[rgb_idx];
        unsigned char g = rgb[rgb_idx + 1];
        unsigned char b = rgb[rgb_idx + 2];
        gray[gray_idx] = static_cast<unsigned char>(0.299f * r + 0.587f * g + 0.114f * b);
    }
}

void launch_rgb_to_grayscale_basic(const unsigned char *rgb,
                                   unsigned char *gray,
                                   int width,
                                   int height) {
    if (width <= 0 || height <= 0) {
        return;
    }

    dim3 threads(16, 16);
    dim3 blocks((width + threads.x - 1) / threads.x,
                (height + threads.y - 1) / threads.y);
    rgb_to_grayscale_basic_kernel<<<blocks, threads>>>(rgb, gray, width, height);
}

convolution_2d⚓︎

convolution_2d (即图像二维卷积与模糊等操作) 也是典型的二维映射问题。输出特征图中的一点会聚合原图中对应的领域值与滤波器的对应权重卷积计算。

Y_{r, c} = \sum_{i} \sum_{j} X_{r+i, c+j} \times W_{i, j}

Basic 实现中,每个二维坐标线程负责各自的领域乘加并进行越界保护:

convolution_2d 实现
convolution_2d_basic
#include <cuda_runtime.h>

__global__ void convolution_2d_basic_kernel(const float *input,
                                            float *output,
                                            const float *filter,
                                            int width,
                                            int height,
                                            int filter_size) {
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    int row = blockIdx.y * blockDim.y + threadIdx.y;

    if (col < width && row < height) {
        float sum = 0.0f;
        int filter_half = filter_size / 2;

        for (int r = -filter_half; r <= filter_half; ++r) {
            for (int c = -filter_half; c <= filter_half; ++c) {
                int cur_row = row + r;
                int cur_col = col + c;

                float value = 0.0f;
                if (cur_row >= 0 && cur_row < height && cur_col >= 0 && cur_col < width) {
                    value = input[cur_row * width + cur_col];
                }

                int filter_r = r + filter_half;
                int filter_c = c + filter_half;
                sum += value * filter[filter_r * filter_size + filter_c];
            }
        }

        output[row * width + col] = sum;
    }
}

void launch_convolution_2d_basic(const float *input,
                                 float *output,
                                 const float *filter,
                                 int width,
                                 int height,
                                 int filter_size) {
    if (width <= 0 || height <= 0 || filter_size <= 0 || filter_size % 2 == 0) {
        return;
    }

    dim3 threads(16, 16);
    dim3 blocks((width + threads.x - 1) / threads.x,
                (height + threads.y - 1) / threads.y);
    convolution_2d_basic_kernel<<<blocks, threads>>>(input, output, filter, width, height, filter_size);
}

边界与局限⚓︎

二维映射并不天然带来高复用。若访问模式只是简单坐标恢复,性能仍主要受全局内存访问方式支配;只有当读写模式发生重排时,shared memory tile 的收益才更明显。

评论