mean_op.h 2.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
liaogang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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. */

#pragma once
Y
Yi Wang 已提交
16 17
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
L
liaogang 已提交
18 19 20 21

namespace paddle {
namespace operators {

D
dongzhihong 已提交
22 23 24 25 26 27 28 29
using Tensor = framework::Tensor;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenScalar = framework::EigenScalar<T, MajorType, IndexType>;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;

Q
QI JUN 已提交
30
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
31
class MeanKernel : public framework::OpKernel<T> {
32
 public:
D
dongzhihong 已提交
33
  void Compute(const framework::ExecutionContext& context) const override {
Y
Yu Yang 已提交
34 35
    auto* input = context.Input<Tensor>("X");
    auto* output = context.Output<Tensor>("Out");
L
liaogang 已提交
36 37

    output->mutable_data<T>(context.GetPlace());
L
liaogang 已提交
38

L
liaogang 已提交
39 40
    auto X = EigenVector<T>::Flatten(*input);
    auto y = EigenScalar<T>::From(*output);
Q
QI JUN 已提交
41 42
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
L
liaogang 已提交
43 44

    y.device(place) = X.mean();
L
liaogang 已提交
45 46 47
  }
};

Q
QI JUN 已提交
48
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
49
class MeanGradKernel : public framework::OpKernel<T> {
50
 public:
D
dongzhihong 已提交
51
  void Compute(const framework::ExecutionContext& context) const override {
52
    auto OG = context.Input<Tensor>(framework::GradVarName("Out"));
53
    PADDLE_ENFORCE(OG->numel() == 1, "Mean Gradient should be scalar");
54
    auto IG = context.Output<Tensor>(framework::GradVarName("X"));
Y
Yu Yang 已提交
55 56
    IG->mutable_data<T>(context.GetPlace());

57
    T ig_size = static_cast<T>(IG->numel());
C
chengduo 已提交
58
    Eigen::DSizes<int, 1> bcast(static_cast<int>(ig_size));
Q
QI JUN 已提交
59 60
    EigenVector<T>::Flatten(*IG).device(
        *context.template device_context<DeviceContext>().eigen_device()) =
61
        (EigenVector<T>::From(*OG) / ig_size).broadcast(bcast);
Y
Yu Yang 已提交
62 63 64
  }
};

L
liaogang 已提交
65 66
}  // namespace operators
}  // namespace paddle