softmax_with_cross_entropy_op.cc 4.3 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 23 24 25
/* 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 SoftmaxWithCrossEntropyOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
C
caoying03 已提交
26
    auto logits = ctx.Input<Tensor>("Logits");
27 28 29
    PADDLE_ENFORCE(
        logits->dims().size() == 2UL,
        "The input of softmax_with_cross_entropy should be a 2-d tensor.");
C
caoying03 已提交
30
    PADDLE_ENFORCE(ctx.Input<Tensor>("Label")->dims().size() == 1UL,
31
                   "The label should be a 1-d tensor.");
C
caoying03 已提交
32
    ctx.Output<Tensor>("Label")->Resize({logits->dims()[0]});
33 34 35 36 37 38 39 40 41
  }
};

class SoftmaxWithCrossEntropyOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  SoftmaxWithCrossEntropyOpMaker(framework::OpProto *proto,
                                 framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
caoying03 已提交
42
    AddInput("Logits",
43 44
             "The unscaled log probabilities which is a 2-D tensor<float> with"
             "shape [N x K]. N is the batch_size, and K is the class number.");
C
caoying03 已提交
45 46 47 48 49 50
    AddInput("Label", "The ground truth. A 1-D tensor<int> with shape N.");
    AddOutput("Softmax",
              "Store the outputs of softmax function, "
              "which will be used in backward calculation.")
        .AsIntermediate();
    AddOutput("Loss", "A 1-D tensor<float> with shape N.");
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    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.
)DOC");
  }
};

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

 protected:
  void InferShape(const framework::InferShapeContext &ctx) const override {
C
caoying03 已提交
74 75 76 77
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Loss"),
                            "Input(Loss) should be not null.");
    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar(framework::GradVarName("Loss")),
                            "Input(Loss@GRAD) should be not null.");
78
    PADDLE_ENFORCE_EQ(
C
caoying03 已提交
79 80 81 82 83 84 85 86 87 88
        ctx.Input<Tensor>("Logits")->dims(),
        ctx.Input<Tensor>(framework::GradVarName("Logits"))->dims(),
        "Input(Logits) and its gradients should have a same shape.");
    PADDLE_ENFORCE_EQ(
        ctx.Input<Tensor>("Logits")->dims(),
        ctx.Input<Tensor>(framework::GradVarName("Logits"))->dims(),
        "Input(Logits) and its gradients should have a same shape.");

    PADDLE_ENFORCE_NOT_NULL(ctx.InputVar("Label"),
                            "Input(Lable) should be not null.");
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  }
};

}  // 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);
REGISTER_OP_CPU_KERNEL(
    softmax_with_cross_entropy,
    ops::SoftmaxWithCrossEntropyKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(
    softmax_with_cross_entropy_grad,
    ops::SoftmaxWithCrossEntropyGradKernel<paddle::platform::CPUPlace, float>);