跳转至

Reduction⚓︎

类型定位⚓︎

Reduction kernel 把一组输入收缩为更小的一组部分结果,或最终收缩为单个标量。它的主要难点不是单个线程如何恢复索引,而是 block 内部如何组织局部归约,以及多个 block 的局部结果如何合并。

这类 kernel 的典型结构是:每个线程先积累私有部分和,再在 block 内做树形归约,最后通过 atomic 或第二阶段 kernel 合并 block 结果。

优化方法⚓︎

  • 先做线程私有累加,减少进入 shared memory 的中间值数量。
  • 使用 shared memory 做 block 内树形归约。
  • 当归约范围缩小到一个 warp 时,使用 __shfl_down_sync 减少 shared memory 读写和同步。
  • 用 block 级局部结果减少全局 atomic 的冲突压力。
  • 对大输入使用分层 reduction,而不是单阶段 atomic 汇总。

题目索引⚓︎

  • reduction
  • count_array_element
  • softmax
  • dot_product
  • mean_squared_error

reduction⚓︎

reduction 把长度为 N 的输入数组收缩为一个总和:

s = \sum_{i=0}^{N-1} x_i

Basic 版本使用 shared memory 做 block 内归约,并用 atomicAdd 合并 block 结果。Advanced 版本在最后阶段切换到 warp shuffle,减少同步与 shared memory 访问。

reduction 实现
reduction_basic
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

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

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

    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            shared_sum[tid] += shared_sum[tid + stride];
        }
        __syncthreads();
    }

    if (tid == 0) {
        atomicAdd(output, shared_sum[0]);
    }
}

void launch_reduction_basic(const float *input, float *output, int N) {
    if (N <= 0) {
        return;
    }
    int blocks = (N + kBlockSize - 1) / kBlockSize;
    reduction_basic_kernel<<<blocks, kBlockSize>>>(input, output, N);
}
reduction_advanced
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;
constexpr unsigned kFullMask = 0xffffffffu;

__device__ float warp_reduce_sum(float value) {
    value += __shfl_down_sync(kFullMask, value, 16);
    value += __shfl_down_sync(kFullMask, value, 8);
    value += __shfl_down_sync(kFullMask, value, 4);
    value += __shfl_down_sync(kFullMask, value, 2);
    value += __shfl_down_sync(kFullMask, value, 1);
    return value;
}

__global__ void reduction_advanced_kernel(const float *input, float *output, int N) {
    int tid = threadIdx.x;
    int lane = tid & 31;
    int warp_id = tid >> 5;

    float thread_sum = 0.0f;
    // 每个线程先处理两个相隔 blockDim.x 的元素,减少后续归约阶段的输入规模。
    int idx = blockIdx.x * (blockDim.x * 2) + tid;
    int stride = gridDim.x * (blockDim.x * 2);
    for (int i = idx; i < N; i += stride) {
        thread_sum += input[i];
        if (i + blockDim.x < N) {
            thread_sum += input[i + blockDim.x];
        }
    }

    thread_sum = warp_reduce_sum(thread_sum);

    // 只把每个 warp 的 lane 0 结果写入 shared memory,减少同步和 shared memory 访问次数。
    __shared__ float warp_sums[kBlockSize / 32];
    if (lane == 0) {
        warp_sums[warp_id] = thread_sum;
    }
    __syncthreads();

    if (warp_id == 0) {
        float block_sum = (tid < kBlockSize / 32) ? warp_sums[lane] : 0.0f;
        block_sum = warp_reduce_sum(block_sum);
        if (lane == 0) {
            atomicAdd(output, block_sum);
        }
    }
}

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

count_array_element⚓︎

count_array_element 统计数组中等于目标值的元素数量:

c = \sum_{i=0}^{N-1} \mathbf{1}(x_i = target)

它本质上是带谓词判断的整数 reduction。Basic 版本每次命中都执行一次全局 atomic;Advanced 版本先在 block 内计数,再由每个 block 发起一次 atomic。

count_array_element 实现
count_array_element_basic
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void count_array_element_basic_kernel(const int *input, int *count, int target, int N) {
    // 获得当前线程的全局一维索引
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < N && input[idx] == target) {
        atomicAdd(count, 1);
    }
}

void launch_count_array_element_basic(const int *input, int *count, int target, int N) {
    if (N <= 0) {
        return;
    }
    int blocks = (N + kBlockSize - 1) / kBlockSize;
    count_array_element_basic_kernel<<<blocks, kBlockSize>>>(input, count, target, N);
}
count_array_element_advanced
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void count_array_element_advanced_kernel(const int *input, int *count, int target, int N) {
    __shared__ int shared_count[kBlockSize];

    int tid = threadIdx.x;
    int idx = blockIdx.x * blockDim.x + tid;
    // 先把命中结果转成 0/1,在 block 内归约后只发起一次 atomicAdd。
    shared_count[tid] = (idx < N && input[idx] == target) ? 1 : 0;
    __syncthreads();

    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            shared_count[tid] += shared_count[tid + stride];
        }
        __syncthreads();
    }

    if (tid == 0 && shared_count[0] > 0) {
        atomicAdd(count, shared_count[0]);
    }
}

void launch_count_array_element_advanced(const int *input, int *count, int target, int N) {
    if (N <= 0) {
        return;
    }
    int blocks = (N + kBlockSize - 1) / kBlockSize;
    count_array_element_advanced_kernel<<<blocks, kBlockSize>>>(input, count, target, N);
}

softmax⚓︎

softmax 对输入向量执行归一化指数变换:

y_i = \frac{e^{x_i - m}}{\sum_j e^{x_j - m}}, \quad m = \max_j x_j

虽然输出形状仍是一组逐元素结果,但它依赖两次聚合:先求最大值,再求指数和。因此它在 kernel 模式上更接近 reduction 组合。

softmax 实现
softmax_basic
#include <cuda_runtime.h>
#include <cfloat>
#include <cmath>

constexpr int kBlockSize = 256;
constexpr unsigned kFullMask = 0xffffffffu;

__device__ float warp_reduce_max(float value) {
    value = fmaxf(value, __shfl_down_sync(kFullMask, value, 16));
    value = fmaxf(value, __shfl_down_sync(kFullMask, value, 8));
    value = fmaxf(value, __shfl_down_sync(kFullMask, value, 4));
    value = fmaxf(value, __shfl_down_sync(kFullMask, value, 2));
    value = fmaxf(value, __shfl_down_sync(kFullMask, value, 1));
    return value;
}

__device__ float warp_reduce_sum(float value) {
    value += __shfl_down_sync(kFullMask, value, 16);
    value += __shfl_down_sync(kFullMask, value, 8);
    value += __shfl_down_sync(kFullMask, value, 4);
    value += __shfl_down_sync(kFullMask, value, 2);
    value += __shfl_down_sync(kFullMask, value, 1);
    return value;
}

__device__ float block_reduce_max(float value) {
    __shared__ float warp_values[kBlockSize / 32];
    int lane = threadIdx.x & 31;
    int warp_id = threadIdx.x >> 5;

    value = warp_reduce_max(value);
    if (lane == 0) {
        warp_values[warp_id] = value;
    }
    __syncthreads();

    // 第二轮只让第一个 warp 归约各 warp 的局部结果。
    value = (threadIdx.x < kBlockSize / 32) ? warp_values[lane] : -FLT_MAX;
    if (warp_id == 0) {
        value = warp_reduce_max(value);
    }
    return value;
}

__device__ float block_reduce_sum(float value) {
    __shared__ float warp_values[kBlockSize / 32];
    int lane = threadIdx.x & 31;
    int warp_id = threadIdx.x >> 5;

    value = warp_reduce_sum(value);
    if (lane == 0) {
        warp_values[warp_id] = value;
    }
    __syncthreads();

    // 非首个 warp 的线程提供 0,避免污染最终 block sum。
    value = (threadIdx.x < kBlockSize / 32) ? warp_values[lane] : 0.0f;
    if (warp_id == 0) {
        value = warp_reduce_sum(value);
    }
    return value;
}

__global__ void softmax_basic_kernel(const float *__restrict__ input,
                                     float *__restrict__ output,
                                     int batch_size,
                                     int seq_len) {
    int row = blockIdx.x;
    if (row >= batch_size) {
        return;
    }

    int tid = threadIdx.x;
    const float *row_input = input + row * seq_len;
    float *row_output = output + row * seq_len;

    // 先减去行最大值,避免 expf 在大输入上溢出。
    float local_max = -FLT_MAX;
    for (int i = tid; i < seq_len; i += blockDim.x) {
        local_max = fmaxf(local_max, row_input[i]);
    }
    float max_value = block_reduce_max(local_max);

    __shared__ float shared_max;
    if (tid == 0) {
        shared_max = max_value;
    }
    __syncthreads();

    float local_sum = 0.0f;
    for (int i = tid; i < seq_len; i += blockDim.x) {
        local_sum += expf(row_input[i] - shared_max);
    }
    float sum_value = block_reduce_sum(local_sum);

    __shared__ float shared_sum;
    if (tid == 0) {
        shared_sum = sum_value;
    }
    __syncthreads();

    for (int i = tid; i < seq_len; i += blockDim.x) {
        row_output[i] = expf(row_input[i] - shared_max) / shared_sum;
    }
}

void launch_softmax_basic(const float *input, float *output, int batch_size, int seq_len) {
    if (batch_size <= 0 || seq_len <= 0) {
        return;
    }

    softmax_basic_kernel<<<batch_size, kBlockSize>>>(input, output, batch_size, seq_len);
}

dot_product⚓︎

dot_product 生成两个向量的点积,是典型的双输入归约:

s = \sum_{i=0}^{N-1} a_i \cdot b_i
dot_product 实现
dot_product_basic
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void dot_product_basic_kernel(const float *a, const float *b, float *output, int N) {
    __shared__ float shared_sum[kBlockSize];

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

    shared_sum[tid] = (idx < N) ? a[idx] * b[idx] : 0.0f;
    __syncthreads();

    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            shared_sum[tid] += shared_sum[tid + stride];
        }
        __syncthreads();
    }

    if (tid == 0) {
        atomicAdd(output, shared_sum[0]);
    }
}

void launch_dot_product_basic(const float *a, const float *b, float *output, int N) {
    if (N <= 0) {
        return;
    }

    int blocks = (N + kBlockSize - 1) / kBlockSize;
    dot_product_basic_kernel<<<blocks, kBlockSize>>>(a, b, output, N);
}

mean_squared_error⚓︎

mean_squared_error 计算预测与真实标签之间的误差平方和:

MSE = \frac{1}{N} \sum_{i=0}^{N-1} (p_i - l_i)^2

Kernel 通常负责执行 Sum,然后在主机端求 Mean。

mean_squared_error 实现
mean_squared_error_basic
#include <cuda_runtime.h>

constexpr int kBlockSize = 256;

__global__ void mean_squared_error_basic_kernel(const float *preds, const float *labels, float *mse, int N) {
    __shared__ float shared_sum[kBlockSize];

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

    float local_err = 0.0f;
    if (idx < N) {
        float diff = preds[idx] - labels[idx];
        local_err = diff * diff;
    }
    shared_sum[tid] = local_err;
    __syncthreads();

    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            shared_sum[tid] += shared_sum[tid + stride];
        }
        __syncthreads();
    }

    if (tid == 0) {
        atomicAdd(mse, shared_sum[0]);
    }
}

void launch_mean_squared_error_basic(const float *preds, const float *labels, float *mse, int N) {
    if (N <= 0) {
        return;
    }

    int blocks = (N + kBlockSize - 1) / kBlockSize;
    mean_squared_error_basic_kernel<<<blocks, kBlockSize>>>(preds, labels, mse, N);
}

边界与局限⚓︎

Reduction 常见瓶颈包括 atomic 冲突、shared memory 同步、以及跨 block 合并成本。输入很大时,单阶段 atomic 汇总通常不够理想,需要分层 reduction。

评论