首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >thrust::device_vector使用推力::替换或插入::用自定义函子/谓词进行转换

thrust::device_vector使用推力::替换或插入::用自定义函子/谓词进行转换
EN

Stack Overflow用户
提问于 2015-11-25 18:13:00
回答 1查看 853关注 0票数 1

我使用cuda内核对推力矢量进行乙状结肠激活:

代码语言:javascript
运行
复制
thrust::device_vector<float> output = input;
float * output_ptr = thrust::raw_pointer_cast( output.data() );
sigmoid_activation<<<num_blocks_x,block_threads_x>>>( output_ptr );

我的内核是:

代码语言:javascript
运行
复制
__device__ float sigmoid_function( float input, float skew )
{
    // -X: Neg X
    float x_neg = __fmul_rz( -1.f, input );
    // Y: exponential value
    float exp_val = __expf( x_neg );
    // 1 + exp^(-X)
    float denom = __fadd_rz( 1.f, e_to_x_neg );
     // 1 / 1 + exp^(-X)
    float output  = __fdividef( 1.f, denom );

    if ( skew != 0.0 )
        return _fadd_rz( output, skew );
    else
        return output;
}

__global__ void sigmoid_activation( float * input float skew )
{
    // Iterate Input vector
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    // Update value
    input[x]  = sigmoid_function( input[x], skew );  
}

我如何使用推力::替换为函子/谓词来做同样的事情?

我看到的例子过于简单化,无法证明这种用途:

代码语言:javascript
运行
复制
thrust::replace(Y.begin(), Y.end(), 1, 10);

代码语言:javascript
运行
复制
thrust::transform(X.begin(), X.end(), Y.begin(),thrust::negate<int>());
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-25 20:35:43

在第8-9页的“推力快速启动指南”中,有一个如何创建自己的转换函数的示例。

我想出了一个解决方案,但请注意,这不会在主机端运行,因为您使用的是CUDA本质。

代码语言:javascript
运行
复制
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/replace.h>
#include <thrust/functional.h>
#include <iostream>

template<typename T>
struct sigmoid_function
{

  float _skew;

  sigmoid_function(float skew) : _skew(skew) { /*Empty */ }

  typedef T argument_type;

  typedef T result_type;

  __device__ T operator()(const T &x) const {

    float x_neg = __fmul_rz( -1.f, x );
    float exp_val = __expf( x_neg );
    float denom = __fadd_rz( 1.f, __expf(-exp_val) );
    float output  = __fdividef( 1.f, denom );

    if ( _skew != 0.0 )
        return __fadd_rz( output, _skew );
    else
        return output;
  }
};

int main(void) {
    // allocate three device_vectors with 10 elements
    thrust::device_vector<float> X(10);

    // initialize X to 0,1,2,3, ....
    thrust::sequence(X.begin(), X.end());

    // Before
    thrust::copy(X.begin(),X.end(),std::ostream_iterator<float>(std::cout, "\n"));

    // Apply
    thrust::transform(X.begin(), X.end(), X.begin(), sigmoid_function<float>(0.1));

    // After
    thrust::copy(X.begin(),X.end(),std::ostream_iterator<float>(std::cout, "\n"));

    return 0;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33923645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档