CUDA编程:Histogram 直方图统计与 Atomic 优化
### 文章目录 - 1. 本课目标 - 2. 什么是 Histogram? - 3. 为什么 Histogram 在 GPU 上有难点? - 4. 两种实现方式 - Global Atomic Histogram - Shared Memory 局部 Histogram - 5. 实验设计 - 6. CUDA C++ 代码 - 7. 编译与运行 - 8. 推荐实验组合 - 8.1 均匀分布 - 8.2 热点分布 - 8.3 数据规模变化 CUDA 第 12 课:Histogram 直方图统计与 Atomic 优化 第 10 课讲了 **Reduction:很多数归约成一个数**。 第 11 课讲了 **Prefix Scan:很多数生成前缀位置**。 第 12 课进入另一个非常常见的并行模式: > **❝Histogram:把大量数据按照类别/bin 统计频次。** 它在图像处理、推荐系统、日志统计、token 分布统计、排序预处理、采样分析中都非常常见。 # **1. 本课目标** 本节课重点掌握: ``` 1. 什么是 histogram 直方图 2. 为什么 histogram 容易产生 atomic 冲突 3. 掌握 global atomic histogram 的基础写法 4. 掌握 shared memory 局部 histogram 优化 5. 理解“先局部统计,再全局合并”的优化思想 6. 对比不同 bin 数量、数据分布下的性能差异 ``` # **2. 什么是 Histogram?** 假设输入数组是: ``` input = [1, 2, 1, 3, 2, 1, 0, 3] ``` 我们希望统计每个数字出现了多少次。 如果 bin 数量是 4,也就是统计 `0,1,2,3` 四类: ``` hist[0] = 1 hist[1] = 3 hist[2] = 2 hist[3] = 2 ``` 最终结果: ``` hist = [1, 3, 2, 2] ```  在这里插入图片描述 # **3. 为什么 Histogram 在 GPU 上有难点?** 如果每个线程处理一个元素: ``` int bin = input[idx]; atomicAdd(&hist[bin], 1); ``` 问题是:很多线程可能同时更新同一个 bin。 例如输入里大量元素都是 `1`: ``` input = [1, 1, 1, 1, 1, 1, ...] ``` 那么所有线程都执行: ``` atomicAdd(&hist[1], 1); ``` 这会造成严重竞争。 所以 histogram 的核心难点是: ``` 多个线程可能同时写同一个地址 必须用 atomic 保证正确性 但 atomic 冲突会影响性能 ``` # **4. 两种实现方式** ## **Global Atomic Histogram** 最简单写法: ``` atomicAdd(&global_hist[bin], 1); ``` 优点: ``` 代码简单 结果正确 适合 bin 多、冲突不严重的情况 ``` 缺点: ``` 所有 block 都直接竞争 global memory 当数据集中在少数 bin 时会很慢 ``` ## **Shared Memory 局部 Histogram** 优化思路: ``` 每个 block 先在 shared memory 中统计一个局部 hist 然后每个 block 再把局部 hist 合并到 global hist ``` 流程: ``` Global input ↓ 每个 block 建立 shared_hist ↓ block 内线程 atomicAdd(shared_hist[bin], 1) ↓ block 内统计完成 ↓ 把 shared_hist 合并到 global_hist ``` 这样可以把大量 global atomic 竞争变成: ``` block 内 shared atomic + 少量 global atomic ``` 通常会更快,尤其是 bin 数量不大时。 # **5. 实验设计** 我们实现并比较: ``` 1. CPU histogram 2. GPU global atomic histogram 3. GPU shared memory histogram ``` 测试维度: ``` 1. bin 数量:16、64、256 2. 数据规模:1M、16M、64M 3. 数据分布: - 均匀分布:冲突较平均 - 热点分布:大量数据集中在少数 bin ``` # **6. CUDA C++ 代码** 保存为: ``` lesson12_histogram.cu ``` 代码如下: ``` #include #include #include #include #include #include #include #include #define CUDA_CHECK(call) \ do { \ cudaError_t err = call; \ if (err != cudaSuccess) { \ std::cerr (blockIdx.x) * blockDim.x + threadIdx.x; if (idx (blockIdx.x) * blockDim.x + threadIdx.x; size_t stride = static_cast(blockDim.x) * gridDim.x; for (size_t i = global_tid; i 0) { atomicAdd(&global_hist[i], shared_hist[i]); } } } /* * 用 cudaEvent 计时一个 kernel。 */ template float time_kernel(LaunchFunc launch, int repeat) { /* * warmup */ launch(); CUDA_CHECK(cudaDeviceSynchronize()); cudaEvent_t start, stop; CUDA_CHECK(cudaEventCreate(&start)); CUDA_CHECK(cudaEventCreate(&stop)); float total_ms = 0.0f; for (int r = 0; r & a, const std::vector& b, int bins) { for (int i = 0; i & input, int bins, const std::string& mode) { std::mt19937 rng(12345); std::uniform_int_distribution uniform_dist(0, bins - 1); std::uniform_real_distribution prob(0.0f, 1.0f); for (size_t i = 0; i = 2) { n = static_cast(std::atoll(argv[1])); } if (argc >= 3) { bins = std::atoi(argv[2]); } if (argc >= 4) { block_size = std::atoi(argv[3]); } if (argc >= 5) { repeat = std::atoi(argv[4]); } if (argc >= 6) { mode = argv[5]; } if (bins 4096) { std::cerr 1024) { std::cerr (bins) * sizeof(int); std::cout h_input(n); std::vector h_cpu_hist(bins, 0); std::vector h_global_hist(bins, 0); std::vector h_shared_hist(bins, 0); generate_input(h_input, bins, mode); /* * CPU timing. */ auto cpu_start = std::chrono::high_resolution_clock::now(); histogram_cpu(h_input.data(), h_cpu_hist.data(), n, bins); auto cpu_end = std::chrono::high_resolution_clock::now(); double cpu_ms = std::chrono::duration( cpu_end - cpu_start ).count(); int* d_input = nullptr; int* d_global_hist = nullptr; int* d_shared_hist = nullptr; CUDA_CHECK(cudaMalloc(&d_input, input_bytes)); CUDA_CHECK(cudaMalloc(&d_global_hist, hist_bytes)); CUDA_CHECK(cudaMalloc(&d_shared_hist, hist_bytes)); CUDA_CHECK(cudaMemcpy(d_input, h_input.data(), input_bytes, cudaMemcpyHostToDevice)); /* * Global atomic kernel 配置。 */ int grid_global = static_cast((n + block_size - 1) / block_size); auto launch_global = [&]() { CUDA_CHECK(cudaMemset(d_global_hist, 0, hist_bytes)); histogram_global_atomic_kernel>>( d_input, d_global_hist, n ); CUDA_CHECK(cudaGetLastError()); }; /* * Shared histogram kernel 配置。 * * 使用固定 block 数量,配合 grid-stride loop。 * 不要让 block 数过大,否则每个 block 都要合并一次 hist,global atomic 次数也会上升。 */ int sm_count = 0; CUDA_CHECK(cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, 0)); int grid_shared = sm_count * 4; size_t shared_bytes = hist_bytes; auto launch_shared = [&]() { CUDA_CHECK(cudaMemset(d_shared_hist, 0, hist_bytes)); histogram_shared_kernel>>( d_input, d_shared_hist, n, bins ); CUDA_CHECK(cudaGetLastError()); }; float global_ms = time_kernel(launch_global, repeat); float shared_ms = time_kernel(launch_shared, repeat); CUDA_CHECK(cudaMemcpy(h_global_hist.data(), d_global_hist, hist_bytes, cudaMemcpyDeviceToHost)); CUDA_CHECK(cudaMemcpy(h_shared_hist.data(), d_shared_hist, hist_bytes, cudaMemcpyDeviceToHost)); bool global_ok = check_hist(h_cpu_hist, h_global_hist, bins); bool shared_ok = check_hist(h_cpu_hist, h_shared_hist, bins); std::cout **❝Histogram 优化的本质,是把全局范围的大量写冲突,拆成 block 内局部冲突和少量全局合并。**