LeetGPU习题02:Matrix Copy

878 字
4 分钟
LeetGPU习题02:Matrix Copy
2026-04-26
更新已完成

算子说明#

名称说明
Vector Addition两个向量逐元素相加
Matrix Addition两个矩阵逐元素相加
Matrix Copy逐元素复制矩阵
Color Inversion对每个像素独立取反
Reverse Array反转数组,每个元素独立移动位置
ReLU逐元素应用 ReLU 函数
Leaky ReLU逐元素应用 Leaky ReLU
Sigmoid Activation逐元素应用 Sigmoid 函数
Value Clipping逐元素裁剪到指定范围
Sigmoid Linear Unit (SiLU)逐元素 SiLU 激活
Swish-Gated Linear Unit (SWiGLU)逐元素 SWiGLU(门控部分也为逐元素)
Gaussian Error Gated Linear Unit (GEGLU)逐元素 GEGLU 激活
RGB to Grayscale每个像素独立转换,不依赖邻域
Interleave Arrays交替合并两数组,每个输出元素仅依赖对应位置输入
Rotary Positional Embedding对每个位置独立应用旋转矩阵
Weight Dequantization每个权重独立反量化
INT8 Quantized MatMul(仅反量化部分)反量化部分为逐元素,整体不是
Simple Inference线性层前向包含矩阵乘,非 element-wise,但其中的激活部分可能是逐元素

1. Matrix Copy#

1.1. 题目#

实现一个程序,在 GPU 上将输入矩阵 A 中的 32 位浮点数按元素直接复制到输出矩阵 B
即对于所有有效下标 (i, j),满足 B[i][j] = A[i][j]

1.2. 实现要求#

  • 不允许使用外部库
  • solve 函数签名必须保持不变
  • 最终结果必须存储在矩阵 B

1.3. 示例#

示例 1:

输入:

A = [[1.0, 2.0],
[3.0, 4.0]]

输出:

B = [[1.0, 2.0],
[3.0, 4.0]]

示例 2:

输入:

A = [[5.5, 6.6, 7.7],
[8.8, 9.9, 10.1],
[11.2, 12.3, 13.4]]

输出:

B = [[5.5, 6.6, 7.7],
[8.8, 9.9, 10.1],
[11.2, 12.3, 13.4]]

1.4. 约束#

  • 1 ≤ N ≤ 4096
  • 所有元素均为 32 位浮点数
  • 性能评测时 N = 4096

2. Pytorch题解#

import torch
def solve(A: torch.Tensor, B: torch.Tensor, N: int):
"""原地复制 A 到 B"""
B.copy_(A) # 进行原地复制

4. Triton题解#

import torch
import triton
import triton.language as tl
@triton.autotune(
configs=[
triton.Config({'BLOCK_SIZE': 256}, num_warps=4),
triton.Config({'BLOCK_SIZE': 512}, num_warps=4),
triton.Config({'BLOCK_SIZE': 1024}, num_warps=4),
triton.Config({'BLOCK_SIZE': 2048}, num_warps=8),
],
key=['n_elements'],
)
@triton.jit
def copy_kernel(src_ptr, dst_ptr, n_elements, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(src_ptr + offsets, mask=mask)
tl.store(dst_ptr + offsets, x, mask=mask)
def solve_triton(A, B, N):
n_elements = A.numel()
grid = lambda meta: (triton.cdiv(n_elements, meta['BLOCK_SIZE']),)
copy_kernel[grid](A, B, n_elements)

测试结果:

Triton和Pytorch对比的测试结果
Triton和Pytorch对比的测试结果

3. CUDA题解#

直接三板斧

#include <cuda_runtime.h>
#include <stdio.h>
__global__ void copy_naive(const float* src, float* dst, int N) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if (tid < N) {
dst[tid] = src[tid];
}
}
__global__ void copy_stride(const float* src, float* dst, int N) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
for (int i = tid; i < N; i += stride) {
dst[i] = src[i];
}
}
__global__ void copy_vec4(const float* src, float* dst, int N) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
int vecN = N / 4;
const float4* src4 = (const float4*)src;
float4* dst4 = (float4*) dst;
for (int i = tid; i < vecN; i += stride) {
dst4[i] = src4[i];
}
int tail_idx = vecN * 4 + tid;
if (tail_idx < N) {
dst[tail_idx] = src[tail_idx];
}
}
// 使用模板 T 接受任意可调用对象
template <typename T>
void run_bench(const char* name, T func, size_t bytes) {
cudaEvent_t start, stop;
cudaEventCreate(&start); cudaEventCreate(&stop);
func(); // Warmup
cudaEventRecord(start);
for (int i = 0; i < 100; i++) func();
cudaEventRecord(stop);
cudaEventSynchronize(stop);
float ms;
cudaEventElapsedTime(&ms, start, stop);
float gib_s = (bytes * 2.0f * 100) / (ms * 1e6f * 1.073741824f);
printf("%-12s : %.2f GiB/s | Avg: %.3f ms\n", name, gib_s, ms / 100.0f);
}
int main() {
const int N = 4097 * 4097, block = 256;
const size_t bytes = N * sizeof(float);
float *d_src, *d_dst;
cudaMalloc(&d_src, bytes); cudaMalloc(&d_dst, bytes);
int sms;
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, 0);
int g_stride = sms * 32;
run_bench("Naive", [=](){ copy_naive<<<(N+block-1)/block, block>>>(d_src, d_dst, N); }, bytes);
run_bench("Stride", [=](){ copy_stride<<<g_stride, block>>>(d_src, d_dst, N); }, bytes);
run_bench("Vec4", [=](){
copy_vec4<<<g_stride, block>>>(d_src,d_dst, N);
}, bytes);
cudaFree(d_src); cudaFree(d_dst);
return 0;
}

预期性能:

CUDA的三种性能对比方案
CUDA的三种性能对比方案

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
LeetGPU习题02:Matrix Copy
https://dlog.com.cn/posts/leetgpu02/matrix_copy/
作者
杜子源
发布于
2026-04-26
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
杜子源
都是风景,幸会
公告
请狠狠地打赏我,打赏一次,爆更一篇!!
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
17
分类
6
标签
8
总字数
27,300
运行时长
0
最后活动
0 天前

目录