cross_entropy_op.cc 8.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Q
Qiao Longfei 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/cross_entropy_op.h"
Q
Qiao Longfei 已提交
16 17 18 19

namespace paddle {
namespace operators {

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

24
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
25 26 27
    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.");
28

Q
Qiao Longfei 已提交
29 30
    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
F
stash  
fengjiayi 已提交
31 32 33 34 35 36 37
    int rank = x_dims.size();
    PADDLE_ENFORCE_EQ(rank, label_dims.size(),
                      "Input(X) and Input(Label) shall have the same rank.");
    PADDLE_ENFORCE_EQ(framework::slice_ddim(x_dims, 0, rank - 1),
                      framework::slice_ddim(label_dims, 0, rank - 1),
                      "Input(X) and Input(Label) shall have the same shape "
                      "except the last dimension.");
38
    if (ctx->Attrs().Get<bool>("soft_label")) {
F
stash  
fengjiayi 已提交
39 40
      PADDLE_ENFORCE_EQ(x_dims[rank - 1], label_dims[rank - 1],
                        "If Attr(soft_label) == true, the last dimension of "
C
caoying03 已提交
41
                        "Input(X) and Input(Label) should be equal.");
42
    } else {
F
stash  
fengjiayi 已提交
43 44
      PADDLE_ENFORCE_EQ(label_dims[rank - 1], 1UL,
                        "If Attr(softLabel) == false, the last dimension of "
C
caoying03 已提交
45
                        "Input(Label) should be 1.");
46
    }
47

F
stash  
fengjiayi 已提交
48 49 50 51 52
    auto out_dim_vec =
        framework::vectorize(framework::slice_ddim(x_dims, 0, rank - 1));
    out_dim_vec.push_back(1);

    ctx->SetOutputDim("Y", framework::make_ddim(out_dim_vec));
Q
Qiao Longfei 已提交
53
    ctx->ShareLoD("X", /*->*/ "Y");
Q
Qiao Longfei 已提交
54
  }
Y
Yu Yang 已提交
55

56
 protected:
C
Cao Ying 已提交
57
  // Explicitly set that the data type of computation kernel of cross_entropy
C
caoying03 已提交
58
  // is determined by its input "X".
59
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
60
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
61 62 63
    return framework::OpKernelType(
        framework::ToDataType(ctx.Input<Tensor>("X")->type()),
        ctx.device_context());
Y
Yu Yang 已提交
64
  }
Q
Qiao Longfei 已提交
65 66
};

67
class CrossEntropyGradientOp : public framework::OperatorWithKernel {
Y
Yu Yang 已提交
68 69 70
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

71
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
Qiao Longfei 已提交
72 73 74 75 76 77
    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.");
78

Q
Qiao Longfei 已提交
79 80 81
    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
    auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y"));
F
stash  
fengjiayi 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    int rank = x_dims.size();
    PADDLE_ENFORCE_EQ(dy_dims.size(), rank,
                      "Input(Y@Grad) and Input(X) should have the same rank.");
    PADDLE_ENFORCE_EQ(label_dims.size(), rank,
                      "Input(Label) and Input(X) should have the same rank.");
    PADDLE_ENFORCE_EQ(framework::slice_ddim(x_dims, 0, rank - 1),
                      framework::slice_ddim(label_dims, 0, rank - 1),
                      "The Input(X) and Input(Label) should have the same "
                      "shape except the last dimension.");
    PADDLE_ENFORCE_EQ(framework::slice_ddim(x_dims, 0, rank - 1),
                      framework::slice_ddim(dy_dims, 0, rank - 1),
                      "The Input(X) and Input(Y@Grad) should have the same "
                      "shape except the last dimension.");
    PADDLE_ENFORCE_EQ(dy_dims[rank - 1], 1,
                      "The last dimension of Input(Y@Grad) should be 1.");
97
    if (ctx->Attrs().Get<bool>("soft_label")) {
F
stash  
fengjiayi 已提交
98 99
      PADDLE_ENFORCE_EQ(x_dims[rank - 1], label_dims[rank - 1],
                        "When Attr(soft_label) == true, the last dimension of "
C
caoying03 已提交
100
                        "Input(X) and Input(Label) should be equal.");
101
    } else {
F
stash  
fengjiayi 已提交
102 103
      PADDLE_ENFORCE_EQ(label_dims[rank - 1], 1,
                        "When Attr(soft_label) == false, the last dimension of "
C
caoying03 已提交
104
                        "Input(Label) should be 1.");
105
    }
Q
Qiao Longfei 已提交
106
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
Q
Qiao Longfei 已提交
107
    ctx->ShareLoD("X", framework::GradVarName("X"));
Y
Yan Chunwei 已提交
108
  }
Y
Yu Yang 已提交
109

110
 protected:
C
Cao Ying 已提交
111 112
  // Explicitly set that the data type of computation kernel of cross_entropy
  // is determined by its input "X".
113
  framework::OpKernelType GetExpectedKernelType(
Y
Yu Yang 已提交
114
      const framework::ExecutionContext& ctx) const override {
Y
Yu Yang 已提交
115 116 117
    return framework::OpKernelType(
        framework::ToDataType(ctx.Input<Tensor>("X")->type()),
        ctx.device_context());
Y
Yu Yang 已提交
118
  }
Y
Yan Chunwei 已提交
119 120
};

121
class CrossEntropyOpMaker : public framework::OpProtoAndCheckerMaker {
122
 public:
Y
Yu Yang 已提交
123
  void Make() override {
C
caoying03 已提交
124
    AddInput("X",
F
stash  
fengjiayi 已提交
125 126 127 128 129 130 131 132 133 134
             "(Tensor, default Tensor<float>), a tensor whose last dimension "
             "size is equal to the number of classes. This input is a "
             "probability computed by the previous operator, which is almost "
             "always the result of a softmax operator.");
    AddInput(
        "Label",
        "(Tensor), the tensor which represents the ground truth. It has the "
        "same shape with 'X' except the last dimension. When soft_label is set "
        "to false, the last dimension size is 1; when soft_label is set to "
        "true, the last dimension size is equal to the number of classes.");
C
caoying03 已提交
135
    AddOutput("Y",
F
stash  
fengjiayi 已提交
136 137 138
              "(Tensor, default Tensor<float>), a tensor whose shape is same "
              "with 'X' except that the last dimension size is 1. It "
              "represents the cross entropy loss.");
C
caoying03 已提交
139 140 141
    AddAttr<bool>("soft_label",
                  "(bool, default false), a flag indicating whether to "
                  "interpretate the given labels as soft labels.")
142
        .SetDefault(false);
Q
Qiao Longfei 已提交
143
    AddComment(R"DOC(
144
CrossEntropy Operator.
Q
Qiao Longfei 已提交
145

F
stash  
fengjiayi 已提交
146 147 148 149 150 151
The input 'X' and 'Label' will first be logically flattened to 2-D matrixs. 
The matrix's second dimension(row length) is as same as the original last 
dimension, and the first dimension(column length) is the product of all other 
original dimensions. Then the softmax computation will take palce on each raw 
of flattened matrixs.

152 153 154
It supports both standard cross-entropy and soft-label cross-entropy loss
computation.
1) One-hot cross-entropy:
155
    soft_label = false, Label[i, 0] indicates the class index for sample i:
156

K
Kexin Zhao 已提交
157
                $Y[i] = -\log(X[i, Label[i]])$
Q
Qiao Longfei 已提交
158

159
2) Soft-label cross-entropy:
160
    soft_label = true, Label[i, j] indicates the soft label of class j
161
    for sample i:
162

K
Kexin Zhao 已提交
163
                $Y[i] = \sum_j{-Label[i, j] * log(X[i, j])}$
164

165
   Please make sure that in this case the summuation of each row of Label
166 167 168 169 170 171
   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 已提交
172

K
Kexin Zhao 已提交
173 174 175
Both the input X and Label can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input X.

Q
Qiao Longfei 已提交
176 177 178 179 180 181
)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

D
dongzhihong 已提交
182
namespace ops = paddle::operators;
183 184
using CPUCtx = paddle::platform::CPUDeviceContext;

Y
Yang Yang 已提交
185
REGISTER_OPERATOR(cross_entropy, ops::CrossEntropyOp, ops::CrossEntropyOpMaker,
186 187
                  paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(cross_entropy_grad, ops::CrossEntropyGradientOp);
188 189
REGISTER_OP_CPU_KERNEL(cross_entropy, ops::CrossEntropyOpKernel<CPUCtx, float>,
                       ops::CrossEntropyOpKernel<CPUCtx, double>);
190
REGISTER_OP_CPU_KERNEL(cross_entropy_grad,
191 192
                       ops::CrossEntropyGradientOpKernel<CPUCtx, float>,
                       ops::CrossEntropyGradientOpKernel<CPUCtx, double>);