lrn_kernel.h 2.3 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 15 16 17 18 19 20 21 22 23

#include "framework/operator.h"
#include "operators/op_param.h"
#pragma once;

namespace paddle_mobile {
namespace operators {

using namespace framework;

朔-望's avatar
朔-望 已提交
24 25
template <typename T>
struct LRNFunctor {
26 27 28 29 30
  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 已提交
31

32 33 34 35
    const int stride0 = C * H * W;
    const int stride1 = H * W;
    const int stride2 = W;
    const int stride3 = 1;
E
eclipsess 已提交
36

37 38 39 40 41 42 43 44
    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 已提交
45 46
            int tmp_u = a * stride0 + b * stride1;
            int tmp_i = a * stride0 + channel * stride1;
47 48
            for (int c = 0; c < H; c++) {
              for (int d = 0; d < W; d++) {
E
eclipsess 已提交
49 50 51
                int tmp = c * stride2 + d;
                int u = tmp_u + tmp;
                int i = tmp_i + tmp;
52 53
                sqr_buffer_ptr[u] += alpha * input_ptr[i] * input_ptr[i];
              }
E
eclipsess 已提交
54
            }
55
          }
E
eclipsess 已提交
56
        }
57 58 59 60 61
      }
    }
    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 已提交
62
    }
63
  }
E
eclipsess 已提交
64 65 66 67
};

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