gpt4 book ai didi

c++ - 使用 thrust::transform 替换 for 循环

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:01 26 4
gpt4 key购买 nike

我正在尝试通过在 GPU 的线程上实现循环来优化我的代码。我正在尝试使用 thrust::transform 消除两个 for 循环。 C++ 中的代码如下所示:

    ka_index = 0;
for (int i = 0; i < N_gene; i++)
{
for (int j = 0; j < n_ka_d[i]; j++ )
{
co0 = get_coeff0(ka_vec_d[ka_index]);
act[i] += (co0*ka_val_d[ka_index]);
ka_index++;
}
act[i] = pow(act[i],n);
}

我正在估算上述循环中常微分方程 (ODE) 的系数并使用推力将所有数据传输到设备上。考虑基因数量由 N_gene 表示的情况。循环的拳头必须运行 N_gene 次数。第二个for循环受每个基因的激活子(基因库中的其他友好基因)数量的限制。每个基因都有许多激活因子(友好基因,其存在会增加基因 i 的浓度),由 n_ka vector 的元素表示。 n_ka[i] 的值可以在 0 到 N_gene - 1 之间变化。ka_val 表示每个激活因子 ka 的激活度量。 ka_vec_d具有激活基因i的基因索引。

我正在尝试使用迭代器来表示这些循环,但无法这样做。我熟悉将 thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple)) 用于单个 for 循环,但很难想出一种使用 counting_iterator 或转换迭代器实现两个 for 循环的方法。任何指针或帮助转换这两个 for 循环将不胜感激。感谢您的宝贵时间!

最佳答案

这看起来像是一个 reduce 问题。我认为您可以将 thrust::transform 与 zip 迭代器和 thrust::reduce_by_key 一起使用。此解决方案的草图是:

// generate indices
std::vector< int > hindices;
for( size_t i=0 ; i<N_gene ; ++i )
for( size_t j=0 ; j<n_ka_d[i] ; ++j )
hindices.push_back( i );
thrust::device_vector< int > indices = hindices;

// generate tmp
// trafo1 implements get_coeff0( get< 0 >( t ) ) * get< 1 >( t);
thrust::device_vector< double > tmp( N );
thrust::transform(
thrust::make_zip_iterator(
thrust::make_tuple( ka_vec_d.begin() , ka_val_d.begin() ) ) ,
thrust::make_zip_iterator(
thrust::make_tuple( ka_vec_d.end() , ka_val_d.end() ) ) ,
tmp.begin() , trafo1 );

// do the reduction for each ac[i]
thrust::device_vector< int > indices_out( N );
thrust::reduce_by_key( indices.begin() , indices.end() , tmp.begin() ,
ac.begin() , indices_out.begin() );

// do the pow transformation
thrust::transform( ac.begin() , ac.end() , ac.begin() , pow_trafo );

我认为这也可以通过 transform_iterators 进行优化,以减少 thrust::transformthrust::recuce_by_key 的调用次数。

关于c++ - 使用 thrust::transform 替换 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com