【问题标题】:How to remove a nested loop with CUDA Thrust for an all-pair distance check?如何使用 CUDA Thrust 删除嵌套循环以进行全对距离检查?
【发布时间】:2017-04-24 08:51:50
【问题描述】:

我有两个数组 array1array2 分别带有 nm 元素。我想找到元素之间的所有对距离。 CPU上的蛮力算法是:

for(int i =0; i<n; i++)
{
    for(int j =0; j<m; j++)
    {
         array_pair_distances[i][j] = array1[i]-array2[j];
    }       
}

使用 CUDA Thrust 我只是通过使用thrust::transform 和一个for 循环将这个n*m 问题变成了n 或m 问题。我的问题是如何使用 Thrust 删除最后一个 for 循环?

编辑:添加了 Thrust 和一个 for 循环的实现示例。代码检查pair-distance是否大于0.1并返回一个int。

#include <stdio.h>
#include <iostream>
#include <cuda.h>

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/random.h>
#include <thrust/fill.h>
#include <thrust/transform.h>
#include <thrust/reduce.h>

struct PairDistanceCheck : public thrust::binary_function<float,float,int>
{
    __host__ __device__
        int operator()(const float& a, const float& b) const
        {
           if(thrust::get<0>(a) - thrust::get<0>(b) > 0.1)
           {
                return 1;
           } 
           else return 0;
        }
};

void function()
{
    int n = 1000;
    int m = 2000;

    // Initialization of host vectors 
    thrust::host_vector<float> h_1 (n);
    thrust::host_vector<float> h_2 (m);

    // Fill host_vectors with data
    *
    *
    *
    //

    // Copy host_vectors to device_vectors
    thrust::device_vector<float> d_1 = h_1;
    thrust::device_vector<float> d_2 = h_2;

    thrust::device_vector<float> d_temp (m);

    thrust::device_vector<int> d_sum (m);
    thrust::fill(d_sum.begin(), d_sum.end(), 0);

    thrust::device_vector<int> d_result (m);

    for (int i=0; i<n; i++)
    {
        // Filling device_vector d_temp with element i from d_2
        thrust::fill(d_temp.begin(), d_temp.end(), d_2[i]);

        thrust::transform((d_1.begin(), d_1.end(), d_temp.begin(), d_result.begin(), PairDistanceCheck());

        // Summing the vectors
        thrust::transform(d_sum.begin(), d_sum.end(), d_result.begin(), d_sum.begin(), thrust::plus<int>());

    }

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

    return 0;
}

【问题讨论】:

  • 有任何代码可以显示您的失败尝试吗?看看这个how-to-ask
  • 我的错。现在添加了一个示例。

标签: c++ loops cuda nested thrust


【解决方案1】:

非常简短的回答是你不能。

Thrust 没有外积算法,这是执行您感兴趣的那种计算所必需的。您可以通过用两个矩阵的行/列填充两个矩阵来做到这一点输入向量,然后直接减去它们。但与适当的外部产品实现相比,这将是非常低效的(内存和性能)。

【讨论】:

  • 这就是我所害怕的。那么,如果我想做一个合适的外部产品实现,我应该从哪里开始呢?
猜你喜欢
  • 1970-01-01
  • 2013-09-16
  • 2011-07-14
  • 1970-01-01
  • 2018-08-12
  • 2018-02-08
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
相关资源
最近更新 更多