thrust::device_vector使用自定义函子/谓词来替换或转换
thrust::device_vector use thrust::replace or thrust::transform with custom functor/predicate
我使用cuda内核对推力向量进行sigmoid激活:
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 );
我的内核在哪里:
__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 );
}
如何使用thrust::replace替换为函子/谓词来执行同样的操作?
我看到的例子过于简单,无法证明这种用途:
thrust::replace(Y.begin(), Y.end(), 1, 10);
或
thrust::transform(X.begin(), X.end(), Y.begin(),thrust::negate<int>());
在第8-9页的"Thrust Quick Start Guide"中,有一个关于如何创建自己的转换函数的示例。
我提出了一个解决方案,但请注意,这不会在主机端运行,因为您使用CUDA内部函数。
代码
#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;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- std::condition_variable::wait()如何评估给定的谓词
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- thrust::device_vector使用自定义函子/谓词来替换或转换
- 转换谓词,通过引用返回局部变量