prelu_kernel.cpp 2.1 KB
Newer Older
T
Tian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#ifdef PRELU_OP

#include "operators/kernel/prelu_kernel.h"
#include <operators/math/transform.h>

namespace paddle_mobile {
I
itminner 已提交
21
namespace operators {
T
Tian 已提交
22

I
itminner 已提交
23 24 25 26
template <typename T>
struct PReluFunctor {
  explicit PReluFunctor(float slope) { this->slope_ = slope; }
  inline T operator()(T in) const { return in > 0 ? in : in * slope_; }
T
Tian 已提交
27

I
itminner 已提交
28 29
  float slope_ = 0.0f;
};
T
Tian 已提交
30 31 32 33

/*
 * @b 特化到具体平台的实现, param 从 op 层传入
 * */
I
itminner 已提交
34 35
template <>
void PReluKernel<CPU, float>::Compute(const PReluParam &param) const {
36
  DLOG << "PReluKernel :Compute";
T
Tian 已提交
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51
  auto *x = param.InputX();
  auto *alpha = param.InputAlpha();
  auto *out = param.Out();
  std::string mode = param.Mode();
  const auto *x_ptr = x->data<float>();
  auto *o_ptr = out->mutable_data<float>();
  const auto *alpha_ptr = alpha->data<float>();
  int numel = x->numel();
  auto dim = x->dims();
  int index = 0;
  int i = 0;
  int temp = 0;
  if (mode == "channel") {
#pragma omp parallel for
T
Tian 已提交
52

53 54 55 56 57 58 59
    for (i = 0; i < numel; i++) {
      temp = numel / (dim[0] * dim[1]);
      index = (i / temp) % dim[1];
      o_ptr[i] = x_ptr[i] > 0 ? x_ptr[i] : alpha_ptr[index] * x_ptr[i];
    }
  } else if (mode == "element") {
#pragma omp parallel for
T
Tian 已提交
60

61 62 63 64 65
    for (i = 0; i < numel; i++) {
      o_ptr[i] = x_ptr[i] > 0 ? x_ptr[i] : alpha_ptr[i] * x_ptr[i];
    }
  } else {
#pragma omp parallel for
T
Tian 已提交
66

67 68
    for (i = 0; i < numel; i++) {
      o_ptr[i] = x_ptr[i] > 0 ? x_ptr[i] : alpha_ptr[0] * x_ptr[i];
I
itminner 已提交
69 70 71 72
    }
  }
}
}  // namespace operators
T
Tian 已提交
73 74
}  // namespace paddle_mobile

I
itminner 已提交
75
#endif