softmax_with_cross_entropy_op.cc 6.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* 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"

namespace paddle {
namespace operators {

class SoftmaxWithCrossEntropyOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
23 24
  SoftmaxWithCrossEntropyOpMaker(framework::OpProto* proto,
                                 framework::OpAttrChecker* op_checker)
25
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
caoying03 已提交
26
    AddInput("Logits",
27
             "(Tensor, default: Tensor<float>), The unscaled log probabilities "
C
caoying03 已提交
28 29
             "which is a 2-D tensor with shape [N x K]. N is the batch_size, "
             "and K is the class number.")
30
        .NotInGradient();
C
caoying03 已提交
31 32
    AddInput(
        "Label",
33 34 35 36
        "(Tensor, default: Tensor<int>), The ground truth which is a 2-D "
        "tensor. "
        "If softLable is set to 0, Label is a Tensor<int> with shape [N x 1]. "
        "If softLable is set to 1, Label is a Tensor<float/double> "
C
caoying03 已提交
37 38 39
        "with shape [N x K].");
    AddOutput(
        "Softmax",
40
        "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N x K]. "
C
caoying03 已提交
41 42
        "The outputs value of softmax activation by given the input batch, "
        "which will be used in backward calculation.")
C
caoying03 已提交
43
        .AsIntermediate();
C
caoying03 已提交
44
    AddOutput("Loss",
45
              "(Tensor, default: Tensor<float>), A 2-D tensor. The cross "
C
caoying03 已提交
46
              "entropy loss with shape [N x 1].");
C
caoying03 已提交
47 48 49 50 51
    AddAttr<bool>(
        "softLabel",
        "(bool, default: false), A flag to indicate whether to interpretate "
        "the given labels as soft labels.")
        .SetDefault(false);
52 53 54 55 56 57 58 59 60 61 62 63 64 65
    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.

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.

C
caoying03 已提交
66
Equation:
67

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

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

2) soft label (a distribution over all classes)

Loss_j = -\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

)DOC");
77 78 79 80 81 82 83 84 85
  }
};

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

 protected:
  void InferShape(const framework::InferShapeContext& ctx) const override {
86 87 88 89 90 91 92 93 94 95
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Logits"),
                            "Input(Logits) should be not null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Label"),
                            "Input(Label) should be not null.");

    PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar("Softmax"),
                            "Output(Softmax) should be not null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar("Loss"),
                            "Output(Loss) should be not null.");

96
    const Tensor* logits = ctx.Input<Tensor>("Logits");
97
    const Tensor* labels = ctx.Input<Tensor>("Label");
C
caoying03 已提交
98 99
    PADDLE_ENFORCE_EQ(
        logits->dims().size(), 2UL,
100
        "The input of softmax_with_cross_entropy should be a 2-D tensor.");
C
caoying03 已提交
101 102
    PADDLE_ENFORCE_EQ(ctx.Input<Tensor>("Label")->dims().size(), 2UL,
                      "The labels should be a 2-D tensor.");
103 104 105 106 107 108

    if (ctx.Attr<bool>("softLabel")) {
      PADDLE_ENFORCE_EQ(logits->dims()[1], labels->dims()[1],
                        "If Attr(softLabel) == true, the 2nd dimension of "
                        "Input(X) and Input(Label) should be equal.");
    } else {
C
caoying03 已提交
109
      PADDLE_ENFORCE_EQ(labels->dims()[1], 1UL,
110 111 112 113 114 115 116 117 118
                        "If Attr(softLabel) == false, the 2nd dimension of "
                        "Input(Label) should be 1.");
    }

    ctx.Output<framework::Tensor>("Softmax")->Resize(logits->dims());
    ctx.Output<framework::Tensor>("Loss")->Resize({logits->dims()[0], 1});

    ctx.ShareLoD("Logits", /*->*/ "Softmax");
    ctx.ShareLoD("Logits", /*->*/ "Loss");
C
caoying03 已提交
119 120 121 122 123 124 125 126 127 128
  }
};

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

 protected:
  void InferShape(const framework::InferShapeContext& ctx) const override {
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Loss")),
129
                            "Input(Loss@Grad) should not be null.");
C
caoying03 已提交
130 131 132
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Softmax"),
                            "Input(Softmax) should be not null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Label"),
C
caoying03 已提交
133
                            "Input(Label) should be not null.");
134 135 136 137 138
    PADDLE_ENFORCE_NOT_NULL(ctx.OutputVar(framework::GradVarName("Logits")),
                            "Output(Logits@Grad) should be not null.");

    const Tensor* softmax = ctx.Input<Tensor>("Softmax");
    const Tensor* labels = ctx.Input<Tensor>("Label");
C
caoying03 已提交
139 140
    PADDLE_ENFORCE_EQ(ctx.Input<Tensor>("Label")->dims().size(), 2UL,
                      "The labels should be a 2-D tensor.");
141 142 143 144 145 146

    if (ctx.Attr<bool>("softLabel")) {
      PADDLE_ENFORCE_EQ(softmax->dims()[1], labels->dims()[1],
                        "When Attr(softLabel) == true, the 2nd dimension of "
                        "Input(X) and Input(Label) should be equal.");
    } else {
C
caoying03 已提交
147
      PADDLE_ENFORCE_EQ(labels->dims()[1], 1UL,
148 149 150
                        "When Attr(softLabel) == false, the 2nd dimension of "
                        "Input(Label) should be 1.");
    }
C
caoying03 已提交
151 152 153

    ctx.Output<framework::LoDTensor>(framework::GradVarName("Logits"))
        ->Resize(ctx.Input<Tensor>("Softmax")->dims());
154 155 156 157 158 159 160 161 162 163 164 165
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyOp,
            ops::SoftmaxWithCrossEntropyOpMaker,
            softmax_with_cross_entropy_grad,
            ops::SoftmaxWithCrossEntropyOpGrad);
166 167 168 169
REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy,
                       ops::SoftmaxWithCrossEntropyKernel<float>);
REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy_grad,
                       ops::SoftmaxWithCrossEntropyGradKernel<float>);