最大使用CUDA的绝对差异

K r*_*esh -1 c++ cuda thrust

我们有以下串行C代码在运行

两个向量a []和b []:

double a[20000],b[20000],r=0.9;

for(int i=1;i<=10000;++i)
{
    a[i]=r*a[i]+(1-r)*b[i]];
    errors=max(errors,fabs(a[i]-b[i]);
    b[i]=a[i];
}
Run Code Online (Sandbox Code Playgroud)

请告诉我们如何将此代码移植到CUDA和Cublas?

Jar*_*ock 5

使用Thrust也可以实现这种减少thrust::transform_reduce.这个解决方案融合了整个操作,正如talonmies建议的那样:

#include <thrust/device_vector.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/transform_reduce.h>
#include <thrust/functional.h>

// this functor unpacks a tuple and then computes
// a weighted absolute difference of its members
struct weighted_absolute_difference
{
  double r;

  weighted_absolute_difference(const double r)
    : r(r)
  {}

  __host__ __device__
  double operator()(thrust::tuple<double,double> t)
  {
    double a = thrust::get<0>(t);
    double b = thrust::get<1>(t);

    a = r * a + (1.0 - r) * b;

    return fabs(a - b);
  }
};

int main()
{
  using namespace thrust;

  const std::size_t n = 20000;

  const double r = 0.9;

  device_vector<double> a(n), b(n);

  // initialize a & b
  ...

  // do the reduction
  double result =
    transform_reduce(make_zip_iterator(make_tuple(a.begin(), b.begin())),
                     make_zip_iterator(make_tuple(a.end(),   b.end())),
                     weighted_absolute_difference(r),
                     -1.f,
                     maximum<double>());

  // note that this solution does not set
  // a[i] = r * a[i] + (1 - r) * b[i]

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们不会a[i] = r * a[i] + (1 - r) * b[i]在此解决方案中执行赋值,但在使用简化后执行此操作会很简单thrust::transform.transform_reduce在两个仿函数中修改参数是不安全的.