Thrust::transform 自定义函数

Thrust::transform custom function

我正在尝试在 CUDA 中做一个非常基本的示例。我想对浮点数列表做一个简单的计算。

vh[x] * k1 + k2

目前我正在尝试这个但它不起作用:

代码 1

#include <vector>
#include <iostream>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>

using namespace std;
using namespace thrust;

float k1 = 42, k2 = 7;

int main(void)
{
    vector<float> vh = { 0, 1, 2, 3, 4, 5, 6, 7 };
    device_vector<float> v = vh;
    device_vector<float> v_out(v.size());

    thrust::transform(v.begin(), v.end(), v_out.begin(), [=] __device__(float x) {
        return x*k1 + k2;
    });

    for (size_t i = 0; i < v_out.size(); i++)
        std::cout << v_out[i] << std::endl;
}

我在上面的代码中遇到了一个非常烦人的 lambda 函数错误,所以我尝试使用自定义函数,如下面的代码所示:

代码 2

#include <vector>
#include <iostream>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>

using namespace std;
using namespace thrust;

float k1 = 42, k2 = 7;

float multiply(float x)
{
    return x * k1 + k2;
}

int main(void) {
    vector<float> vh = { 0, 1, 2, 3, 4, 5, 6, 7 };
    device_vector<float> v = vh;
    device_vector<float> v_out(v.size());
    thrust::negate<float> op;

    thrust::transform(v.begin(), v.end(), v_out.begin(), multiply __device__(float x) );

    for (size_t i = 0; i < v_out.size(); i++)
        std::cout << v_out[i] << std::endl;

    std::getwchar();
}

谁能告诉我为什么代码 1 and/or 代码 2 不起作用?

对于代码 2,您必须将函数包装在对象中以创建仿函数。

对于代码 1,您必须使用 --expt-extended-lambda nvcc 选项来启用完整的 lambda 支持。

您还必须将 k1k2 声明为 const,或者不通过(例如)在 main.[=17 中声明它们来使它们成为静态的=]

将仿函数用于生产代码,除非您的 lambda 非常 简单。

查看以下代码作为工作示例:

#include <vector>
#include <iostream>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>

using namespace std;
using namespace thrust;



template<class T>
struct saxpi{
    T k1;
    T k2;
    saxpi(T _k1, T _k2){
        k1=_k1;
        k2=_k2;
    }
    __host__ __device__ T operator()(T &x) const{
        return x*k1+k2;
    }
};


int main(void)
{
    float kk1=1, kk2=5;
    vector<float> vh = { 0, 1, 2, 3, 4, 5, 6, 7 };
    device_vector<float> v = vh;
    device_vector<float> v_out(v.size());
    cout<<"Lambda:"<<endl;
    auto ff = [=]  __device__ (float x) {return kk1*x +kk2;};

    thrust::transform(v.begin(),v.end(),v_out.begin(),ff);

    for (size_t i = 0; i < v_out.size(); i++)
        std::cout << v_out[i] << std::endl;

    cout<<"Functor:"<<endl;
    saxpi<float> f(kk1,kk2);
    v_out.clear();
    v_out.resize(v.size());
    thrust::transform(v.begin(),v.end(),v_out.begin(),f);


    for (size_t i = 0; i < v_out.size(); i++)
            std::cout << v_out[i] << std::endl;

}

使用以下选项编译它:--expt-extended-lambda -std=c++11

Lambda:
5
6
7
8
9
10
11
12
Functor:
5
6
7
8
9
10
11
12