modified_huber_loss_op.cc 6.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/modified_huber_loss_op.h"
16

17
#include <memory>
18 19 20 21 22 23 24 25

namespace paddle {
namespace operators {

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

26
  void InferShape(framework::InferShapeContext* ctx) const override {
27 28
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "ModifiedHuberLoss");
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "ModifiedHuberLoss");
29

Q
Qiao Longfei 已提交
30 31
    auto x_dims = ctx->GetInputDim("X");
    auto y_dims = ctx->GetInputDim("Y");
32

33
    PADDLE_ENFORCE_EQ(
34 35
        x_dims.size(),
        2,
36 37 38
        platform::errors::InvalidArgument("Input(input) rank should be 2, "
                                          "but received input rank(%d) != 2",
                                          x_dims.size()));
39

P
phlrain 已提交
40
    if (ctx->IsRuntime() ||
41
        (phi::product(x_dims) > 0 && phi::product(y_dims) > 0)) {
42
      PADDLE_ENFORCE_EQ(
43 44
          x_dims,
          y_dims,
45 46 47
          platform::errors::InvalidArgument(
              "The Input(input) and Input(label) should have the same "
              "shape, but received input shape [%s] != label shape [%s]",
48 49
              x_dims,
              y_dims));
P
phlrain 已提交
50 51 52
    }

    if (ctx->IsRuntime()) {
53 54
      PADDLE_ENFORCE_EQ(x_dims[1],
                        1,
55 56 57 58
                        platform::errors::InvalidArgument(
                            "The second dimension of Input(input) should be 1, "
                            "but received second dimension of input (%d) != 1",
                            x_dims[1]));
P
phlrain 已提交
59
    }
60

Q
Qiao Longfei 已提交
61 62
    ctx->SetOutputDim("IntermediateVal", x_dims);
    ctx->SetOutputDim("Out", {x_dims[0], 1});
63 64 65 66 67
  }
};

class ModifiedHuberLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
68
  void Make() override {
69
    AddInput("X",
K
kexinzhao 已提交
70
             "The input tensor of modified huber loss op. "
71 72
             "X is 2-D tensor with shape [batch_size, 1].");
    AddInput("Y",
K
kexinzhao 已提交
73 74
             "The target labels of modified huber loss op. "
             "The shape of Y is the same as X. Values of Y must be 0 or 1.");
75
    AddOutput("IntermediateVal",
Y
yangyaming 已提交
76 77 78
              "Variable to save intermediate result which will be reused in "
              "backward processing.")
        .AsIntermediate();
79
    AddOutput("Out", "Classification loss for X.");
Y
yangyaming 已提交
80
    AddComment(R"DOC(
K
kexinzhao 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
Modified Huber Loss Operator.

This operator is used in binary classification problem. The shape of
input X and target Y are both [N, 1] and so is the shape of the output loss.
Since target Y is not differentiable, calculating gradient for Y is illegal.
The formula of modified huber loss is:

$$
L(y, f(x)) = 
\begin{cases}
(\max(0, 1 - yf(x)))^2,  \text{if} \  yf(x) >= -1    \\
             -4yf(x),    \quad \text{otherwise}
\end{cases}
$$

Make sure the values of target label Y are in {0, 1} here. This operator will
97
scale values of Y to {-1, +1} when computing losses and gradients.
K
kexinzhao 已提交
98

Y
yangyaming 已提交
99
)DOC");
100 101 102 103 104 105 106
  }
};

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

107
  void InferShape(framework::InferShapeContext* ctx) const override {
108
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "ModifiedHuberLossGrad");
109 110 111 112 113 114 115
    OP_INOUT_CHECK(ctx->HasInput("IntermediateVal"),
                   "Input",
                   "IntermediateVal",
                   "ModifiedHuberLossGrad");
    OP_INOUT_CHECK(ctx->HasInputs(framework::GradVarName("Out")),
                   "Input",
                   "Out@GRAD",
116
                   "ModifiedHuberLossGrad");
Q
Qiao Longfei 已提交
117

118
    auto y_dims = ctx->GetInputDim("Y");
Q
Qiao Longfei 已提交
119 120
    auto intermediate_dims = ctx->GetInputDim("IntermediateVal");
    auto out_grad_dims = ctx->GetInputDim(framework::GradVarName("Out"));
121

P
phlrain 已提交
122 123
    if (ctx->IsRuntime()) {
      PADDLE_ENFORCE_EQ(
124 125
          intermediate_dims,
          y_dims,
126 127 128 129 130
          platform::errors::InvalidArgument(
              "The shape of Intermediate variable which will be reused in "
              "backward processing should the same as "
              "the shape of Input(label), but received Intermediate variable "
              "shape [%s] != label shape [%s]",
131 132
              intermediate_dims,
              y_dims));
133 134

      PADDLE_ENFORCE_EQ(
135 136
          out_grad_dims,
          y_dims,
137 138 139 140
          platform::errors::InvalidArgument(
              "The shape of output gradient should be the same as "
              "the shape of Input(label), but received the output gradient "
              "shape [%s] != label shape [%s]",
141 142
              out_grad_dims,
              y_dims));
P
phlrain 已提交
143
    }
144

Q
Qiao Longfei 已提交
145
    if (ctx->HasOutput(framework::GradVarName("X"))) {
146
      ctx->SetOutputDim(framework::GradVarName("X"), y_dims);
Q
Qiao Longfei 已提交
147
    }
148 149 150
  }
};

H
hong 已提交
151 152
template <typename T>
class ModifiedHuberLossGradOpMaker : public framework::SingleGradOpMaker<T> {
153
 public:
H
hong 已提交
154
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
155 156

 protected:
157
  void Apply(GradOpPtr<T> op) const override {
158
    op->SetType("modified_huber_loss_grad");
H
hong 已提交
159 160 161 162 163
    op->SetInput("Y", this->Input("Y"));
    op->SetInput("IntermediateVal", this->Output("IntermediateVal"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
164 165 166
  }
};

167 168 169 170
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
171
REGISTER_OPERATOR(
172 173
    modified_huber_loss,
    ops::ModifiedHuberLossOp,
H
hong 已提交
174 175 176
    ops::ModifiedHuberLossOpMaker,
    ops::ModifiedHuberLossGradOpMaker<paddle::framework::OpDesc>,
    ops::ModifiedHuberLossGradOpMaker<paddle::imperative::OpBase>);
177
REGISTER_OPERATOR(modified_huber_loss_grad, ops::ModifiedHuberLossGradOp);
178 179 180

REGISTER_OP_CPU_KERNEL(
    modified_huber_loss,
Q
QI JUN 已提交
181
    ops::ModifiedHuberLossKernel<paddle::platform::CPUDeviceContext, float>);
182 183
REGISTER_OP_CPU_KERNEL(modified_huber_loss_grad,
                       ops::ModifiedHuberLossGradCPUKernel<float>);