bce_loss_op.cc 5.7 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.

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 <memory>
#include <string>
#include <vector>

19 20 21 22
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/phi/infermeta/binary.h"

C
ceci3 已提交
23 24 25 26 27 28 29 30
namespace paddle {
namespace operators {

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

 protected:
31
  phi::KernelKey GetExpectedKernelType(
C
ceci3 已提交
32
      const framework::ExecutionContext& ctx) const override {
33 34
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                          ctx.device_context().GetPlace());
C
ceci3 已提交
35 36 37 38 39 40 41 42
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
C
ceci3 已提交
43 44
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "BCELossGrad");
    OP_INOUT_CHECK(ctx->HasInput("Label"), "Input", "Label", "BCELossGrad");
45 46 47 48 49 50 51 52
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
                   "BCELossGrad");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   framework::GradVarName("X"),
                   "BCELossGrad");
C
ceci3 已提交
53 54

    auto x_dims = ctx->GetInputDim("X");
55
    auto labels_dims = ctx->GetInputDim("Label");
C
ceci3 已提交
56
    auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out"));
57 58

    bool check = true;
59
    if ((!ctx->IsRuntime()) &&
60
        (phi::product(x_dims) <= 0 || phi::product(labels_dims) <= 0)) {
61 62 63
      check = false;
    }

C
ceci3 已提交
64
    if (check) {
65 66
      PADDLE_ENFORCE_EQ(x_dims,
                        labels_dims,
67 68 69 70
                        platform::errors::InvalidArgument(
                            "Input(X) and Input(Label) shall have the same "
                            "shape. But received: the shape of Input(X) is "
                            "[%s], the shape of Input(Label) is [%s].",
71 72
                            x_dims,
                            labels_dims));
73

74 75
      PADDLE_ENFORCE_EQ(x_dims,
                        dout_dims,
C
ceci3 已提交
76
                        platform::errors::InvalidArgument(
77 78 79
                            "Input(X) and Input(Out@Grad) shall have the same "
                            "shape. But received: the shape of Input(X) is "
                            "[%s], the shape of Input(Out@Grad) is [%s].",
80 81
                            x_dims,
                            dout_dims));
C
ceci3 已提交
82
    }
83

C
ceci3 已提交
84 85 86 87 88
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
    ctx->ShareLoD("X", framework::GradVarName("X"));
  }

 protected:
89
  phi::KernelKey GetExpectedKernelType(
C
ceci3 已提交
90
      const framework::ExecutionContext& ctx) const override {
91 92
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                          ctx.device_context().GetPlace());
C
ceci3 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  }
};

class BCELossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(Tensor, default Tensor<float>), the input is a tensor of logits"
             "computed by the previous operator, which is always the result of"
             "a sigmoid operator. Input must between in 0 and 1.");
    AddInput("Label",
             "(Tensor, default Tensor<float>), have same shape with input"
             "label should between in 0 and 1.");
    AddOutput("Out",
              "(Tensor, default Tensor<float>), have same shape with"
              "input");
    AddComment(R"DOC(
BinaryCrossEntropy operator.

This measures the element-wise probability error in classification tasks
in which each class is independent.

The logitstic loss is given as follows:
      $$loss = -Label * \log(X) - (1 - Label) * \log(1 - X)$$
)DOC");
  }
};

template <typename T>
class BCELossGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("bce_loss_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("Label", this->Input("Label"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
  }
};

DECLARE_INPLACE_OP_INFERER(BCELossInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(BCELossGradInplaceInferer,
                           {framework::GradVarName("Out"),
                            framework::GradVarName("X")});

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
145 146
DECLARE_INFER_SHAPE_FUNCTOR(bce_loss,
                            BCELossInferShapeFunctor,
147
                            PD_INFER_META(phi::BCELossInferMeta));
148

149 150 151
REGISTER_OPERATOR(bce_loss,
                  ops::BCELossOp,
                  ops::BCELossOpMaker,
C
ceci3 已提交
152 153
                  ops::BCELossGradOpMaker<paddle::framework::OpDesc>,
                  ops::BCELossGradOpMaker<paddle::imperative::OpBase>,
154 155 156 157
                  ops::BCELossInplaceInferer,
                  BCELossInferShapeFunctor);
REGISTER_OPERATOR(bce_loss_grad,
                  ops::BCELossGradOp,
C
ceci3 已提交
158
                  ops::BCELossGradInplaceInferer);