cross_entropy_op.h 3.9 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
D
dongzhihong 已提交
16
#include "paddle/framework/op_registry.h"
Q
Qiao Longfei 已提交
17 18 19 20

namespace paddle {
namespace operators {

D
dongzhihong 已提交
21 22
using Tensor = framework::Tensor;

23
template <typename T>
D
dangqingqing 已提交
24
inline T tolerable_value(const T x) {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
  static_assert(std::is_floating_point<T>::value,
                "tolerable_value works only on float, "
                "double and double double.");

  const T kApproInf = 1e20;

  if (x == INFINITY) {
    return kApproInf;
  }

  if (x == -INFINITY) {
    return -kApproInf;
  }

  return x;
}
Y
Yan Chunwei 已提交
41

42
template <typename T>
43
class CrossEntropyOpKernel : public framework::OpKernel {
44
 public:
D
dongzhihong 已提交
45
  void Compute(const framework::ExecutionContext& ctx) const override {
46 47 48
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    auto x = ctx.Input<Tensor>("X");
    auto y = ctx.Output<Tensor>("Y");

    auto* x_data = x->data<T>();
    y->mutable_data<T>(ctx.GetPlace());
    auto* y_data = y->data<T>();

    int batch_size = x->dims()[0];
    int class_num = x->dims()[1];
    int label_rank = ctx.Input<Tensor>("Label")->dims().size();

    if (label_rank == 2) {
      // soft cross entropy
      auto* label_data = ctx.Input<Tensor>("Label")->data<T>();
      int index = 0;
      for (int i = 0; i < batch_size; ++i) {
        T sum = static_cast<T>(0);
        for (int j = 0; j < class_num; ++j) {
          sum += label_data[index] * std::log(x_data[index]);
          y_data[i] = -tolerable_value(sum);
          index++;
        }
      }
    } else {
      // normal cross entropy
      auto* label_data = ctx.Input<Tensor>("Label")->data<int>();
      for (int i = 0; i < batch_size; ++i) {
        int index = i * class_num + label_data[i];
        y_data[i] = -tolerable_value(std::log(x_data[index]));
      }
Y
Yan Chunwei 已提交
79 80 81 82
    }
  }
};

83
template <typename T>
84
class CrossEntropyGradientOpKernel : public framework::OpKernel {
Y
Yan Chunwei 已提交
85
 public:
D
dongzhihong 已提交
86
  void Compute(const framework::ExecutionContext& ctx) const override {
87 88 89
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");

90 91 92 93
    auto x = ctx.Input<Tensor>("X");
    auto dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto dy = ctx.Input<Tensor>(framework::GradVarName("Y"));
    auto label = ctx.Input<Tensor>("Label");
Y
Yan Chunwei 已提交
94

95 96 97
    auto* dx_data = dx->mutable_data<T>(ctx.GetPlace());
    auto* dy_data = dy->data<T>();
    auto* x_data = x->data<T>();
Y
Yan Chunwei 已提交
98

99 100 101
    int batch_size = x->dims()[0];
    int class_num = x->dims()[1];
    int label_rank = ctx.Input<Tensor>("Label")->dims().size();
Y
Yan Chunwei 已提交
102

103
    // TODO(qingqing): make zero setting an common function.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    if (label_rank == 2) {
      // soft cross entropy
      auto* label_data = ctx.Input<Tensor>("Label")->data<T>();
      int index = 0;
      for (int i = 0; i < batch_size; ++i) {
        for (int j = 0; j < class_num; ++j) {
          dx_data[index] = -label_data[index] * dy_data[i] / x_data[index];
          index++;
        }
      }
    } else {
      // normal cross entropy
      auto* label_data = label->data<int>();
      memset(dx_data, 0, sizeof(T) * batch_size * class_num);
      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 已提交
123 124 125 126 127 128
    }
  }
};

}  // namespace operators
}  // namespace paddle