1 #ifndef CAFFE2_OPERATORS_SINUSOID_POSITION_ENCODING_OP_H_ 2 #define CAFFE2_OPERATORS_SINUSOID_POSITION_ENCODING_OP_H_ 5 #define _USE_MATH_DEFINES 9 #include "caffe2/core/operator.h" 12 #include "caffe2/utils/eigen_utils.h" 16 template <
class Context>
19 template <
class... Args>
23 this->
template GetSingleArgument<int>(
"embedding_size", 100)),
24 alpha_(this->
template GetSingleArgument<float>(
"alpha", 10000)),
25 amplitude_(this->
template GetSingleArgument<float>(
"amplitude", 1)) {}
26 USE_OPERATOR_CONTEXT_FUNCTIONS;
28 bool RunOnDevice()
override {
30 this, this->
template Input<Tensor>(0, CPU));
33 template <
typename Index>
34 bool DoRunWithType() {
35 auto& positions =
Input(0);
37 CAFFE_ENFORCE_EQ(positions.dim(), 2,
"POSITIONS should be a 2-D tensor");
39 auto shape = positions.sizes().vec();
40 shape.push_back(embedding_size_);
41 auto* output = Output(0, shape, at::dtype<float>());
45 const Index* idxs = positions.template data<Index>();
46 float* out = output->template mutable_data<float>();
48 float log_alpha = std::log(alpha_);
50 ((float)embedding_size_ - 1.0f) / (float)embedding_size_;
52 for (
int i = 0; i < M; ++i) {
53 float pos = (float)idxs[i * K];
56 float* row = &out[i * K * embedding_size_];
57 Eigen::Map<Eigen::VectorXf> row_map(row, embedding_size_, 1);
58 auto row_array = row_map.array();
60 float log_pos = std::log(pos);
61 row_array.setLinSpaced(
62 embedding_size_, log_pos, log_pos - log_alpha * max_alpha_pow);
63 row_array = row_array.exp().eval();
67 for (
int k = 1; k < embedding_size_; k += 2) {
68 row[k] += (float)M_PI_2;
70 row_array = amplitude_ * row_array.sin().eval();
73 for (
int j = 1; j < K; ++j) {
74 int base = i * K * embedding_size_;
77 &out[base + embedding_size_],
78 &out[base + j * embedding_size_]);
92 #endif // CAFFE2_OPERATORS_SINUSOID_POSITION_ENCODING_OP_H_
const Tensor & Input(int idx, DeviceType type=Context::GetDeviceType())
Retrieve a non-owning reference to the input at position 'idx' for this operator. ...
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...