“30061d48313d9c96af49dfe65939c47ca3bb3470”上不存在“paddle/legacy/trainer/tests/CMakeLists.txt”
cross_entropy_op.h 3.3 KB
Newer Older
Q
Qiao Longfei 已提交
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
Y
Yi Wang 已提交
16 17 18 19
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/cross_entropy.h"
#include "paddle/fluid/operators/math/math_function.h"
Q
Qiao Longfei 已提交
20 21 22 23

namespace paddle {
namespace operators {

D
dongzhihong 已提交
24
using Tensor = framework::Tensor;
C
caoying03 已提交
25 26 27
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;
D
dongzhihong 已提交
28

29
template <typename T>
Y
Yu Yang 已提交
30
class CrossEntropyOpKernel : public framework::OpKernel<T> {
31
 public:
D
dongzhihong 已提交
32
  void Compute(const framework::ExecutionContext& ctx) const override {
33
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
C
caoying03 已提交
34
                   "This kernel only runs on CPU.");
C
caoying03 已提交
35 36 37
    const Tensor* x = ctx.Input<Tensor>("X");
    const Tensor* labels = ctx.Input<Tensor>("Label");
    Tensor* y = ctx.Output<Tensor>("Y");
38
    y->mutable_data<T>(ctx.GetPlace());
C
caoying03 已提交
39

Q
QI JUN 已提交
40 41 42
    math::CrossEntropyFunctor<platform::CPUDeviceContext, T>()(
        ctx.template device_context<platform::CPUDeviceContext>(), y, x, labels,
        ctx.Attr<bool>("soft_label"));
Y
Yan Chunwei 已提交
43 44 45
  }
};

46
template <typename T>
Y
Yu Yang 已提交
47
class CrossEntropyGradientOpKernel : public framework::OpKernel<T> {
Y
Yan Chunwei 已提交
48
 public:
D
dongzhihong 已提交
49
  void Compute(const framework::ExecutionContext& ctx) const override {
50
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
C
caoying03 已提交
51 52 53 54 55 56
                   "This kernel only runs on CPU.");
    const Tensor* x = ctx.Input<Tensor>("X");
    const Tensor* dy = ctx.Input<Tensor>(framework::GradVarName("Y"));
    const Tensor* label = ctx.Input<Tensor>("Label");
    Tensor* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    T* dx_data = dx->mutable_data<T>(ctx.GetPlace());
Y
Yan Chunwei 已提交
57

58
    int64_t class_num = x->dims()[1];
59
    if (ctx.Attr<bool>("soft_label")) {
C
caoying03 已提交
60 61 62 63 64
      auto x_mat = EigenMatrix<T>::From(*x);
      auto dy_mat = EigenMatrix<T>::From(*dy);
      auto lbl_mat = EigenMatrix<T>::From(*label);
      auto dx_mat = EigenMatrix<T>::From(*dx);

Q
QI JUN 已提交
65 66
      dx_mat.device(*ctx.template device_context<platform::CPUDeviceContext>()
                         .eigen_device()) =
67 68
          -(lbl_mat *
            dy_mat.broadcast(Eigen::DSizes<int64_t, 2>(1, class_num)) / x_mat);
69
    } else {
70
      int64_t batch_size = x->dims()[0];
C
caoying03 已提交
71 72
      const T* dy_data = dy->data<T>();
      const T* x_data = x->data<T>();
73
      const int64_t* label_data = label->data<int64_t>();
C
caoying03 已提交
74

Q
QI JUN 已提交
75 76
      math::SetConstant<platform::CPUDeviceContext, T> functor;
      functor(ctx.template device_context<platform::CPUDeviceContext>(), dx, 0);
C
caoying03 已提交
77

78
      for (int64_t i = 0; i < batch_size; ++i) {
79
        PADDLE_ASSERT(label_data[i] >= 0 || label_data[i] < class_num);
80
        int64_t index = i * class_num + label_data[i];
81 82
        dx_data[index] = -dy_data[i] / x_data[index];
      }
Q
Qiao Longfei 已提交
83 84 85 86 87 88
    }
  }
};

}  // namespace operators
}  // namespace paddle