hinge_loss_op.cc 5.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
S
Siddharth Goyal 已提交
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/hinge_loss_op.h"
16 17 18
#include <memory>
#include <string>
#include <vector>
S
Siddharth Goyal 已提交
19 20 21 22 23 24 25 26 27

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
28 29
    OP_INOUT_CHECK(ctx->HasInput("Logits"), "Input", "Logits", "HingeLoss");
    OP_INOUT_CHECK(ctx->HasInput("Labels"), "Input", "Labels", "HingeLoss");
S
Siddharth Goyal 已提交
30 31 32 33

    auto pred_dims = ctx->GetInputDim("Logits");
    auto label_dims = ctx->GetInputDim("Labels");

34 35 36 37 38 39 40 41 42 43 44 45 46
    PADDLE_ENFORCE_EQ(
        pred_dims, label_dims,
        platform::errors::InvalidArgument(
            "The Input(input) and Input(label) should have the same "
            "shape, but received input shape [%s] != label shape [%s]",
            pred_dims, label_dims));

    PADDLE_ENFORCE_EQ(
        pred_dims.size(), 2,
        platform::errors::InvalidArgument("Input(input) rank should be 2, "
                                          "but received input rank(%d) != 2",
                                          pred_dims.size()));

S
Siddharth Goyal 已提交
47
    PADDLE_ENFORCE_EQ(pred_dims[1], 1,
48 49 50 51 52
                      platform::errors::InvalidArgument(
                          "The second dimension of Input(input) should be 1, "
                          "as each row of input contains a real value, "
                          "but received second dimension of input (%d) != 1",
                          pred_dims[1]));
S
Siddharth Goyal 已提交
53 54 55 56 57 58 59 60 61

    ctx->SetOutputDim("Loss", {pred_dims[0], 1});
    ctx->ShareLoD("Logits", "Loss");
  }
};

template <typename AttrType>
class HingeLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
62
  void Make() override {
S
Siddharth Goyal 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    AddInput("Logits",
             "The input value (Logits) of Hinge loss op."
             "Logits is a 2-D tensor with shape [batch_size, 1].");
    AddInput("Labels",
             "The target value (Labels) of Hinge loss op."
             "Labels is a 2-D tensor with shape [batch_size, 1].");
    AddOutput("Loss",
              "The output tensor with shape [batch_size, 1] "
              "which represents the hinge loss.");
    AddComment(R"DOC(
HingeLoss Operator.

Let x be a logit (prediction) and y be the actual label. The logit can
take any values from (-inf, inf), but the labels should be either -1 or 1.
Then, the hinge loss is computed as follows:

$$
L_(x, y) = max(1 - y.x, 0) 
$$

Note that the labels passed as input will have values as either 0 or 1.

)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
94 95 96 97 98 99
    OP_INOUT_CHECK(ctx->HasInput("Logits"), "Input", "Logits", "HingeLossGrad");
    OP_INOUT_CHECK(ctx->HasInput("Labels"), "Input", "Labels", "HingeLossGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Loss")), "Input",
                   "Loss@GRAD", "HingeLossGrad");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("Logits")), "Output",
                   "Logits@GRAD", "HingeLossGrad");
S
Siddharth Goyal 已提交
100 101 102 103

    auto pred_dims = ctx->GetInputDim("Logits");
    auto loss_grad_dims = ctx->GetInputDim(framework::GradVarName("Loss"));

104 105 106 107 108 109
    PADDLE_ENFORCE_EQ(loss_grad_dims, pred_dims,
                      platform::errors::InvalidArgument(
                          "The shape of loss gradient should be the same as "
                          "the shape of Input(input), but received the loss "
                          "gradient shape [%s] != input shape [%s]",
                          loss_grad_dims, pred_dims));
S
Siddharth Goyal 已提交
110 111 112 113 114 115

    auto pred_grad_name = framework::GradVarName("Logits");
    ctx->SetOutputDim(pred_grad_name, pred_dims);
  }
};

H
hong 已提交
116 117
template <typename T>
class HingeLossGradOpMaker : public framework::SingleGradOpMaker<T> {
118
 public:
H
hong 已提交
119
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
120 121

 protected:
122
  void Apply(GradOpPtr<T> op) const override {
123
    op->SetType("hinge_loss_grad");
H
hong 已提交
124 125 126 127 128
    op->SetInput("Logits", this->Input("Logits"));
    op->SetInput("Labels", this->Input("Labels"));
    op->SetInput(framework::GradVarName("Loss"), this->OutputGrad("Loss"));
    op->SetOutput(framework::GradVarName("Logits"), this->InputGrad("Logits"));
    op->SetAttrMap(this->Attrs());
129 130 131
  }
};

S
Siddharth Goyal 已提交
132 133 134 135
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
136
REGISTER_OPERATOR(hinge_loss, ops::HingeLossOp, ops::HingeLossOpMaker<float>,
H
hong 已提交
137 138
                  ops::HingeLossGradOpMaker<paddle::framework::OpDesc>,
                  ops::HingeLossGradOpMaker<paddle::imperative::OpBase>);
139
REGISTER_OPERATOR(hinge_loss_grad, ops::HingeLossGradOp);
Q
QI JUN 已提交
140 141 142
REGISTER_OP_CPU_KERNEL(
    hinge_loss,
    ops::HingeLossKernel<paddle::platform::CPUDeviceContext, float>);
S
Siddharth Goyal 已提交
143 144
REGISTER_OP_CPU_KERNEL(
    hinge_loss_grad,
Q
QI JUN 已提交
145
    ops::HingeLossGradKernel<paddle::platform::CPUDeviceContext, float>);
146 147 148 149 150 151 152

REGISTER_OP_CUDA_KERNEL(
    hinge_loss,
    ops::HingeLossKernel<paddle::platform::CUDADeviceContext, float>);
REGISTER_OP_CUDA_KERNEL(
    hinge_loss_grad,
    ops::HingeLossGradKernel<paddle::platform::CUDADeviceContext, float>);