推力:如何直接控制算法调用的执行位置



以下代码没有任何可能导致它在 CPU 或 GPU 上运行的信息。我想知道"减少"操作在哪里执行?

#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)

此外

thrust::transform_reduce(
    thrust::counting_iterator<unsigned int>(0), 
    thrust::counting_iterator<unsigned int>(N), 
    MyOperation(data), 0 ,thrust::plus<unsigned int>())

即使数据定义为 thrust::host_vector,此函数也会尝试在 GPU 上执行(编译器会给出相关错误,因为文件名以 .cpp 结尾(。我怎样才能使代码在 CPU 上运行。或者我应该寻找另一种方法来执行相同的操作,例如不使用counting_iterator?

默认情况下,像这样的算法调用在设备后端(即您的情况下为 GPU(上执行。

如果您使用的是 Thrust 1.7 或更高版本,请使用 thrust::host 执行策略强制在主机(即 CPU(上执行算法调用:

#include <thrust/execution_policy.h>
...
thrust::reduce(thrust::host, first, last);
...
thrust::transform_reduce(thrust::host,
                         first,
                         last,
                         MyOperation(data),
                         0,
                         thrust::plus<unsigned int>());

如果您使用的是 Thrust 1.6,则可以通过retag现有迭代器来将调用重新定位到主机:

#include <thrust/iterator/retag.h>
...
thrust::reduce(thrust::retag<thrust::host_system_tag>(first),
               thrust::retag<thrust::host_system_tag>(last));
...
thrust::transform_reduce(thrust::retag<thrust::host_system_tag>(first),
                         thrust::retag<thrust::host_system_tag>(last),
                         MyOperation(data),
                         0,
                         thrust::plus<unsigned int>());

如果您使用的是 1.6 之前的旧版 Thrust,则需要将 host_space_tag 传递给 counting_iterator 作为模板参数:

thrust::reduce(thrust::counting_iterator<unsigned int, thrust::host_space_tag>(0),
               thrust::counting_iterator<unsigned int, thrust::host_space_tag>(N));

最新更新