CUDA从入门到放弃(十四):CUDA Thrust库

news/2024/7/27 8:35:53/文章来源:https://blog.csdn.net/shanglianlm/article/details/137131240

CUDA从入门到放弃(十四):CUDA Thrust库

Thrust 是一个基于标准模板库(STL)的 C++ 模板库,专为 CUDA 设计,旨在简化高性能并行应用的开发。它提供了一系列数据并行原语,如扫描、排序和归约,可组合实现复杂算法。通过高级抽象描述计算,Thrust 能自动选择最优实现,适用于 CUDA 应用的快速原型设计和生产环境,提高程序员生产率和性能。

1 安装

安装 CUDA Toolkit 会将 Thrust 的头文件复制到您系统的标准 CUDA 包含目录中。由于 Thrust 是一个由头文件组成的模板库,因此无需进行其他安装步骤即可开始使用 Thrust。

2 Vectors

Thrust 提供了 host_vector 和 device_vector 两种向量容器,分别用于主机和 GPU 设备内存。它们类似于 C++ STL 中的 std::vector,是泛型容器,可动态调整大小。使用 = 运算符可以轻松地复制容器内容。device_vector 的元素可以通过标准括号访问,但应谨慎使用,因为每次访问都涉及内存复制。

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>#include <iostream>int main(void)
{// H has storage for 4 integersthrust::host_vector<int> H(4);// initialize individual elementsH[0] = 14;H[1] = 20;H[2] = 38;H[3] = 46;// H.size() returns the size of vector Hstd::cout << "H has size " << H.size() << std::endl;// print contents of Hfor(int i = 0; i < H.size(); i++)std::cout << "H[" << i << "] = " << H[i] << std::endl;// resize HH.resize(2);std::cout << "H now has size " << H.size() << std::endl;// Copy host_vector H to device_vector Dthrust::device_vector<int> D = H;// elements of D can be modifiedD[0] = 99;D[1] = 88;// print contents of Dfor(int i = 0; i < D.size(); i++)std::cout << "D[" << i << "] = " << D[i] << std::endl;// H and D are automatically deleted when the function returnsreturn 0;
}

Thrust 还提供了初始化向量元素和复制特定值集的方法。

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/sequence.h>#include <iostream>int main(void)
{// initialize all ten integers of a device_vector to 1thrust::device_vector<int> D(10, 1);// set the first seven elements of a vector to 9thrust::fill(D.begin(), D.begin() + 7, 9);// initialize a host_vector with the first five elements of Dthrust::host_vector<int> H(D.begin(), D.begin() + 5);// set the elements of H to 0, 1, 2, 3, ...thrust::sequence(H.begin(), H.end());// copy all of H back to the beginning of Dthrust::copy(H.begin(), H.end(), D.begin());// print Dfor(int i = 0; i < D.size(); i++)std::cout << "D[" << i << "] = " << D[i] << std::endl;return 0;
}

2-1 Thrust 命名空间

Thrust 命名空间允许我们调用特定的函数或类,如 thrust::host_vector 和 thrust::copy,从而避免与其他库中的函数或类名称冲突。

2-2 迭代器与静态分发 Iterators and Static Dispatching

在 Thrust 中,迭代器类似于指针,用于访问容器中的元素。Thrust 函数通过检查迭代器的类型,自动决定使用主机还是设备实现,这个过程称为静态分发,它在编译时确定,没有运行时开销。

原始指针和device_ptr 互相转换:
如果使用原始指针作为参数,Thrust 会默认使用主机路径。若指针指向设备内存,则需要用 thrust::device_ptr 包装后再调用函数。

size_t N = 10;// raw pointer to device memory
int * raw_ptr;
cudaMalloc((void **) &raw_ptr, N * sizeof(int));// wrap raw pointer with a device_ptr
thrust::device_ptr<int> dev_ptr(raw_ptr);// use device_ptr in thrust algorithms
thrust::fill(dev_ptr, dev_ptr + N, (int) 0);

从 device_ptr 中提取原始指针:

size_t N = 10;// create a device_ptr
thrust::device_ptr<int> dev_ptr = thrust::device_malloc<int>(N);// extract raw pointer from device_ptr
int * raw_ptr = thrust::raw_pointer_cast(dev_ptr);

STL 和 互相转换:

#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <list>
#include <vector>int main(void)
{// create an STL list with 4 valuesstd::list<int> stl_list;stl_list.push_back(10);stl_list.push_back(20);stl_list.push_back(30);stl_list.push_back(40);// initialize a device_vector with the listthrust::device_vector<int> D(stl_list.begin(), stl_list.end());// copy a device_vector into an STL vectorstd::vector<int> stl_vector(D.size());thrust::copy(D.begin(), D.end(), stl_vector.begin());return 0;
}

3 Algorithms

Thrust 提供众多常见并行算法,其中许多与 STL 中的算法相对应,并采用相同名称。这些算法都有主机和设备的实现,根据使用的迭代器类型自动选择执行路径。除了 thrust::copy 外,Thrust 算法的迭代器参数应全部位于同一位置(主机或设备),否则编译器会报错。

3-1 Transformations

以下源代码演示了几种转换算法。

#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/replace.h>
#include <thrust/functional.h>
#include <iostream>int main(void)
{// allocate three device_vectors with 10 elementsthrust::device_vector<int> X(10);thrust::device_vector<int> Y(10);thrust::device_vector<int> Z(10);// initialize X to 0,1,2,3, ....thrust::sequence(X.begin(), X.end());// compute Y = -Xthrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>());// fill Z with twosthrust::fill(Z.begin(), Z.end(), 2);// compute Y = X mod 2thrust::transform(X.begin(), X.end(), Z.begin(), Y.begin(), thrust::modulus<int>());// replace all the ones in Y with tensthrust::replace(Y.begin(), Y.end(), 1, 10);// print Ythrust::copy(Y.begin(), Y.end(), std::ostream_iterator<int>(std::cout, "\n"));return 0;
}

3-2 Reductions

归约算法使用二元操作将输入序列减少到单个值。
例如,通过使用加法操作对数字数组进行归约,可以得到数组的和。使用 thrust::reduce 实现数组的和如下:

int sum = thrust::reduce(D.begin(), D.end(), (int) 0, thrust::plus<int>());

通过使用接受两个输入并返回最大值的操作符进行归约,可以得到数组的最大值。

 int max_value = thrust::reduce(data.begin(), data.end(),  data[0], // 初始值  thrust::maximum<int>()); // 自定义操作符  

thrust::count 返回给定序列中特定值的实例数量。

int result = thrust::count(vec.begin(), vec.end(), 1);

3-3 Prefix-Sums

并行前缀和,或扫描操作,是许多并行算法(如流压缩和基数排序)中的重要组成部分。
以下代码演示了使用默认加法运算符的 inclusive_scan 操作:

#include <thrust/scan.h>int data[6] = {1, 0, 2, 2, 1, 3};thrust::inclusive_scan(data, data + 6, data); // in-place scan// data is now {1, 1, 3, 5, 6, 9}

在包含扫描中,输出序列的每个元素都是输入范围内相应部分的和。例如,data[2] = data[0] + data[1] + data[2]。

exclusive scan 类似,但向右移动了一个位置:

#include <thrust/scan.h>int data[6] = {1, 0, 2, 2, 1, 3};thrust::exclusive_scan(data, data + 6, data); // in-place scan// data is now {0, 1, 1, 3, 5, 6}

因此,现在 data[2] = data[0] + data[1]。

Thrust 还提供了 transform_inclusive_scan 和 transform_exclusive_scan 函数,它们在执行扫描之前对输入序列应用一元函数。

3-4 Reordering

Thrust 通过以下算法提供了对分区和流压缩的支持:

  • copy_if:复制满足特定断言条件的元素到一个新的容器
#include <thrust/copy_if.h>  
#include <thrust/device_vector.h>  
#include <thrust/functional.h> // for thrust::is_even  
#include <iostream>  int main(void)  
{  // 初始化设备向量  thrust::device_vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  // 创建一个空的设备向量用于存储结果  thrust::device_vector<int> even_numbers(data.size());  // 使用 copy_if 复制偶数  // 注意:copy_if 的结果迭代器是输出范围的开始迭代器  thrust::copy_if(data.begin(), data.end(),  even_numbers.begin(),  thrust::is_even<int>()); // 断言条件:检查是否为偶数  // 获取实际复制的元素数量  size_t even_count = thrust::distance(even_numbers.begin(),  thrust::remove_if(even_numbers.begin(), even_numbers.end(), thrust::not1(thrust::is_even<int>())).end());  // 调整 even_numbers 的大小以匹配实际元素数量  even_numbers.resize(even_count);  // 输出结果  std::cout << "Even numbers: ";  thrust::copy(even_numbers.begin(), even_numbers.end(), std::ostream_iterator<int>(std::cout, " "));  std::cout << std::endl;  return 0;  
}
  • partition:partition 函数会根据提供的断言条件重新排列输入序列中的元素,使得满足条件的元素出现在不满足条件的元素之前。
#include <thrust/partition.h>  
#include <thrust/device_vector.h>  
#include <thrust/functional.h> // for thrust::less  
#include <iostream>  int main(void)  
{  // 初始化设备向量  thrust::device_vector<int> data = {1, 3, 2, 5, 4, 6, 7, 8, 9, 10};  // 使用 partition 重新排列数据,使得小于 5 的数在前  thrust::partition(data.begin(), data.end(), thrust::less<int>(5));  // 输出结果  std::cout << "Partitioned data: ";  thrust::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));  std::cout << std::endl;  return 0;  
}
  • remove 和 remove_if:remove函数会移除给定序列中等于某个特定值的所有元素,而remove_if函数则会根据提供的断言条件移除元素。
#include <thrust/remove.h>  
#include <thrust/device_vector.h>  
#include <thrust/copy.h>  
#include <iostream>  int main(void)  
{  // 初始化设备向量  thrust::device_vector<int> data = {1, 2, 3, 2, 4, 2, 5, 6};  // 使用 remove 移除所有值为 2 的元素  thrust::device_vector<int>::iterator new_end = thrust::remove(data.begin(), data.end(), 2);  // 使用 remove_if 移除所有大于 5 的元素  // thrust::device_vector<int>::iterator new_end = thrust::remove_if(data.begin(), data.end(), thrust::greater<int>(5));// 调整数据向量的大小以匹配新的末尾迭代器  data.resize(thrust::distance(data.begin(), new_end));  // 输出结果  std::cout << "Data after removing 2s: ";  thrust::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));  std::cout << std::endl;  return 0;  
}
  • unique:unique函数会移除序列中连续重复的元素,使得每个元素只出现一次。
#include <thrust/unique.h>  
#include <thrust/device_vector.h>  
#include <thrust/copy.h>  
#include <iostream>  int main(void)  
{  // 初始化设备向量  thrust::device_vector<int> data = {1, 2, 2, 3, 4, 4, 4, 5, 6, 6};  // 使用 unique 移除连续重复的元素  thrust::device_vector<int>::iterator new_end = thrust::unique(data.begin(), data.end());  // 调整数据向量的大小以匹配新的末尾迭代器  data.resize(thrust::distance(data.begin(), new_end));  // 输出结果  std::cout << "Data after removing consecutive duplicates: ";  thrust::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));  std::cout << std::endl;  return 0;  
}

3-5 Sorting

Thrust 提供多种函数,可按给定条件排序或重新排列数据。其中,thrust::sort 和 thrust::stable_sort 与 STL 中的对应函数相似。

#include <thrust/sort.h>...
const int N = 6;
int A[N] = {1, 4, 2, 8, 5, 7};thrust::sort(A, A + N);// A is now {1, 2, 4, 5, 7, 8}

此外,Thrust 还有 thrust::sort_by_key 和 thrust::stable_sort_by_key,用于排序分别存储的键值对。

#include <thrust/sort.h>...
const int N = 6;
int    keys[N] = {  1,   4,   2,   8,   5,   7};
char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'};thrust::sort_by_key(keys, keys + N, values);// keys is now   {  1,   2,   4,   5,   7,   8}
// values is now {'a', 'c', 'b', 'e', 'f', 'd'}

这些排序函数也支持用户自定义比较操作符。

#include <thrust/sort.h>
#include <thrust/functional.h>...
const int N = 6;
int A[N] = {1, 4, 2, 8, 5, 7};thrust::stable_sort(A, A + N, thrust::greater<int>());// A is now {8, 7, 5, 4, 2, 1}

4 Fancy Iterators

4-1 constant_iterator

constant_iterator 是一种简单的迭代器,它在每次访问时返回相同的值。

#include <thrust/iterator/constant_iterator.h>
...
// create iterators
thrust::constant_iterator<int> first(10);
thrust::constant_iterator<int> last = first + 3;first[0]   // returns 10
first[1]   // returns 10
first[100] // returns 10// sum of [first, last)
thrust::reduce(first, last);   // returns 30 (i.e. 3 * 10)

4-2 counting_iterator

counting_iterator 生成递增的序列。

#include <thrust/iterator/counting_iterator.h>
...
// create iterators
thrust::counting_iterator<int> first(10);
thrust::counting_iterator<int> last = first + 3;first[0]   // returns 10
first[1]   // returns 11
first[100] // returns 110// sum of [first, last)
thrust::reduce(first, last);   // returns 33 (i.e. 10 + 11 + 12)

4-3 transform_iterator

transform_iterator 允许我们对序列中的每个元素应用转换。

#include <thrust/iterator/transform_iterator.h>
// initialize vector
thrust::device_vector<int> vec(3);
vec[0] = 10; vec[1] = 20; vec[2] = 30;// create iterator (type omitted)
...
first = thrust::make_transform_iterator(vec.begin(), negate<int>());
...
last  = thrust::make_transform_iterator(vec.end(),   negate<int>());first[0]   // returns -10
first[1]   // returns -20
first[2]   // returns -30// sum of [first, last)
thrust::reduce(first, last);   // returns -60 (i.e. -10 + -20 + -30)// 或者
// sum of [first, last)
thrust::reduce(thrust::make_transform_iterator(vec.begin(), negate<int>()),thrust::make_transform_iterator(vec.end(),   negate<int>()));

4-4 permutation_iterator

permutation_iterator 允许我们重新排列序列中元素的顺序。通过指定一个映射,我们可以按特定顺序访问元素:

#include <thrust/iterator/permutation_iterator.h>...// gather locations
thrust::device_vector<int> map(4);
map[0] = 3;
map[1] = 1;
map[2] = 0;
map[3] = 5;// array to gather from
thrust::device_vector<int> source(6);
source[0] = 10;
source[1] = 20;
source[2] = 30;
source[3] = 40;
source[4] = 50;
source[5] = 60;// fuse gather with reduction:
//   sum = source[map[0]] + source[map[1]] + ...
int sum = thrust::reduce(thrust::make_permutation_iterator(source.begin(), map.begin()),thrust::make_permutation_iterator(source.begin(), map.end()));

4-5 zip_iterator

zip_iterator 可以将多个序列合并为一个元组序列。这使得我们可以同时处理多个序列:

#include <thrust/iterator/zip_iterator.h>
...
// initialize vectors
thrust::device_vector<int>  A(3);
thrust::device_vector<char> B(3);
A[0] = 10;  A[1] = 20;  A[2] = 30;
B[0] = 'x'; B[1] = 'y'; B[2] = 'z';// create iterator (type omitted)
first = thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin()));
last  = thrust::make_zip_iterator(thrust::make_tuple(A.end(),   B.end()));first[0]   // returns tuple(10, 'x')
first[1]   // returns tuple(20, 'y')
first[2]   // returns tuple(30, 'z')// maximum of [first, last)
thrust::maximum< tuple<int,char> > binary_op;
thrust::tuple<int,char> init = first[0];
thrust::reduce(first, last, init, binary_op); // returns tuple(30, 'z')

参考资料
1 Thrust docs
2 Thrust: The C++ Parallel Algorithms Library

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_1034596.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

增强Java技能:使用OkHttp下载www.dianping.com信息

在这篇技术文章中&#xff0c;我们将探讨如何使用Java和OkHttp库来下载并解析www.dianping.com上的商家信息。我们的目标是获取商家名称、价格、评分和评论&#xff0c;并将这些数据存储到CSV文件中。此外&#xff0c;我们将使用爬虫代理来绕过任何潜在的IP限制&#xff0c;并实…

浅谈物联网高速公路智慧配电室系统构建方案

关键词&#xff1a;高速公路&#xff1b;智慧供配电&#xff1b;电力监控&#xff1b;配电室智能运维托管&#xff1b;安全隐患 0、引言 随着高速公路事业的不断发展和路网的不断延伸&#xff0c;传统的管理方式已难以满足日益增长的需求&#xff0c;动态管理和安全隐患预警成…

Java项目:85 springboot智能物流管理系统

作者主页&#xff1a;源码空间codegym 简介&#xff1a;Java领域优质创作者、Java项目、学习资料、技术互助 文中获取源码 作者主页&#xff1a;舒克日记 简介&#xff1a;Java领域优质创作者、Java项目、学习资料、技术互助 文中获取源码 项目介绍 本美发门店管理系统有管理员…

SpringBoot | Spring Boot“整合Redis“

目录: 1. Redis 介绍2. Redis 下载安装3. Redis “服务开启”和“连接配置”4. Spring Boot整合Redis的“前期准备” :① 编写实体类② 编写Repository 接口③ 在“全局配置文件”中添加 “Redis数据库” 的 “相关配置信息” 5. Spring Boot整合“Redis” (案例展示) 作者简介…

QA测试开发工程师面试题满分问答6: 如何判断接口功能正常?从QA的角度设计测试用例

判断接口功能是否正常的方法之一是设计并执行相关的测试用例。下面是从测试QA的角度设计接口测试用例的一些建议&#xff0c;包括功能、边界、异常、链路、上下游和并发等方面&#xff1a; 通过综合考虑这些测试维度&#xff0c;并设计相应的测试用例&#xff0c;可以更全面地评…

设计模式之装饰模式精讲

概念&#xff1a;动态地给一个对象添加一些额外的职责。 装饰器模式侧重于在不改变接口的前提下动态地给对象添加新功能&#xff0c;保持对象结构的透明性&#xff0c;客户端无感知。 以一个咖啡制作和装饰的例子来帮助大家理解&#xff1a; public interface Coffee {double…

esp32中vscode的开发环境

vscode中安装esp32开发环境请参考&#xff1a;CSDN 1、调出esp32的控制面板View ->Command Paletter&#xff0c;或者快捷键&#xff08;ctrshitp&#xff09; 调出esp-idf的样例工程 选择ESP-IDF所在的安装路径 选择一个样例工程&#xff0c;作为工程模板 创建的新工程如…

docker部署DOS游戏

下载镜像 docker pull registry.cn-beijing.aliyuncs.com/wuxingge123/dosgame-web-docker:latestdocker-compose部署 vim docker-compose.yml version: 3 services:dosgame:container_name: dosgameimage: registry.cn-beijing.aliyuncs.com/wuxingge123/dosgame-web-docke…

电子积木方案开发商

东莞市酷得智能科技有限公司电子积木方案开发商 提供消费电子解决方案、提供IC技术支持&#xff0c;全国线上线下服务 积木小车底层驱动开发过程主要涉及到以下几个方面&#xff1a; 首先&#xff0c;需要对小车底盘结构、硬件、模块等有深入的了解。底盘承载着机器人定位、导…

Android adb ime 调试输入法

目录 前言列出所有输入法仅列出输入法 id列出所有输入法的所有信息 启用/禁用 输入法启用输入法禁用输入法 切换输入法还原输入法 前言 安装多个输入法后&#xff0c;可以在设置里进行切换。 既然是开发&#xff0c;能用命令就就命令~ ime 帮助说明&#xff1a; ime <c…

入门级深度学习主机组装过程

一 配置 先附上电脑配置图&#xff0c;如下&#xff1a; 利用公司的办公电脑对配置进行升级改造完成。除了显卡和电源&#xff0c;其他硬件都是公司电脑原装。 二 显卡 有钱直接上 RTX4090&#xff0c;也不能复用公司的电脑&#xff0c;其他配置跟不上。 进行深度学习&…

面试题 之 vue

1.vue里怎样实现双向数据绑定&#xff1f; Viewmodel 中的Domlisteners 工具会帮我们检测页面上Dom元素的变化&#xff0c;如果有变化&#xff0c;则更改Model中的数据&#xff0c;更新model中的数据时&#xff0c;数据事件绑定工具会帮我们更新页面中的Dom元素 2.Vue的响应式原…

59 使用 uqrcodejs 生成二维码

前言 这是一个最近的一个来自于朋友的需求, 然后做了一个 基于 uqrcodejs 来生成 二维码的一个 demo package.json 中增加以依赖 "uqrcodejs": "^4.0.7", 测试用例 <template><div class"hello"><canvas id"qrcode&qu…

数据库-root密码丢失的重置方案(win11环境)

当在windows系统中安装的mysql由于操作不当&#xff0c;或者密码遗忘&#xff0c;今天测试了一下&#xff0c;可以用以下方法重置root的密码。 mysqlwindows环境root密码重置问题 在win10/11环境下mysql8密码遗忘后的重置密码方案。 停止mysql服务 查找windows中的mysql服务名称…

【讲解下Gitea】

&#x1f308;个人主页:程序员不想敲代码啊 &#x1f3c6;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f44d;点赞⭐评论⭐收藏 &#x1f91d;希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff0c;让我们共…

day02-SpringCloud02(Nacos、Feign、Gateway)

1.Nacos 配置管理 Nacos 除了可以做注册中心&#xff0c;同样可以做配置管理来使用。 1.1.统一配置管理 当微服务部署的实例越来越多&#xff0c;达到数十、数百时&#xff0c;逐个修改微服务配置就会让人抓狂&#xff0c;而且很容易出错。我们需要一种统一配置管理方案&#x…

图论做题笔记:dfs

Leetcode - 797&#xff1a;所有可能的路径 题目&#xff1a; 给你一个有 n 个节点的 有向无环图&#xff08;DAG&#xff09;&#xff0c;请你找出所有从节点 0 到节点 n-1 的路径并输出&#xff08;不要求按特定顺序&#xff09; graph[i] 是一个从节点 i 可以访问的所有节…

HTTPS跟HTTP有区别吗?

HTTPS和HTTP的区别&#xff0c;白话一点说就是&#xff1a; 1. 安全程度&#xff1a; - HTTP&#xff1a;就像是你和朋友面对面聊天&#xff0c;说的话大家都能听见&#xff08;信息明文传输&#xff0c;容易被偷听&#xff09;。 - HTTPS&#xff1a;就像是你们俩戴着加密耳机…

C#属性显示

功能&#xff1a; 显示对象的属性&#xff0c;包括可显示属性、可编辑属性、及不可编辑属性。 1、MainWindow.xaml <Window x:Class"FlowChart.MainWindow"xmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x"http://sche…

AI 论道|极狐GitLab 客户私享会上海站成功举办

3 月 22 日下午&#xff0c;极狐GitLab 在上海办公室举办了客户私享会&#xff0c;邀请了来自多个行业的多家客户&#xff0c;围绕 AI 提升研发效率的道法术器进行了充分交流。整个交流时长达两个多小时。 极狐GitLab 战略业务与区域发展副总裁何庆出席了此次活动并致开场辞。他…