cuda算子--矩阵转置

复制代码
#include <cuda_runtime.h>

#define TILE 32
#define BLOCK_ROWS 8   // block 的 y 方向线程数,配合 TILE 减少 padding 浪费

// 用 padding 避免 shared bank conflict
__global__ void transpose_shared_kernel(const float* __restrict__ input,
                                        float* __restrict__ output,
                                        int rows, int cols) {
    __shared__ float tile[TILE][TILE + 1];

    const int tx = threadIdx.x;   // [0, TILE)
    const int ty = threadIdx.y;   // [0, BLOCK_ROWS)

    // ---- 读阶段 ----
    // 该 block 负责 input 的子块:
    //   行 [blockIdx.y*TILE, blockIdx.y*TILE + TILE)
    //   列 [blockIdx.x*TILE, blockIdx.x*TILE + TILE)
    const int col = blockIdx.x * TILE + tx;   // input 列
    const int row = blockIdx.y * TILE + ty;   // input 行起点

    #pragma unroll
    for (int j = 0; j < TILE; j += BLOCK_ROWS) {
        if (col < cols && (row + j) < rows)
            tile[ty + j][tx] = input[(size_t)(row + j) * cols + col];
    }

    __syncthreads();

    // ---- 写阶段 ----
    // 转置后,output 的子块:
    //   行 [blockIdx.x*TILE, blockIdx.x*TILE + TILE)  ← 原来是 input 的列
    //   列 [blockIdx.y*TILE, blockIdx.y*TILE + TILE)  ← 原来是 input 的行
    const int outCol     = blockIdx.y * TILE + tx;   // 输出列 = 原输入行
    const int outRowBase = blockIdx.x * TILE + ty;   // 输出行起点 = 原输入列

    #pragma unroll
    for (int j = 0; j < TILE; j += BLOCK_ROWS) {
        const int outRow = outRowBase + j;           // 关键:j 加到行上
        if (outCol < rows && outRow < cols)
            output[(size_t)outRow * rows + outCol] = tile[tx][ty + j];
    }
}

extern "C" void solve(const float* input, float* output, int rows, int cols) {
    if (rows <= 0 || cols <= 0) return;

    dim3 threadsPerBlock(TILE, BLOCK_ROWS);
    dim3 blocksPerGrid((cols + TILE - 1) / TILE,
                       (rows + TILE - 1) / TILE);

    matrix_transpose_kernel<<<blocksPerGrid, threadsPerBlock>>>(input, output, rows, cols);
    cudaDeviceSynchronize();
}

关键是

for (int j = 0; j < TILE; j += BLOCK_ROWS) {

const int outRow = outRowBase + j; // 关键:j 加到行上

if (outCol < rows && outRow < cols)

output(size_t)outRow \* rows + outCol = tiletxty + j;

}

如果让block都等于0的话,那么base row和col就是ty,tx,那么最后就是outputtytx=tiletxty]很简单的转置。接下来考虑block x增加,此时base row下移,但他不应该影响与tile的对应关系,因为tile只有一块,所以应该还是和block x等于0时一样,去tile的同样的位置去找。需要注意的是,为什么base row对应的是block x,而不是y,因为这样out才对应input矩阵的block级转置,而thread是对应tile级的转置。

相关推荐
吴佳浩4 小时前
我把 HAMi 摆回一台双卡机器上跑了一遍:GPU 编排的性能账,到底记在谁头上
人工智能·gpu
forest_098 小时前
《AI 编程 Harness 实战手册》04|审批这道门:点了一百次“允许”,还剩多少作用?
人工智能·算法·prompt·agi
H.莓飛8 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
火山引擎开发者社区9 小时前
当 RPA 遇上 Agent:MUA 混合执行 Workflow 深度拆解
人工智能
严肃小白兔10 小时前
第 10/24 期:深度神经网络的自动求导机制与梯度验证
人工智能·神经网络·dnn
火山引擎开发者社区10 小时前
定档12.16-12.18!FORCE原动力大会上海见!
人工智能
努力的MM12310 小时前
CAIE 二级和阿里云大模型 ACP 怎么选?企业 AI 工程与云平台开发能力对比
人工智能
老金带你玩AI10 小时前
Kling Image 4.0来了!8K和组图直出,电商人的提效神器?
人工智能
孟健10 小时前
用 unslop 拯救 AI 生成网页的塑料感,7 分钟重构落地实测
前端·人工智能·ai编程