跳转至

Scan⚓︎

类型定位⚓︎

Scan 或 prefix kernel 不只是做求和,而是为每个位置生成其前缀聚合结果。它与 reduction 的区别在于:reduction 只保留收缩结果,而 scan 需要保留所有位置的前缀状态。

在 CUDA 中,scan 通常先在 block 内完成树形扫描;当输入跨越多个 block 时,再把每个 block 的总和继续扫描,并把 block offset 回填到原输出上。

优化方法⚓︎

  • 小输入直接使用单 block shared memory scan。
  • 使用 Blelloch scan 的 upsweep / downsweep 结构生成 exclusive prefix。
  • 大输入拆成 block tiles,先生成每个 block 的局部 scan 与 block_sums。
  • 对 block_sums 再执行第二层 scan,得到每个 block 的 offset。
  • 最后把 block offset 回加到对应 block 的局部输出。

题目索引⚓︎

  • exclusive_scan
  • segmented_prefix_sum

exclusive_scan⚓︎

exclusive_scan 为每个位置输出其左侧所有元素的前缀和,不包含当前位置本身:

y_i = \sum_{j=0}^{i-1} x_j

因此 y_0 = 0。Basic 版本展示单 block Blelloch scan。Advanced 版本展示多 block scan 的局部扫描和 offset 回加阶段;完整任意长度 scan 还需要继续扫描 block_sums 生成 block_offsets。

exclusive_scan 实现
exclusive_scan_basic
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void exclusive_scan_basic_kernel(const float *input, float *output, int N) {
    __shared__ float shared[kBlockSize];

    int tid = threadIdx.x;
    shared[tid] = (tid < N) ? input[tid] : 0.0f;
    __syncthreads();

    // Upsweep 建树,先把区间和收拢到右端点。
    for (int stride = 1; stride < blockDim.x; stride <<= 1) {
        int index = ((tid + 1) * stride * 2) - 1;
        if (index < blockDim.x) {
            shared[index] += shared[index - stride];
        }
        __syncthreads();
    }

    if (tid == 0) {
        shared[blockDim.x - 1] = 0.0f;
    }
    __syncthreads();

    // Downsweep 把父节点的前缀值向左下传递。
    for (int stride = blockDim.x >> 1; stride > 0; stride >>= 1) {
        int index = ((tid + 1) * stride * 2) - 1;
        if (index < blockDim.x) {
            float left = shared[index - stride];
            shared[index - stride] = shared[index];
            shared[index] += left;
        }
        __syncthreads();
    }

    if (tid < N) {
        output[tid] = shared[tid];
    }
}

void launch_exclusive_scan_basic(const float *input, float *output, int N) {
    if (N <= 0 || N > kBlockSize) {
        return;
    }
    exclusive_scan_basic_kernel<<<1, kBlockSize>>>(input, output, N);
}
exclusive_scan_advanced
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void exclusive_scan_blocks_kernel(const float *input, float *output, float *block_sums, int N) {
    __shared__ float shared[kBlockSize];

    int tid = threadIdx.x;
    int idx = blockIdx.x * blockDim.x + tid;
    shared[tid] = (idx < N) ? input[idx] : 0.0f;
    __syncthreads();

    for (int stride = 1; stride < blockDim.x; stride <<= 1) {
        int index = ((tid + 1) * stride * 2) - 1;
        if (index < blockDim.x) {
            shared[index] += shared[index - stride];
        }
        __syncthreads();
    }

    if (tid == 0) {
        // 这里先产出 block_sums;完整多 block scan 还需要对它再做一次 scan。
        block_sums[blockIdx.x] = shared[blockDim.x - 1];
        shared[blockDim.x - 1] = 0.0f;
    }
    __syncthreads();

    for (int stride = blockDim.x >> 1; stride > 0; stride >>= 1) {
        int index = ((tid + 1) * stride * 2) - 1;
        if (index < blockDim.x) {
            float left = shared[index - stride];
            shared[index - stride] = shared[index];
            shared[index] += left;
        }
        __syncthreads();
    }

    if (idx < N) {
        output[idx] = shared[tid];
    }
}

__global__ void add_block_offsets_kernel(float *output, const float *block_offsets, int N) {
    // block_offsets 是每个 block 左侧所有 block_sums 的 exclusive scan。
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < N) {
        output[idx] += block_offsets[blockIdx.x];
    }
}

void launch_exclusive_scan_blocks(const float *input, float *output, float *block_sums, int N) {
    if (N <= 0) {
        return;
    }
    int blocks = (N + kBlockSize - 1) / kBlockSize;
    exclusive_scan_blocks_kernel<<<blocks, kBlockSize>>>(input, output, block_sums, N);
}

void launch_add_block_offsets(float *output, const float *block_offsets, int N) {
    if (N <= 0) {
        return;
    }
    int blocks = (N + kBlockSize - 1) / kBlockSize;
    add_block_offsets_kernel<<<blocks, kBlockSize>>>(output, block_offsets, N);
}

segmented_prefix_sum⚓︎

segmented_prefix_sum 是 Prefix Sum 的变体,通过 flags 数组判断是否开启新的一段序列。

遇到新序列标记时,重置累加逻辑。

segmented_prefix_sum 实现
segmented_prefix_sum_basic
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void segmented_prefix_sum_basic_kernel(const float *input,
                                                  const int *flags,
                                                  float *output,
                                                  int N) {
    __shared__ float shared_data[kBlockSize];
    __shared__ int shared_head[kBlockSize];

    int tid = threadIdx.x;
    int idx = blockIdx.x * blockDim.x + tid;

    shared_data[tid] = (idx < N) ? input[idx] : 0.0f;
    shared_head[tid] = (idx < N && flags[idx] != 0) ? tid : -1;
    __syncthreads();

    // shared_head 记录当前前缀能跨过的最近段起点,遇到新段标记后停止吸收左侧累加值。
    for (int stride = 1; stride < blockDim.x; stride <<= 1) {
        float left_data = 0.0f;
        int left_head = -1;
        if (tid >= stride) {
            left_data = shared_data[tid - stride];
            left_head = shared_head[tid - stride];
        }
        __syncthreads();

        if (tid >= stride && left_head >= shared_head[tid]) {
            shared_data[tid] += left_data;
            shared_head[tid] = left_head;
        }
        __syncthreads();
    }

    if (idx < N) {
        output[idx] = shared_data[tid];
    }
}

void launch_segmented_prefix_sum_basic(const float *input, const int *flags, float *output, int N) {
    if (N <= 0) {
        return;
    }

    int blocks = (N + kBlockSize - 1) / kBlockSize;
    segmented_prefix_sum_basic_kernel<<<blocks, kBlockSize>>>(input, flags, output, N);
}

边界与局限⚓︎

Scan 对同步结构比 reduction 更敏感,因为它必须保留前缀顺序信息。对于极大输入,仅靠单层 block offsets 往往不够,需要更完整的分层或递归设计。

评论