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

namespace paddle {
namespace operators {

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

27
  void InferShape(framework::InferShapeContext* ctx) const override {
28 29
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "HuberLoss");
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "HuberLoss");
Y
yangyaming 已提交
30

31 32
    auto x_dims = ctx->GetInputDim("X");
    auto y_dims = ctx->GetInputDim("Y");
33

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

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

51 52 53
    auto out_dims = y_dims;
    ctx->SetOutputDim("Residual", out_dims);
    ctx->SetOutputDim("Out", out_dims);
54
    ctx->ShareLoD("X", "Out");
Y
yangyaming 已提交
55 56 57 58 59 60
  }
};

template <typename AttrType>
class HuberLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
61
  void Make() override {
62 63
    AddInput("X",
             "The input value of huber loss op."
64
             "X is a N-D tensor with shape [N_1, N_2,..., N_n].");
65 66
    AddInput("Y",
             "The target value of huber loss op."
67
             "Y is a N-D tensor with shape [N_1, N_2,..., N_n].");
68
    AddOutput("Residual",
69
              "Intermediate tensor to cache residual value between Y and X."
70
              "The shape is same as Input(X) and will be reused in backward.")
Y
yangyaming 已提交
71
        .AsIntermediate();
72
    AddOutput("Out",
73
              "The output N-D tensor with shape [N_1, N_2,..., N_n] "
K
kexinzhao 已提交
74
              "which represents the huber loss.");
Y
yangyaming 已提交
75 76
    AddAttr<AttrType>("delta", "Hyper parameter in huber loss.");
    AddComment(R"DOC(
K
kexinzhao 已提交
77 78
HuberLoss Operator.

79 80
Huber loss is a loss function used in robust regression. We define X as the
input value and Y as the target value. Huber loss can evaluate the fitness of
81
X to Y. Different from MSE loss, Huber loss is more robust for outliers. If the
82
shape of X and Y are [batch_size, 1]. The equation is:
Y
yangyaming 已提交
83

84
$$
Y
yangyaming 已提交
85
Out_{\delta}(X, Y)_i =
86
\begin{cases}
Y
yangyaming 已提交
87 88 89
0.5 * (Y_i - X_i)^2,
\quad |Y_i - X_i| \leq \delta \\
\delta * (|Y_i - X_i| - 0.5 * \delta),
90
\quad otherwise
91
\end{cases}
92
$$
Y
yangyaming 已提交
93

Y
yangyaming 已提交
94 95 96
In the above equation, $Out_\delta(X, Y)_i$, $X_i$ and $Y_i$ represent the ith
element of Out, X and Y.

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

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

105
  void InferShape(framework::InferShapeContext* ctx) const override {
106 107
    OP_INOUT_CHECK(ctx->HasInputs(framework::GradVarName("Out")), "Input",
                   "Out@GRAD", "HuberLossGrad");
108 109 110 111 112 113

    auto residual_dims = ctx->GetInputDim("Residual");

    auto x_grad_name = framework::GradVarName("X");
    auto y_grad_name = framework::GradVarName("Y");
    if (ctx->HasOutput(x_grad_name)) {
114
      ctx->SetOutputDim(x_grad_name, residual_dims);
115 116
    }
    if (ctx->HasOutput(y_grad_name)) {
117
      ctx->SetOutputDim(y_grad_name, residual_dims);
118
    }
Y
yangyaming 已提交
119 120 121
  }
};

H
hong 已提交
122 123
template <typename T>
class HuberLossGradOpMaker : public framework::SingleGradOpMaker<T> {
124
 public:
H
hong 已提交
125
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
126 127

 protected:
128
  void Apply(GradOpPtr<T> op) const override {
129
    op->SetType("huber_loss_grad");
H
hong 已提交
130 131 132 133 134
    op->SetInput("Residual", this->Output("Residual"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Y"), this->InputGrad("Y"));
    op->SetAttrMap(this->Attrs());
135 136 137
  }
};

Y
yangyaming 已提交
138 139 140 141
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
142
REGISTER_OPERATOR(huber_loss, ops::HuberLossOp, ops::HuberLossOpMaker<float>,
H
hong 已提交
143 144
                  ops::HuberLossGradOpMaker<paddle::framework::OpDesc>,
                  ops::HuberLossGradOpMaker<paddle::imperative::OpBase>);
145
REGISTER_OPERATOR(huber_loss_grad, ops::HuberLossGradOp);
Q
QI JUN 已提交
146
REGISTER_OP_CPU_KERNEL(
147 148
    huber_loss, ops::HuberLossKernel<paddle::platform::CPUDeviceContext, float>,
    ops::HuberLossKernel<paddle::platform::CPUDeviceContext, double>);
Y
yangyaming 已提交
149 150
REGISTER_OP_CPU_KERNEL(
    huber_loss_grad,
151 152
    ops::HuberLossGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::HuberLossGradKernel<paddle::platform::CPUDeviceContext, double>);