prelu_kernel.cpp 2.0 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
template <>
N
nhzlx 已提交
35
void PReluKernel<CPU, float>::Compute(const PReluParam<CPU> &param) const {
36 37
  auto *x = param.InputX();
  auto *alpha = param.InputAlpha();
I
itminner 已提交
38
  auto *out = param.Out();
39 40 41 42 43 44 45 46 47 48
  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") {
49
    temp = numel / (dim[0] * dim[1]);
xiebaiyuan's avatar
xiebaiyuan 已提交
50
    #pragma omp parallel for
51 52 53 54 55
    for (i = 0; i < numel; i++) {
      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") {
xiebaiyuan's avatar
xiebaiyuan 已提交
56
    #pragma omp parallel for
57 58 59 60
    for (i = 0; i < numel; i++) {
      o_ptr[i] = x_ptr[i] > 0 ? x_ptr[i] : alpha_ptr[i] * x_ptr[i];
    }
  } else {
xiebaiyuan's avatar
xiebaiyuan 已提交
61
    #pragma omp parallel for
62 63
    for (i = 0; i < numel; i++) {
      o_ptr[i] = x_ptr[i] > 0 ? x_ptr[i] : alpha_ptr[0] * x_ptr[i];
I
itminner 已提交
64 65 66 67
    }
  }
}
}  // namespace operators
T
Tian 已提交
68 69
}  // namespace paddle_mobile

I
itminner 已提交
70
#endif