涉及去除矢量元素的推力矢量变换

时间:2013-01-31 05:42:19

标签: cuda thrust cublas bspline

我有一个推力device_vector分为100个块(但在GPU内存上完全连续),我想删除每个块的最后5个元素,而不必重新分配新的device_vector来复制它。

// Layout in memory before (number of elements in each contiguous subblock listed):
// [   95   | 5 ][   95   | 5 ][   95   | 5 ]........

// Layout in memory after cutting out the last 5 of each chunk (number of elements listed)
// [  95  ][  95  ][  95  ].........

thrust::device_vector v;
// call some function on v;

// so elements 95-99, 195-99, 295-299, etc are removed (assuming 0-based indexing)

如何正确实现此功能?我希望避免在GPU内存中分配新的向量以保存转换。我知道有Thrust模板函数来处理这些类型的操作,但是我很难将它们串在一起。 Thrust提供的东西能做到吗?

1 个答案:

答案 0 :(得分:1)

不分配缓冲区mem意味着您必须保留复制顺序,这不能与完全利用GPU硬件并行。

这是使用Thrust和缓冲存储器执行此操作的版本。

它需要Thrust 1.6.0+,因为lambda表达式functor用于迭代器。

#include "thrust/device_vector.h"
#include "thrust/iterator/counting_iterator.h"
#include "thrust/iterator/permutation_iterator.h"
#include "thrust/iterator/transform_iterator.h"
#include "thrust/copy.h"
#include "thrust/functional.h"

using namespace thrust::placeholders;

int main()
{
    const int oldChunk = 100, newChunk = 95;
    const int size = 10000;

    thrust::device_vector<float> v(
            thrust::counting_iterator<float>(0),
            thrust::counting_iterator<float>(0) + oldChunk * size);
    thrust::device_vector<float> buf(newChunk * size);

    thrust::copy(
            thrust::make_permutation_iterator(
                    v.begin(),
                    thrust::make_transform_iterator(
                            thrust::counting_iterator<int>(0),
                            _1 / newChunk * oldChunk + _1 % newChunk)),
            thrust::make_permutation_iterator(
                    v.begin(),
                    thrust::make_transform_iterator(
                            thrust::counting_iterator<int>(0),
                            _1 / newChunk * oldChunk + _1 % newChunk))
                    + buf.size(),
            buf.begin());

    return 0;
}

我认为由于使用了mod运算符%,上述版本可能无法达到最高性能。为了获得更高的性能,您可以考虑使用cuBLAS函数cublas_geam()

float alpha = 1;
float beta = 0;
cublasSgeam(handle, CUBLAS_OP_N, CUBLAS_OP_N,
            newChunk, size,
            &alpha,
            thrust::raw_pointer_cast(&v[0]), oldChunk,
            &beta,
            thrust::raw_pointer_cast(&v[0]), oldChunk,
            thrust::raw_pointer_cast(&buf[0]), newChunk);