以下代码没有可能导致其在 CPU 或 GPU 上运行的信息。我想知道“reduce”操作是在哪里执行的?
#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,则可以通过重新标记
现有迭代器将调用重新定位到主机:
#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));
关于cuda - Thrust:如何直接控制算法调用的执行位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17005694/