softmax_with_cross_entropy_op.cc 7.9 KB
Newer Older
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. */

#include "paddle/operators/softmax_with_cross_entropy_op.h"
Y
Yu Yang 已提交
16
#include <paddle/function/TensorType.h>
Y
Yu Yang 已提交
17 18
#include <iostream>

19 20 21 22 23 24
namespace paddle {
namespace operators {

class SoftmaxWithCrossEntropyOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
25 26
  SoftmaxWithCrossEntropyOpMaker(framework::OpProto* proto,
                                 framework::OpAttrChecker* op_checker)
27
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
caoying03 已提交
28
    AddInput("Logits",
29
             "(Tensor, default: Tensor<float>), The unscaled log probabilities "
C
caoying03 已提交
30
             "which is a 2-D tensor with shape [N x K]. N is the batch_size, "
31 32 33 34
             "and K is the class number.");
    AddInput("Label",
             "(Tensor, default: Tensor<int>), The ground truth which is a 2-D "
             "tensor. "
C
caoying03 已提交
35 36 37
             "If softLabel is set to false, Label is a Tensor<int> with shape "
             "[N x 1]."
             "If softLabel is set to true, Label is a Tensor<float/double> "
38
             "with shape [N x K].");
C
caoying03 已提交
39 40
    AddOutput(
        "Softmax",
41
        "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N x K]. "
C
caoying03 已提交
42 43
        "The outputs value of softmax activation by given the input batch, "
        "which will be used in backward calculation.")
C
caoying03 已提交
44
        .AsIntermediate();
C
caoying03 已提交
45
    AddOutput("Loss",
46
              "(Tensor, default: Tensor<float>), A 2-D tensor. The cross "
C
caoying03 已提交
47
              "entropy loss with shape [N x 1].");
C
caoying03 已提交
48 49 50 51 52
    AddAttr<bool>(
        "softLabel",
        "(bool, default: false), A flag to indicate whether to interpretate "
        "the given labels as soft labels.")
        .SetDefault(false);
53 54 55 56 57 58 59 60 61 62
    AddComment(R"DOC(
Cross entropy loss with softmax are used as the output layer extensively. This
operator computes the softmax normalized values for each row of the input
tensor, after which cross-entropy loss is then computed. This provides a more
numerically stable gradient.

Because this operators performs a softmax on logits internally, it expects
unscaled logits. Please do not call this op with the output of softmax operator,
which will produce incorrect results.

63 64 65
When the attribute softLabel is set false, this operators expects mutually
exclusive hard labels, each sample in a batch is in exactly one class with
probabilities 1. Each sample in the batch with one and only one label.
66

C
caoying03 已提交
67
Equation:
68

C
caoying03 已提交
69
1) hard label (one-hot label)
70

71 72 73
Loss_j = \f$ -\text{Logit}_{Label_j} +
\log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right),
j = 1, ..., K $\f
C
caoying03 已提交
74 75 76

2) soft label (a distribution over all classes)

77 78 79
Loss_j = \f$ -\sum_{i=0}^{K}\text{Label}_i\left(\text{Logit}_i -
\log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right)\right),
j = 1,...,K $\f
C
caoying03 已提交
80 81

)DOC");
82 83 84 85 86 87 88 89
  }
};

class SoftmaxWithCrossEntropyOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
90
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
qiaolongfei 已提交
91 92 93 94 95 96 97 98 99 100
    PADDLE_ENFORCE(ctx->HasInput("Logits"),
                   "Input(Logits) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null.");

    PADDLE_ENFORCE(ctx->HasOutput("Softmax"),
                   "Output(Softmax) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput("Loss"), "Output(Loss) should be not null.");

    auto logits_dims = ctx->GetInputDim("Logits");
    auto labels_dims = ctx->GetInputDim("Label");
C
caoying03 已提交
101
    PADDLE_ENFORCE_EQ(
Q
qiaolongfei 已提交
102
        logits_dims.size(), 2UL,
103
        "The input of softmax_with_cross_entropy should be a 2-D tensor.");
Q
qiaolongfei 已提交
104
    PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL,
C
caoying03 已提交
105
                      "The labels should be a 2-D tensor.");
106

Q
qiaolongfei 已提交
107 108
    if (ctx->Attrs().Get<bool>("softLabel")) {
      PADDLE_ENFORCE_EQ(logits_dims[1], labels_dims[1],
109 110 111
                        "If Attr(softLabel) == true, the 2nd dimension of "
                        "Input(X) and Input(Label) should be equal.");
    } else {
Q
qiaolongfei 已提交
112
      PADDLE_ENFORCE_EQ(labels_dims[1], 1UL,
113 114 115 116
                        "If Attr(softLabel) == false, the 2nd dimension of "
                        "Input(Label) should be 1.");
    }

Q
qiaolongfei 已提交
117 118
    ctx->SetOutputDim("Softmax", logits_dims);
    ctx->SetOutputDim("Loss", {logits_dims[0], 1});
119

Q
qiaolongfei 已提交
120 121
    ctx->ShareLoD("Logits", /*->*/ "Softmax");
    ctx->ShareLoD("Logits", /*->*/ "Loss");
C
caoying03 已提交
122
  }
Y
Yu Yang 已提交
123 124 125 126 127

  framework::DataType IndicateDataType(
      const framework::ExecutionContext& ctx) const override {
    return framework::ToDataType(ctx.Input<Tensor>("Logits")->type());
  }
C
caoying03 已提交
128 129 130 131 132 133 134
};

class SoftmaxWithCrossEntropyOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
135
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
qiaolongfei 已提交
136 137 138 139 140 141 142 143 144 145 146
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")),
                   "Input(Loss@Grad) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Softmax"),
                   "Input(Softmax) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")),
                   "Output(Logits@Grad) should be not null.");

    auto softmax_dims = ctx->GetInputDim("Softmax");
    auto labels_dims = ctx->GetInputDim("Label");
    PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL,
C
caoying03 已提交
147
                      "The labels should be a 2-D tensor.");
148

Q
qiaolongfei 已提交
149 150
    if (ctx->Attrs().Get<bool>("softLabel")) {
      PADDLE_ENFORCE_EQ(softmax_dims[1], labels_dims[1],
151 152 153
                        "When Attr(softLabel) == true, the 2nd dimension of "
                        "Input(X) and Input(Label) should be equal.");
    } else {
Q
qiaolongfei 已提交
154
      PADDLE_ENFORCE_EQ(labels_dims[1], 1UL,
155 156 157
                        "When Attr(softLabel) == false, the 2nd dimension of "
                        "Input(Label) should be 1.");
    }
C
caoying03 已提交
158

Q
qiaolongfei 已提交
159 160
    ctx->SetOutputDim(framework::GradVarName("Logits"),
                      ctx->GetInputDim("Softmax"));
161
  }
Y
Yu Yang 已提交
162 163 164

  framework::DataType IndicateDataType(
      const framework::ExecutionContext& ctx) const override {
Y
Fix CI  
Yu Yang 已提交
165 166
    return framework::ToDataType(
        ctx.Input<Tensor>(framework::GradVarName("Loss"))->type());
Y
Yu Yang 已提交
167
  }
168 169
};

170 171 172 173 174
class SoftmaxGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
Y
Yu Yang 已提交
175 176 177 178 179 180 181 182 183 184 185
  std::unique_ptr<framework::OpDescBind> Apply() const override {
    auto* grad_op = new framework::OpDescBind();
    grad_op->SetType("softmax_with_cross_entropy_grad");
    grad_op->SetInput("Label", Input("Label"));
    grad_op->SetInput("Softmax", Output("Softmax"));
    grad_op->SetInput("Loss", Output("Loss"));
    grad_op->SetInput(framework::GradVarName("Softmax"), OutputGrad("Softmax"));
    grad_op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss"));
    grad_op->SetOutput(framework::GradVarName("Logits"), InputGrad("Logits"));
    grad_op->SetAttrMap(Attrs());
    return std::unique_ptr<framework::OpDescBind>(grad_op);
186 187 188
  }
};

189 190 191 192 193
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

194
REGISTER_OPERATOR(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyOp,
Y
Yu Yang 已提交
195
                  ops::SoftmaxWithCrossEntropyOpMaker, ops::SoftmaxGradMaker);
196 197
REGISTER_OPERATOR(softmax_with_cross_entropy_grad,
                  ops::SoftmaxWithCrossEntropyOpGrad);
198 199 200 201
REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy,
                       ops::SoftmaxWithCrossEntropyKernel<float>);
REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy_grad,
                       ops::SoftmaxWithCrossEntropyGradKernel<float>);