Thrust库中的Gather和Scatter操作

Thrust库中的Gather和Scatter操作

Thrust是CUDA提供的一个类似于C++ STL的并行算法库,其中包含两个重要的数据操作:gather(聚集)和scatter(散开)。

Gather操作

Gather操作从一个源数组中按照指定的索引收集元素到目标数组中。

函数原型:

cpp 复制代码
template<typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator gather(InputIterator1 map_first, 
                     InputIterator1 map_last,
                     InputIterator2 input_first, 
                     OutputIterator result);

工作方式:

复制代码
result[i] = input[map[i]] 对于 map中的每个索引i

示例:

cpp 复制代码
#include <thrust/gather.h>
#include <thrust/device_vector.h>

// 源数据
thrust::device_vector<int> input(4);
input[0] = 10; input[1] = 20; input[2] = 30; input[3] = 40;

// 索引映射
thrust::device_vector<int> map(3);
map[0] = 3; map[1] = 1; map[2] = 2;

// 目标向量
thrust::device_vector<int> result(3);

// 执行gather操作
thrust::gather(map.begin(), map.end(), input.begin(), result.begin());
// result现在包含 [40, 20, 30]

Scatter操作

Scatter操作将源数组的元素按照指定的索引分散到目标数组中。

函数原型:

cpp 复制代码
template<typename InputIterator1, typename InputIterator2, typename InputIterator3, typename OutputIterator>
OutputIterator scatter(InputIterator1 first, 
                      InputIterator1 last,
                      InputIterator2 map_first, 
                      InputIterator3 stencil,
                      OutputIterator result);

工作方式:

复制代码
result[map[i]] = input[i] 对于 map中的每个索引i

示例:

cpp 复制代码
#include <thrust/scatter.h>
#include <thrust/device_vector.h>

// 源数据
thrust::device_vector<int> input(3);
input[0] = 10; input[1] = 20; input[2] = 30;

// 索引映射
thrust::device_vector<int> map(3);
map[0] = 3; map[1] = 1; map[2] = 2;

// 目标向量(需要足够大)
thrust::device_vector<int> result(4);

// 执行scatter操作
thrust::scatter(input.begin(), input.end(), map.begin(), result.begin());
// result现在包含 [0, 20, 30, 10] (初始值为0)

应用场景

  1. 数据重排:当需要按照特定顺序重新排列数据时
  2. 稀疏矩阵操作:在稀疏矩阵计算中高效地访问非零元素
  3. 数据库操作:实现类似SQL中的选择和投影操作
  4. 图像处理:像素重映射操作

变体函数

Thrust还提供了一些变体函数:

  • gather_if:带条件的gather操作
  • scatter_if:带条件的scatter操作
  • stable_scatter:保持相对顺序的scatter操作

这些操作在GPU上高度优化,能够充分利用并行计算能力,比在CPU上实现的类似操作要快得多。

相关推荐
I_belong_to_jesus5 天前
tiny-gpu入门4: ALU模块分析
gpu算力·gpu
算家计算9 天前
推理成本吞噬AI未来,云计算如何平衡速度与成本的难题?
人工智能·云计算·gpu
扫地的小何尚11 天前
AI创新的火花:NVIDIA DGX Spark开箱与深度解析
大数据·人工智能·spark·llm·gpu·nvidia·dgx
扫地的小何尚12 天前
一小时内使用NVIDIA Nemotron创建你自己的Bash计算机使用智能体
开发语言·人工智能·chrome·bash·gpu·nvidia
胡耀超12 天前
5、服务器互连技术(小白入门版)
服务器·网络·ai·网络拓扑·gpu·pcie·1024程序员节
七宝大爷13 天前
NVIDIA Blackwell Ultra GB300深度解析:AI芯片性能的新巅峰
人工智能·gpu·gb300
AAA小肥杨16 天前
基于k8s的Python的分布式深度学习训练平台搭建简单实践
人工智能·分布式·python·ai·kubernetes·gpu
爱听歌的周童鞋17 天前
斯坦福大学 | CS336 | 从零开始构建语言模型 | Spring 2025 | 笔记 | Lecture 5: GPUs
llm·gpu·flashattention·cs336·tiling
文火冰糖的硅基工坊18 天前
[创业之路-702]:“第三次”与“第四次工业革命”的范式跃迁
大数据·人工智能·科技·嵌入式硬件·架构·嵌入式·gpu
文火冰糖的硅基工坊18 天前
[嵌入式系统-136]:主流AIOT智能体软件技术栈
嵌入式硬件·架构·嵌入式·cpu·gpu