smooth_l1_loss_op.cc 8.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
yangyaming 已提交
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
Y
yangyaming 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
yangyaming 已提交
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. */
Y
yangyaming 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/smooth_l1_loss_op.h"
X
xuezhong 已提交
16
#include <memory>
Y
yangyaming 已提交
17 18 19 20 21 22 23 24

namespace paddle {
namespace operators {

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

25
  void InferShape(framework::InferShapeContext* ctx) const override {
26 27
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "SmoothL1Loss");
    OP_INOUT_CHECK(ctx->HasInput("Y"), "Input", "Y", "SmoothL1Loss");
Q
Qiao Longfei 已提交
28 29 30

    auto x_dims = ctx->GetInputDim("X");
    auto y_dims = ctx->GetInputDim("Y");
X
xuezhong 已提交
31 32 33 34 35 36
    bool check = true;
    if ((!ctx->IsRuntime()) &&
        (framework::product(x_dims) <= 0 || framework::product(y_dims) <= 0)) {
      check = false;
    }
    if (check) {
37 38 39 40 41 42
      PADDLE_ENFORCE_EQ(
          x_dims, y_dims,
          platform::errors::InvalidArgument(
              "Input(X) ans Input(Y) of SmoothL1LossOp should "
              "have the same size, but received X dim is %s, Y dim is %s",
              x_dims.to_str(), y_dims.to_str()));
X
xuezhong 已提交
43
    }
Q
Qiao Longfei 已提交
44
    PADDLE_ENFORCE_GE(x_dims.size(), 2,
45 46 47 48
                      platform::errors::InvalidArgument(
                          "The tensor rank of Input(X) of SmoothL1LossOp "
                          "should not be less than 2, but received %d.",
                          x_dims.size()));
Q
Qiao Longfei 已提交
49
    if (ctx->HasInput("InsideWeight")) {
50 51 52 53
      PADDLE_ENFORCE_EQ(ctx->HasInput("OutsideWeight"), true,
                        platform::errors::InvalidArgument(
                            "If weights are provided, must specify both "
                            "inside and outside weights."));
X
xuezhong 已提交
54 55 56 57 58 59 60
      auto dims = ctx->GetInputDim("InsideWeight");
      bool check = true;
      if ((!ctx->IsRuntime()) &&
          (framework::product(dims) <= 0 || framework::product(x_dims) <= 0)) {
        check = false;
      }
      if (check) {
61 62 63 64 65 66
        PADDLE_ENFORCE_EQ(x_dims, dims,
                          platform::errors::InvalidArgument(
                              "Input(X) ans Input(InsideWeight) of "
                              "SmoothL1LossOp should have the same size, but "
                              "received X dim is %s, InsideWeight dim is %s",
                              x_dims.to_str(), dims.to_str()));
X
xuezhong 已提交
67 68 69 70 71 72 73 74 75
      }

      dims = ctx->GetInputDim("OutsideWeight");
      check = true;
      if ((!ctx->IsRuntime()) &&
          (framework::product(dims) <= 0 || framework::product(x_dims) <= 0)) {
        check = false;
      }
      if (check) {
76 77 78 79 80 81
        PADDLE_ENFORCE_EQ(x_dims, dims,
                          platform::errors::InvalidArgument(
                              "Input(X) ans Input(OutsideWeight) of "
                              "SmoothL1LossOp should have the same size, but "
                              "received X dim is %s, OutsideWeight dim is %s",
                              x_dims.to_str(), dims.to_str()));
X
xuezhong 已提交
82
      }
Y
yangyaming 已提交
83 84
    }

Q
Qiao Longfei 已提交
85
    ctx->SetOutputDim("Diff", x_dims);
Y
yangyaming 已提交
86
    // loss is a two-rank tensor
Q
Qiao Longfei 已提交
87
    ctx->SetOutputDim("Out", {x_dims[0], 1});
Y
yangyaming 已提交
88 89 90 91 92
  }
};

class SmoothL1LossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
93
  void Make() override {
Y
yangyaming 已提交
94
    AddInput("X",
Y
yangyaming 已提交
95 96 97
             "(Tensor, default Tensor<float>) A tensor with rank at least 2. "
             "The input value of smooth l1 loss op with shape "
             "[batch_size, dim1, ..., dimN].");
Y
yangyaming 已提交
98
    AddInput("Y",
Y
yangyaming 已提交
99 100
             "(Tensor, default Tensor<float>) A tensor with rank at least 2. "
             "The target value of smooth l1 loss op with same shape as X.");
Y
yangyaming 已提交
101
    AddInput("InsideWeight",
Y
yangyaming 已提交
102 103 104
             "(Tensor, default Tensor<float>) A tensor with rank at least 2. "
             "This input is optional and should have same shape with X. "
             "If provided, the result of (X - Y) will be multiplied "
Y
Yang Yang(Tony) 已提交
105 106
             "by this tensor element by element.")
        .AsDispensable();
Y
yangyaming 已提交
107
    AddInput("OutsideWeight",
Y
yangyaming 已提交
108 109 110 111
             "(Tensor, default Tensor<float>) A tensor with rank at least 2. "
             "This input is optional and should have same shape with X. "
             "If provided, the out smooth l1 loss will be multiplied by this "
             "tensor element by element.")
Y
Yang Yang(Tony) 已提交
112
        .AsDispensable();
Y
yangyaming 已提交
113
    AddOutput("Diff", "Intermediate variable to cache InsideWeight * (X - Y).")
Y
yangyaming 已提交
114
        .AsIntermediate();
Y
yangyaming 已提交
115 116 117
    AddOutput("Out",
              "(Tensor, default Tensor<float>) A tensor with rank be 2. "
              "The output smooth l1 loss with shape [batch_size, 1].");
118 119 120 121
    AddAttr<float>("sigma",
                   "Hyper parameter of smooth l1 loss op."
                   "A float scalar with default value 3.0.")
        .SetDefault(1.0);
Y
yangyaming 已提交
122
    AddComment(R"DOC(
123 124
Smooth L1 Loss Operator.

Y
yangyaming 已提交
125 126
This operator computes the smooth l1 loss for X and Y.
The operator takes the first dimension of X and Y as batch size.
127
For each instance, it computes the smooth l1 loss element by element first
Y
yangyaming 已提交
128
and then sums all the losses. So the shape of Out is [batch_size, 1].
129

Y
yangyaming 已提交
130
The equation is:
Y
yangyaming 已提交
131 132 133 134 135 136 137 138 139 140 141
$$
Out_{\sigma}(X, Y)_i = \begin{cases}
0.5 * (\sigma * (X_i - Y_i)) ^ 2
\quad |X_i - Y_i| \lt \frac{1} {{\sigma} ^ 2} \\
\frac{|X_i - Y_i| - 0.5}{{\sigma}^2},
\quad otherwise
\end{cases}
$$

In the above equation, $Out_{\sigma}(X, Y)_i$, $X_i$ and $Y_i$ represent the ith
element of Out, X and Y.
142

Y
yangyaming 已提交
143 144 145 146 147 148 149 150
)DOC");
  }
};

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

151
  void InferShape(framework::InferShapeContext* ctx) const override {
Q
qingqing01 已提交
152
    auto in_dims = ctx->GetInputDim("Diff");
Q
Qiao Longfei 已提交
153
    auto out_dims = ctx->GetInputDim(framework::GradVarName("Out"));
Y
yangyaming 已提交
154

155 156 157 158 159
    PADDLE_ENFORCE_GE(
        out_dims.size(), 2,
        platform::errors::InvalidArgument(
            "The tensor rank of Input(Out@Grad) should be 2, but received %d.",
            out_dims.size()));
160
    if (ctx->IsRuntime()) {
161 162 163 164 165 166
      PADDLE_ENFORCE_EQ(
          out_dims[0], in_dims[0],
          platform::errors::InvalidArgument(
              "The 1st dimension of Input(Out@Grad) must be "
              "same as input in SmoothL1LossGradOp, but received %d and %d.",
              out_dims[0], in_dims[0]));
167
      PADDLE_ENFORCE_EQ(out_dims[1], 1,
168 169 170 171
                        platform::errors::InvalidArgument(
                            "The 2nd dimension of Input(Out@Grad) must be 1 in "
                            "SmoothL1LossGradOp, but received %d.",
                            out_dims[1]));
172
    }
Y
yangyaming 已提交
173

Q
Qiao Longfei 已提交
174 175 176 177 178 179 180 181
    auto x_grad_name = framework::GradVarName("X");
    auto y_grad_name = framework::GradVarName("Y");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, in_dims);
    }
    if (ctx->HasOutput(y_grad_name)) {
      ctx->SetOutputDim(y_grad_name, in_dims);
    }
Y
yangyaming 已提交
182 183 184
  }
};

H
hong 已提交
185 186
template <typename T>
class SmoothL1LossGradMaker : public framework::SingleGradOpMaker<T> {
Q
qingqing01 已提交
187
 public:
H
hong 已提交
188
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Q
qingqing01 已提交
189 190

 protected:
191
  void Apply(GradOpPtr<T> op) const override {
Q
qingqing01 已提交
192
    op->SetType("smooth_l1_loss_grad");
H
hong 已提交
193 194 195 196
    op->SetInput("InsideWeight", this->Input("InsideWeight"));
    op->SetInput("OutsideWeight", this->Input("OutsideWeight"));
    op->SetInput("Diff", this->Output("Diff"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
Q
qingqing01 已提交
197

H
hong 已提交
198
    op->SetAttrMap(this->Attrs());
Q
qingqing01 已提交
199

H
hong 已提交
200 201
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Y"), this->InputGrad("Y"));
Q
qingqing01 已提交
202 203 204
  }
};

Y
yangyaming 已提交
205 206 207 208
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
209
REGISTER_OPERATOR(smooth_l1_loss, ops::SmoothL1LossOp, ops::SmoothL1LossOpMaker,
H
hong 已提交
210 211
                  ops::SmoothL1LossGradMaker<paddle::framework::OpDesc>,
                  ops::SmoothL1LossGradMaker<paddle::imperative::OpBase>);
212
REGISTER_OPERATOR(smooth_l1_loss_grad, ops::SmoothL1LossGradOp);
Y
yangyaming 已提交
213
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
214 215
    smooth_l1_loss,
    ops::SmoothL1LossKernel<paddle::platform::CPUDeviceContext, float>);
Y
yangyaming 已提交
216 217
REGISTER_OP_CPU_KERNEL(
    smooth_l1_loss_grad,
Q
QI JUN 已提交
218
    ops::SmoothL1LossGradKernel<paddle::platform::CPUDeviceContext, float>);