当前位置: 首页 > article >正文

Thrust库中的Gather和Scatter操作

Thrust库中的Gather和Scatter操作

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

Gather操作

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

函数原型:

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

示例:

#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操作将源数组的元素按照指定的索引分散到目标数组中。

函数原型:

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

示例:

#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上实现的类似操作要快得多。

http://www.lryc.cn/news/2379020.html

相关文章:

  • 计算机发展的历程
  • 深度学习驱动下的目标检测技术:原理、算法与应用创新(三)
  • Python爬虫实战:研究 RPC 远程调用机制,实现逆向解密
  • [学习] RTKLib详解:qzslex.c、rcvraw.c与solution.c
  • jenkins流水线常规配置教程!
  • Java中序列化和反序列化的理解
  • 基于OpenCV的SIFT特征和FLANN匹配器的指纹认证
  • 零基础学Java——第十一章:实战项目 - 桌面应用开发(JavaFX入门)
  • Milvus 视角看主流嵌入式模型(Embeddings)
  • leetcode:58. 最后一个单词的长度(python3解法)
  • 虹科应用 | 探索PCAN卡与医疗机器人的革命性结合
  • entity线段材质设置
  • [STM32] 5-1 时钟树(上)
  • 【Linux网络与网络编程】12.NAT技术内网穿透代理服务
  • 【​​HTTPS基础概念与原理​】TLS握手过程详解​​
  • 从辅助到协作:GitHub Copilot的进化之路
  • Linux运行时的参数、命令、网络、磁盘参数和日志监控
  • 鸿蒙页面布局入门
  • VTK|类似CloudCompare的比例尺实现2-vtk实现
  • 阿里巴巴开源移动端多模态LLM工具——MNN
  • 【漫话机器学习系列】256.用 k-NN 填补缺失值
  • React组件(一):生命周期
  • 金格iWebOffice控件在新版谷歌Chrome中不能加载了怎么办?
  • 实验6分类汇总
  • 如何通过交流沟通实现闭环思考模式不断实现自身强效赋能-250517
  • Python 3.11详细安装步骤(包含安装包)Python 3.11详细图文安装教程
  • [深度解析] 服务器内存(RAM)演进之路(2025):DDR5 vs HBM vs CXL 内存技术与选型指南
  • C语言输入函数对比解析
  • 【Java-EE进阶】SpringBoot针对某个IP限流问题
  • 一个指令,让任意 AI 快速生成思维导图