Permutation⚓︎
类型定位⚓︎
Permutation 类 kernel 的主要任务不是增加算术密度,而是改变数据位置映射。输出值通常直接来自输入,只是索引关系发生变化。
优化方法⚓︎
- 保持至少一侧访存连续,例如连续读取输入或连续写回输出。
- 避免不必要的同步,因为简单 permutation 通常没有跨线程数据依赖。
- 只有当排列关系复杂、或需要在 tile 内重排时,才引入 shared memory 作为中间缓冲。
题目索引⚓︎
reverse_arraymatrix_copyinterleave
reverse_array⚓︎
reverse_array 把输入数组按逆序写入输出。若输入长度为 N,可以写作:
y_i = x_{N-1-i}
实现上也可以让线程读取 x_i 后写入 y_{N-1-i}。这个 kernel 的核心不是算术计算,而是索引关系变化;线程仍按连续 idx 启动,但输出地址由反向映射决定。这里展示的是 out-of-place 写法,输入和输出不能指向同一段内存。
reverse_array 实现
reverse_array_basic
#include <cuda_runtime.h>
__global__ void reverse_array_basic_kernel(const float *input, float *output, int N) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < N) {
output[N - 1 - idx] = input[idx];
}
}
void launch_reverse_array_basic(const float *input, float *output, int N) {
if (N <= 0) {
return;
}
int threads = 256;
int blocks = (N + threads - 1) / threads;
reverse_array_basic_kernel<<<blocks, threads>>>(input, output, N);
}
matrix_copy⚓︎
matrix_copy 是将2D或展开的扁平矩阵做复制操作,没有复杂的数学运算:
Y_{i, j} = X_{i, j}
matrix_copy 实现
matrix_copy_basic
#include <cuda_runtime.h>
__global__ void matrix_copy_basic_kernel(const float *input, float *output, 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 idx = row * width + col;
output[idx] = input[idx];
}
}
void launch_matrix_copy_basic(const float *input, float *output, 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);
matrix_copy_basic_kernel<<<blocks, threads>>>(input, output, width, height);
}
interleave⚓︎
interleave 是典型的索引重排操作,将两个同等规模向量交叉混合:
y_{2i} = a_i , \quad y_{2i+1} = b_i
interleave 实现
interleave_basic
#include <cuda_runtime.h>
__global__ void interleave_basic_kernel(const float *a, const float *b, float *output, int N) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < N) {
output[2 * idx] = a[idx];
output[2 * idx + 1] = b[idx];
}
}
void launch_interleave_basic(const float *a, const float *b, float *output, int N) {
if (N <= 0) {
return;
}
int threads = 256;
int blocks = (N + threads - 1) / threads;
interleave_basic_kernel<<<blocks, threads>>>(a, b, output, N);
}
边界与局限⚓︎
Permutation kernel 往往算术量很低,因此更容易完全受内存访问模式支配。它适合作为理解“索引重排”与“访存代价”关系的最小样例。