lrn_kernel.h 2.4 KB
Newer Older
E
eclipsess 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/* 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. */
E
eclipsess 已提交
14

L
liuruilong 已提交
15 16 17 18
#ifdef LRN_OP

#pragma once

E
eclipsess 已提交
19 20 21 22 23 24 25 26
#include "framework/operator.h"
#include "operators/op_param.h"

namespace paddle_mobile {
namespace operators {

using namespace framework;

朔-望's avatar
朔-望 已提交
27 28
template <typename T>
struct LRNFunctor {
29 30 31 32 33
  void operator()(const framework::Tensor &input, framework::Tensor *out, int N,
                  int C, int H, int W, int n, T k, T alpha, T beta) {
    auto input_ptr = input.data<T>();
    const int start = -(n - 1) / 2;
    const int end = start + n;
E
eclipsess 已提交
34

35 36 37 38
    const int stride0 = C * H * W;
    const int stride1 = H * W;
    const int stride2 = W;
    const int stride3 = 1;
E
eclipsess 已提交
39

40 41 42 43 44 45 46 47
    framework::Tensor sqr_buffer;
    auto sqr_buffer_ptr = sqr_buffer.mutable_data<T>(input.dims());
    std::fill(sqr_buffer_ptr, sqr_buffer_ptr + sqr_buffer.numel(), k);
    for (int a = 0; a < N; a++) {
      for (int b = 0; b < C; b++) {
        for (int index = start; index < end; index++) {
          int channel = b + index;
          if (channel >= 0 && channel < C) {
E
eclipsess 已提交
48 49
            int tmp_u = a * stride0 + b * stride1;
            int tmp_i = a * stride0 + channel * stride1;
50 51
            for (int c = 0; c < H; c++) {
              for (int d = 0; d < W; d++) {
E
eclipsess 已提交
52 53 54
                int tmp = c * stride2 + d;
                int u = tmp_u + tmp;
                int i = tmp_i + tmp;
55 56
                sqr_buffer_ptr[u] += alpha * input_ptr[i] * input_ptr[i];
              }
E
eclipsess 已提交
57
            }
58
          }
E
eclipsess 已提交
59
        }
60 61 62 63 64
      }
    }
    auto out_ptr = out->data<T>();
    for (int i = 0; i < input.numel(); i++) {
      out_ptr[i] = input_ptr[i] / pow(sqr_buffer_ptr[i], beta);
E
eclipsess 已提交
65
    }
66
  }
E
eclipsess 已提交
67 68 69 70
};

template <typename DeviceType, typename T>
class LrnKernel : public framework::OpKernelBase<DeviceType, LrnParam> {
朔-望's avatar
朔-望 已提交
71
 public:
72
  void Compute(const LrnParam &param) const;
E
eclipsess 已提交
73
};
朔-望's avatar
朔-望 已提交
74 75
}  // namespace operators
}  // namespace paddle_mobile
L
liuruilong 已提交
76 77

#endif