Interleave Arrays
2026/6/6小于 1 分钟
Interleave Arrays
题目描述
编写一个 GPU 程序,将两个 32 位浮点数数组交错合并。给定两个输入数组 和 ,每个长度为 ,生成一个长度为 的输出数组,元素在 和 之间交替排列:
实现要求
- 不允许使用外部库。
solve函数签名必须保持不变。- 最终结果必须存储在
output数组中。
示例
示例 1
Input: A = [1.0, 2.0, 3.0], B = [4.0, 5.0, 6.0]
Output: [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]示例 2
Input: A = [10.0, 20.0], B = [30.0, 40.0]
Output: [10.0, 30.0, 20.0, 40.0]约束条件
- 。
- 性能测试在 的规模下进行。
解题思路
数组交织是一种分散写(Scatter)操作——连续读但间隔写。每个线程负责一对元素 ,写入输出的 和 位置。float2 向量化可将两次 ST 合并为一次 ST.64。
代码实现
CUDA
#include <cuda_runtime.h>
// 解法一:基础逐元素交织
__global__ void interleave_kernel(const float* A, const float* B, float* output, int N) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < N) {
output[i * 2] = A[i];
output[i * 2 + 1] = B[i];
}
}
// 解法二:Grid-Stride Loop
__global__ void interleave_grid_stride(const float* A, const float* B, float* output, int N) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
for (int i = idx; i < N; i += stride) {
output[i * 2] = A[i];
output[i * 2 + 1] = B[i];
}
}
// 解法三:float2 向量化写入(一次 ST.64 写 8 字节 = 2 个 float)
__global__ void interleave_float2(const float* A, const float* B, float* output, int N) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
float2* out2 = (float2*)output;
for (int i = idx; i < N; i += stride) {
out2[i] = make_float2(A[i], B[i]);
}
}
extern "C" void solve(const float* A, const float* B, float* output, int N) {
int threadsPerBlock = 256;
int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;
interleave_kernel<<<blocksPerGrid, threadsPerBlock>>>(A, B, output, N);
cudaDeviceSynchronize();
}Triton
import triton
import triton.language as tl
import torch
@triton.jit
def interleave_kernel(
A_ptr, B_ptr, output_ptr,
N: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
pid = tl.program_id(0)
idx = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = idx < N
a = tl.load(A_ptr + idx, mask=mask)
b = tl.load(B_ptr + idx, mask=mask)
tl.store(output_ptr + idx * 2, a, mask=mask)
tl.store(output_ptr + idx * 2 + 1, b, mask=mask)