cross_entropy_op.cc 5.8 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:
D
dongzhihong 已提交
25
  void InferShape(const framework::InferShapeContext &ctx) const override {
26
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"), "Input(X) must not be null.");
27
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Label"),
28 29 30 31 32 33 34 35 36 37 38
                            "Input(Label) must not be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar("Y"), "Output(Y) must not be null.");

    auto x = ctx.Input<Tensor>("X");
    auto label = ctx.Input<Tensor>("Label");
    PADDLE_ENFORCE_EQ(x->dims().size(), 2, "Input(X)'s rank must be 2.");
    PADDLE_ENFORCE_EQ(label->dims().size(), 2,
                      "Input(Label)'s rank must be 2.");
    PADDLE_ENFORCE_EQ(x->dims()[0], label->dims()[0],
                      "The 1st dimension of Input(X) and Input(Label) must "
                      "be equal.");
39
    if (ctx.Attr<bool>("soft_label")) {
40
      PADDLE_ENFORCE_EQ(x->dims()[1], label->dims()[1],
41
                        "If Attr(soft_label) == true, The 2nd dimension of "
42
                        "Input(X) and Input(Label) must be equal.");
43
    } else {
44
      PADDLE_ENFORCE_EQ(label->dims()[1], 1,
45
                        "If Attr(soft_label) == false, The 2nd dimension of "
46
                        "Input(Label) must be 1.");
47
    }
48

D
dangqingqing 已提交
49
    ctx.Output<Tensor>("Y")->Resize({x->dims()[0], 1});
50
    ctx.ShareLoD("X", /*->*/ "Y");
Q
Qiao Longfei 已提交
51 52 53
  }
};

54
class CrossEntropyGradientOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
55 56 57
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

Y
Yan Chunwei 已提交
58
 protected:
D
dongzhihong 已提交
59
  void InferShape(const framework::InferShapeContext &ctx) const override {
60 61 62 63 64
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("X"), "Input(X) must not be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Label"),
                            "Input(Label) must not be null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Y")),
                            "Input(Y@GRAD) must not be null.");
65

66
    auto x = ctx.Input<Tensor>("X");
67 68 69 70 71 72 73 74 75 76 77 78 79 80
    auto label = ctx.Input<Tensor>("Label");
    auto dy = ctx.Input<Tensor>(framework::GradVarName("Y"));
    PADDLE_ENFORCE_EQ(x->dims().size(), 2, "Input(X)'s rank must be 2.");
    PADDLE_ENFORCE_EQ(dy->dims().size(), 2, "Input(Y@Grad)'s rank must be 2.");
    PADDLE_ENFORCE_EQ(label->dims().size(), 2,
                      "Input(Label)'s rank must be 2.");
    PADDLE_ENFORCE_EQ(x->dims()[0], label->dims()[0],
                      "The 1st dimension of Input(X) and Input(Label) must "
                      "be equal.");
    PADDLE_ENFORCE_EQ(x->dims()[0], dy->dims()[0],
                      "The 1st dimension of Input(X) and Input(Y@Grad) must "
                      "be equal.");
    PADDLE_ENFORCE_EQ(dy->dims()[1], 1,
                      "The 2nd dimension of Input(Y@Grad) must be 1.");
81
    if (ctx.Attr<bool>("soft_label")) {
82
      PADDLE_ENFORCE_EQ(x->dims()[1], label->dims()[1],
83
                        "If Attr(soft_label) == true, The 2nd dimension of "
84 85 86
                        "Input(X) and Input(Label) must be equal.");
    } else {
      PADDLE_ENFORCE_EQ(label->dims()[1], 1,
87
                        "If Attr(soft_label) == false, The 2nd dimension of "
88 89
                        "Input(Label) must be 1.");
    }
Y
Yan Chunwei 已提交
90

D
dangqingqing 已提交
91
    auto dx = ctx.Output<Tensor>(framework::GradVarName("X"));
92
    dx->Resize(x->dims());
Y
Yan Chunwei 已提交
93 94 95
  }
};

96
class CrossEntropyOpMaker : public framework::OpProtoAndCheckerMaker {
97
 public:
98 99
  CrossEntropyOpMaker(framework::OpProto *proto,
                      framework::OpAttrChecker *op_checker)
100
      : OpProtoAndCheckerMaker(proto, op_checker) {
101 102 103
    AddInput("X", "The first input of CrossEntropyOp");
    AddInput("Label", "The second input of CrossEntropyOp");
    AddOutput("Y", "The output of CrossEntropyOp");
104 105
    AddAttr<bool>("soft_label", "Is soft label. Default zero.")
        .SetDefault(false);
106

Q
Qiao Longfei 已提交
107
    AddComment(R"DOC(
108
CrossEntropy Operator.
Q
Qiao Longfei 已提交
109

110 111 112
It supports both standard cross-entropy and soft-label cross-entropy loss
computation.
1) One-hot cross-entropy:
113
    soft_label = False, Label[i, 0] indicates the class index for sample i:
114

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

117
2) Soft-label cross-entropy:
118
    soft_label = True, Label[i, j] indicates the soft label of class j
119
    for sample i:
120

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

123
   Please make sure that in this case the summuation of each row of Label
124 125 126 127 128 129
   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 已提交
130 131 132

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 已提交
133 134 135 136 137 138
)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
139
namespace ops = paddle::operators;
140 141 142 143 144
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>);