我是CUDA的新手。
我希望以下列方式在device_vector
中复制和求和值。是否有更有效的方法(或由推力提供的功能)来实现这些?
thrust::device_vector<int> device_vectorA(5);
thrust::device_vector<int> device_vectorB(20);
以下列方式将
device_vectorA
4次转换为device_vectorB
:for (size_t i = 0; i < 4; i++)
{
offset_sta = i * 5;
thrust::copy(device_vectorA.begin(), device_vectorA.end(), device_vectorB.begin() + offset_sta);
}
device_vectorB
中的每5个值,并将结果存储在新的device_vector中(大小为4):// Example
device_vectorB = 1 2 3 4 5 | 1 2 3 4 5 | 1 2 3 4 5 | 1 2 3 4 5
device_vectorC = 15 15 15 15
thrust::device_vector<int> device_vectorC(4);
for (size_t i = 0; i < 4; i++)
{
offset_sta = i * 5;
offset_end = (i + 1) * 5 - 1;
device_vectorC[i] = thrust::reduce(device_vectorB.begin() + offset_sta, device_vectorB.begin() + offset_end, 0);
}
是否有更有效的方法(或由推力提供的功能)来实现这些?
P.S. 1和2是单独的实例。为了简单起见,这两个实例只是使用相同的向量来说明。
发布于 2022-10-13 05:41:44
步骤1可以使用一个置换迭代器完成::复制操作,该迭代器使用在计数迭代器上工作的转换迭代器来“动态”生成副本索引。
第2步是分区缩减,使用thrust::reduce_by_key。我们可以再次使用转换迭代器在计数迭代器上“动态”创建标志数组。
下面是一个示例:
$ cat t2124.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/copy.h>
#include <thrust/reduce.h>
#include <thrust/sequence.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <iostream>
using namespace thrust::placeholders;
const int As = 5;
const int Cs = 4;
const int Bs = As*Cs;
int main(){
thrust::device_vector<int> A(As);
thrust::device_vector<int> B(Bs);
thrust::device_vector<int> C(Cs);
thrust::sequence(A.begin(), A.end(), 1); // fill A with 1,2,3,4,5
thrust::copy_n(thrust::make_permutation_iterator(A.begin(), thrust::make_transform_iterator(thrust::counting_iterator<int>(0), _1%A.size())), B.size(), B.begin()); // step 1
auto my_flags_iterator = thrust::make_transform_iterator(thrust::counting_iterator<int>(0), _1/A.size());
thrust::reduce_by_key(my_flags_iterator, my_flags_iterator+B.size(), B.begin(), thrust::make_discard_iterator(), C.begin()); // step 2
thrust::host_vector<int> Ch = C;
thrust::copy_n(Ch.begin(), Ch.size(), std::ostream_iterator<int>(std::cout, ","));
std::cout << std::endl;
}
$ nvcc -o t2124 t2124.cu
$ compute-sanitizer ./t2124
========= COMPUTE-SANITIZER
15,15,15,15,
========= ERROR SUMMARY: 0 errors
$
如果我们愿意的话,即使是设备向量A
也可以被取消;这可以使用计数迭代器“动态”创建。但想必你的投入实际上不是1,2,3,4,5
https://stackoverflow.com/questions/74049426
复制相似问题