cross_entropy_op.h 4.0 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
C
caoying03 已提交
16
#include "paddle/framework/eigen.h"
D
dongzhihong 已提交
17
#include "paddle/framework/op_registry.h"
18
#include "paddle/platform/hostdevice.h"
Q
Qiao Longfei 已提交
19 20 21 22

namespace paddle {
namespace operators {

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

28
template <typename T>
C
caoying03 已提交
29 30 31 32 33
struct TolerableValue {
  HOSTDEVICE T operator()(const T& x) const {
    PADDLE_ASSERT(std::is_floating_point<T>::value);
    const T kApproInf = 1e20;

C
caoying03 已提交
34 35
    if (x == INFINITY) return kApproInf;
    if (x == -INFINITY) return -kApproInf;
C
caoying03 已提交
36
    return x;
37
  }
C
caoying03 已提交
38
};
Y
Yan Chunwei 已提交
39

40
template <typename T>
41
class CrossEntropyOpKernel : public framework::OpKernel {
42
 public:
D
dongzhihong 已提交
43
  void Compute(const framework::ExecutionContext& ctx) const override {
44
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
C
caoying03 已提交
45
                   "This kernel only runs on CPU.");
C
caoying03 已提交
46 47 48
    const Tensor* x = ctx.Input<Tensor>("X");
    const Tensor* labels = ctx.Input<Tensor>("Label");
    Tensor* y = ctx.Output<Tensor>("Y");
C
caoying03 已提交
49
    T* y_data = y->mutable_data<T>(ctx.GetPlace());
50

C
caoying03 已提交
51
    const int batch_size = x->dims()[0];
C
caoying03 已提交
52
    if (ctx.Attr<bool>("softLabel")) {
C
caoying03 已提交
53 54 55 56 57
      auto prob = EigenMatrix<T>::From(*x);
      auto lbl_mat = EigenMatrix<T>::From(*labels);
      auto loss = EigenMatrix<T>::From(*y);

      loss.device(ctx.GetEigenDevice<platform::CPUPlace>()) =
C
caoying03 已提交
58
          -((lbl_mat * prob.log().unaryExpr(TolerableValue<T>()))
C
caoying03 已提交
59 60
                .sum(Eigen::DSizes<int, 1>(1))
                .reshape(Eigen::DSizes<int, 2>(batch_size, 1)));
61
    } else {
C
caoying03 已提交
62 63 64 65
      const int class_num = x->dims()[1];
      const T* x_data = x->data<T>();

      const int* label_data = labels->data<int>();
66 67
      for (int i = 0; i < batch_size; ++i) {
        int index = i * class_num + label_data[i];
C
caoying03 已提交
68
        y_data[i] = -TolerableValue<T>()(std::log(x_data[index]));
69
      }
Y
Yan Chunwei 已提交
70 71 72 73
    }
  }
};

74
template <typename T>
75
class CrossEntropyGradientOpKernel : public framework::OpKernel {
Y
Yan Chunwei 已提交
76
 public:
D
dongzhihong 已提交
77
  void Compute(const framework::ExecutionContext& ctx) const override {
78
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
C
caoying03 已提交
79 80 81 82 83 84
                   "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 已提交
85

86
    int class_num = x->dims()[1];
C
caoying03 已提交
87 88 89 90 91 92 93 94 95
    if (ctx.Attr<bool>("softLabel")) {
      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);

      dx_mat.device(ctx.GetEigenDevice<platform::CPUPlace>()) =
          -(lbl_mat * dy_mat.broadcast(Eigen::DSizes<int, 2>(1, class_num)) /
            x_mat);
96
    } else {
C
caoying03 已提交
97 98 99 100 101 102
      int batch_size = x->dims()[0];
      const T* dy_data = dy->data<T>();
      const T* x_data = x->data<T>();
      const int* label_data = label->data<int>();

      // TODO(qingqing): make zero setting a common function.
103
      memset(dx_data, 0, sizeof(T) * batch_size * class_num);
C
caoying03 已提交
104

105 106 107 108 109
      for (int i = 0; i < batch_size; ++i) {
        PADDLE_ASSERT(label_data[i] >= 0 || label_data[i] < class_num);
        int index = i * class_num + label_data[i];
        dx_data[index] = -dy_data[i] / x_data[index];
      }
Q
Qiao Longfei 已提交
110 111 112 113 114 115
    }
  }
};

}  // namespace operators
}  // namespace paddle