如何从仿函数访问device_vector

时间:2013-11-23 02:32:50

标签: c++ cuda thrust

我在正确创建仿函数以访问设备向量时遇到了一些麻烦。 基本上,我有两个设备向量,我想在仿函数中使用。在for_each期间调用仿函数。

这是我的仿函数:

struct likelihood_functor
{
int N;
float* v1;
float* v2;

likelihood_functor(int _N, float* _v1, float* _v2) : N(_N),v1(_v1),v2(_v2) {}
template <typename Tuple>

__host__ __device__ void operator()(Tuple t)
{
    float A = thrust::get<0>(t);
    float rho = thrust::get<1>(t);
    float mux = thrust::get<2>(t);
    float muy = thrust::get<3>(t);
    float sigx = thrust::get<4>(t);
    float sigy = thrust::get<5>(t);

    thrust::device_ptr<float> v1_p(v1);
    thrust::device_vector<float> X(v1_p,v1_p+N);
            thrust::device_ptr<float> v2_p(v2);
    thrust::device_vector<float> Y(v2_p,v2_p+N);

    thrust::get<6>(t) = 600*logf(A)
        - 600/2*logf(sigx*sigx*sigy*sigy*(1-rho*rho))
        - thrust::reduce(X.begin(),X.end())
        - thrust::reduce(Y.begin(),Y.end())
        - 2*rho/(sigx*sigy);
}
};

这是我的主要():

int main(void)
{

// create a 2D dataset
const int N=2500; //number of counts

thrust::device_vector<float> data_x(N);
thrust::device_vector<float> data_y(N);

thrust::counting_iterator<unsigned int> begin(0);
    thrust::transform(begin,
        begin + N,
        data_x.begin(),
        get_normal(5.f,1.f,2.f));
thrust::transform(begin,
        begin + N,
        data_y.begin(),
        get_normal(5.f,1.f,2.f));

    //
    // Some code here to initiate A_n, rho_na, mux_n etc...
    //

// apply the transformation
thrust::for_each(
    thrust::make_zip_iterator( 
      thrust::make_tuple(A_n.begin(), rho_n.begin(), mux_n.begin(),  muy_n.begin(), sigx_n.begin(),sigy_n.begin(), L.begin()) 
    ), 
    thrust::make_zip_iterator( 
      thrust::make_tuple(A_n.end(), rho_n.end(), mux_n.end(), muy_n.end(), sigx_n.end(),sigy_n.end(),L.end())
    ), 
    likelihood_functor(N,thrust::raw_pointer_cast(&(data_x[0])),thrust::raw_pointer_cast(&(data_y[0])))
    );

// print the output
for(int i=0; i<4096; i++)
{
    std::cout << "[" << i << "] : " << L[i] <<std::endl;
}

}

代码编译,但它不运行。我知道这是因为在我的仿函数中,device_vector X和Y没有正确完成。

我使用相同的代码在我的main函数中创建X和Y,当我这样做时,程序运行正常(在这种情况下,我不调用functor)。 与函数内部有什么不同,它会使某些东西在主程序中运行而不是在函数中?

还有另一种方法可以做我想做的事吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在cuda设备代码中不能使用推力算法(例如转换,缩减等)。

__global____device__之前的任何函数都不能使用推力(例如,不能使用thrust::reduce)。

因此,您的仿函数不会在设备代码中工作,因为它使用推力构造(例如thrust::reduce)。

我意识到你说你的代码编译,但我不确定我是否相信。如果我尝试在thrust::device_vector代码中声明__device__,我会收到编译错误。由于您在此处显示的代码在许多方面都不完整,因此您无法使用您的代码轻松演示,因为您发布的内容存在其他问题。