cross_entropy_op.cc 7.0 KB
Newer Older
Q
Qiao Longfei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* 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. */

#include "paddle/operators/cross_entropy_op.h"

namespace paddle {
namespace operators {

20
class CrossEntropyOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
21 22 23
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

24
 protected:
25
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
26 27 28
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput("Y"), "Output(Y) should be not null.");
29

Q
Qiao Longfei 已提交
30 31
    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
C
caoying03 已提交
32 33 34
    PADDLE_ENFORCE_EQ(x_dims.size(), 2UL, "Input(X)'s rank should be 2.");
    PADDLE_ENFORCE_EQ(label_dims.size(), 2UL,
                      "Input(Label)'s rank should be 2.");
Q
Qiao Longfei 已提交
35
    PADDLE_ENFORCE_EQ(x_dims[0], label_dims[0],
C
caoying03 已提交
36
                      "The 1st dimension of Input(X) and Input(Label) should "
37
                      "be equal.");
Q
Qiao Longfei 已提交
38 39
    if (ctx->Attrs().Get<bool>("softLabel")) {
      PADDLE_ENFORCE_EQ(x_dims[1], label_dims[1],
C
caoying03 已提交
40
                        "If Attr(softLabel) == true, the 2nd dimension of "
C
caoying03 已提交
41
                        "Input(X) and Input(Label) should be equal.");
42
    } else {
C
caoying03 已提交
43
      PADDLE_ENFORCE_EQ(label_dims[1], 1UL,
C
caoying03 已提交
44
                        "If Attr(softLabel) == false, the 2nd dimension of "
C
caoying03 已提交
45
                        "Input(Label) should be 1.");
46
    }
47

Q
Qiao Longfei 已提交
48 49
    ctx->SetOutputDim("Y", {x_dims[0], 1});
    ctx->ShareLoD("X", /*->*/ "Y");
Q
Qiao Longfei 已提交
50
  }
Y
Yu Yang 已提交
51

52
  // Explicitly set that data type of the output of the cross_entropy operator
C
caoying03 已提交
53
  // is determined by its input "X".
Y
Yu Yang 已提交
54 55 56 57
  framework::DataType IndicateDataType(
      const framework::ExecutionContext& ctx) const override {
    return framework::ToDataType(ctx.Input<Tensor>("X")->type());
  }
Q
Qiao Longfei 已提交
58 59
};

60
class CrossEntropyGradientOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
61 62 63
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

Y
Yan Chunwei 已提交
64
 protected:
65
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
66 67 68 69 70 71
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Y")),
                   "Input(Y@GRAD) shoudl be not null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")),
                   "Output(X@GRAD) should be not null.");
72

Q
Qiao Longfei 已提交
73 74 75 76 77 78 79
    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
    auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y"));
    PADDLE_ENFORCE_EQ(x_dims.size(), 2, "Input(X)'s rank should be 2.");
    PADDLE_ENFORCE_EQ(dy_dims.size(), 2, "Input(Y@Grad)'s rank should be 2.");
    PADDLE_ENFORCE_EQ(label_dims.size(), 2, "Input(Label)'s rank should be 2.");
    PADDLE_ENFORCE_EQ(x_dims[0], label_dims[0],
C
caoying03 已提交
80
                      "The 1st dimension of Input(X) and Input(Label) should "
81
                      "be equal.");
Q
Qiao Longfei 已提交
82
    PADDLE_ENFORCE_EQ(x_dims[0], dy_dims[0],
C
caoying03 已提交
83
                      "The 1st dimension of Input(X) and Input(Y@Grad) should "
84
                      "be equal.");
Q
Qiao Longfei 已提交
85
    PADDLE_ENFORCE_EQ(dy_dims[1], 1,
C
caoying03 已提交
86
                      "The 2nd dimension of Input(Y@Grad) should be 1.");
Q
Qiao Longfei 已提交
87 88
    if (ctx->Attrs().Get<bool>("softLabel")) {
      PADDLE_ENFORCE_EQ(x_dims[1], label_dims[1],
C
caoying03 已提交
89
                        "When Attr(softLabel) == true, the 2nd dimension of "
C
caoying03 已提交
90
                        "Input(X) and Input(Label) should be equal.");
91
    } else {
Q
Qiao Longfei 已提交
92
      PADDLE_ENFORCE_EQ(label_dims[1], 1,
C
caoying03 已提交
93
                        "When Attr(softLabel) == false, the 2nd dimension of "
C
caoying03 已提交
94
                        "Input(Label) should be 1.");
95
    }
Q
Qiao Longfei 已提交
96
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
Y
Yan Chunwei 已提交
97
  }
Y
Yu Yang 已提交
98 99 100 101 102 103

  // CrossEntropy's data type just determined by "X"
  framework::DataType IndicateDataType(
      const framework::ExecutionContext& ctx) const override {
    return framework::ToDataType(ctx.Input<Tensor>("X")->type());
  }
Y
Yan Chunwei 已提交
104 105
};

106
class CrossEntropyOpMaker : public framework::OpProtoAndCheckerMaker {
107
 public:
Q
Qiao Longfei 已提交
108 109
  CrossEntropyOpMaker(framework::OpProto* proto,
                      framework::OpAttrChecker* op_checker)
110
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
caoying03 已提交
111 112 113 114 115
    AddInput("X",
             "(Tensor, default Tensor<float>), a 2-D tensor with shape N x D, "
             "where N is the batch size and D is the number of classes. "
             "This input is a probability computed by the previous operator, "
             "which is almost always the result of a softmax operator.");
C
caoying03 已提交
116 117 118 119 120 121 122 123
    AddInput(
        "Label",
        "(Tensor, default Tensor<int>), the ground truth which is "
        "a 2-D tensor. "
        "When softLabel is set to false, `Label` is a Tensor<int> with shape "
        "[N x 1]. "
        "When softLabel is set to true, `Label` is a Tensor<float/double> "
        "with shape [N x K].");
C
caoying03 已提交
124
    AddOutput("Y",
C
caoying03 已提交
125
              "(Tensor, default Tensor<float>), a 2-D tensor "
C
caoying03 已提交
126 127
              "with shape [N x 1]. The cross entropy loss.");
    AddAttr<bool>(
C
caoying03 已提交
128
        "softLabel",
C
caoying03 已提交
129 130
        "(bool, default false), a flag to indicate whether to interpretate "
        "the given labels as soft labels.")
131
        .SetDefault(false);
Q
Qiao Longfei 已提交
132
    AddComment(R"DOC(
133
CrossEntropy Operator.
Q
Qiao Longfei 已提交
134

135 136 137
It supports both standard cross-entropy and soft-label cross-entropy loss
computation.
1) One-hot cross-entropy:
C
caoying03 已提交
138
    softLabel = false, Label[i, 0] indicates the class index for sample i:
139

140
                Y[i] = -log(X[i, Label[i]])
Q
Qiao Longfei 已提交
141

142
2) Soft-label cross-entropy:
C
caoying03 已提交
143
    softLabel = true, Label[i, j] indicates the soft label of class j
144
    for sample i:
145

146
                Y[i] = \sum_j{-Label[i, j] * log(X[i, j])}
147

148
   Please make sure that in this case the summuation of each row of Label
149 150 151 152 153 154
   equals one.

3) One-hot cross-entropy with vecterized Input(Label):
     As a special case of 2), when each row of Input(Label) has only one
     non-zero element (equals 1), soft-label cross-entropy degenerates to a
     one-hot cross-entropy with one-hot label representation.
D
dangqingqing 已提交
155 156 157

Both the input `X` and `Label` can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD with input `X`.
Q
Qiao Longfei 已提交
158 159 160 161 162 163
)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
164
namespace ops = paddle::operators;
165 166 167 168 169
REGISTER_OP(cross_entropy, ops::CrossEntropyOp, ops::CrossEntropyOpMaker,
            cross_entropy_grad, ops::CrossEntropyGradientOp);
REGISTER_OP_CPU_KERNEL(cross_entropy, ops::CrossEntropyOpKernel<float>);
REGISTER_OP_CPU_KERNEL(cross_entropy_grad,
                       ops::CrossEntropyGradientOpKernel<float>);