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

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
D
dongzhihong 已提交
16 17
#include "paddle/framework/eigen.h"
#include "paddle/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());
58
    Eigen::DSizes<int, 1> bcast(ig_size);
Y
Yu Yang 已提交
59

Q
QI JUN 已提交
60 61
    EigenVector<T>::Flatten(*IG).device(
        *context.template device_context<DeviceContext>().eigen_device()) =
62
        (EigenVector<T>::From(*OG) / ig_size).broadcast(bcast);
Y
Yu Yang 已提交
63 64 65
  }
};

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