smooth_l1_loss_op.cc 5.1 KB
Newer Older
Y
yangyaming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   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 "paddle/operators/smooth_l1_loss_op.h"

namespace paddle {
namespace operators {

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

 protected:
Q
Qiao Longfei 已提交
25 26 27 28 29 30 31 32
  void InferShape(framework::InferShapeContextBase* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"), "X must be initialized.");
    PADDLE_ENFORCE(ctx->HasInput("Y"), "Y must be initialized.");

    auto x_dims = ctx->GetInputDim("X");
    auto y_dims = ctx->GetInputDim("Y");
    PADDLE_ENFORCE_EQ(x_dims, y_dims, "The shape of X and Y must be the same.");
    PADDLE_ENFORCE_GE(x_dims.size(), 2,
Y
yangyaming 已提交
33
                      "The tensor rank of X must be at least 2.");
Q
Qiao Longfei 已提交
34 35 36 37 38
    if (ctx->HasInput("InsideWeight")) {
      PADDLE_ENFORCE(ctx->HasInput("OutsideWeight"),
                     "If weights are provided, must specify both "
                     "inside and outside weights.");
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("InsideWeight"), x_dims,
Y
yangyaming 已提交
39
                        "The shape of InsideWeight must be same as X.");
Q
Qiao Longfei 已提交
40
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("OutsideWeight"), x_dims,
Y
yangyaming 已提交
41
                        "The shape of OutsideWeight must be same as X.");
Y
yangyaming 已提交
42 43
    }

Q
Qiao Longfei 已提交
44
    ctx->SetOutputDim("Diff", x_dims);
Y
yangyaming 已提交
45
    // loss is a two-rank tensor
Q
Qiao Longfei 已提交
46
    ctx->SetOutputDim("Out", {x_dims[0], 1});
Y
yangyaming 已提交
47 48 49 50 51 52 53 54 55
  }
};

template <typename AttrType>
class SmoothL1LossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  SmoothL1LossOpMaker(framework::OpProto* proto,
                      framework::OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
Y
yangyaming 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    AddInput("X",
             "The input tensor of smooth l1 loss op."
             "The rank should be greater or equal to 2 with shape "
             "[batch_size, value_dim1, value_dim2, ..., value_dimN]");
    AddInput("Y",
             "The target tensor of smooth l1 loss op "
             "with the same shape as X.");
    AddInput("InsideWeight",
             "Optional input tensor of smooth l1 loss op with the same shape "
             "as X. If provided, the result of (X - Y) will be multiplied "
             "by this tensor element by element.");
    AddInput("OutsideWeight",
             "Optinal input of smooth l1 loss op with the same shape as X."
             "If provided, the output smooth l1 loss will be multiplied by "
             "this tensor element by element.");
    AddOutput("Diff", "Intermediate variable to cache InsideWeight*(X-Y).")
Y
yangyaming 已提交
72
        .AsIntermediate();
Y
yangyaming 已提交
73 74 75 76
    AddOutput("Out", "Smooth l1 loss.");
    AddAttr<AttrType>("sigma",
                      "Hyper parameter of smooth l1 loss op."
                      "A float scalar with default value 3.0.")
Y
yangyaming 已提交
77
        .SetDefault(3.0);
Y
yangyaming 已提交
78
    AddComment(R"DOC(
Y
yangyaming 已提交
79 80 81 82
Compute smooth l1 loss for input and target. The operator take the 1st
dimension of input as batch size. For each instance, it will compute
smooth l1 loss element by element first and sum all losses to one value.
So the output shape is [batch_size, 1].
83

Y
yangyaming 已提交
84
The equation is:
Y
yangyaming 已提交
85 86
loss = 0.5 * (sigma * (x-y))^2    if abs(x - y) < 1 / sigma^2
       abs(x - y) - 0.5 / sigma^2 otherwise
87

Y
yangyaming 已提交
88 89 90 91 92 93 94 95 96
)DOC");
  }
};

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

 protected:
Q
Qiao Longfei 已提交
97 98 99
  void InferShape(framework::InferShapeContextBase* ctx) const override {
    auto in_dims = ctx->GetInputDim("X");
    auto out_dims = ctx->GetInputDim(framework::GradVarName("Out"));
Y
yangyaming 已提交
100

101
    PADDLE_ENFORCE_GE(out_dims.size(), 2,
Y
yangyaming 已提交
102
                      "The tensor rank of Input(Out@Grad) should be 2.");
Y
yangyaming 已提交
103
    PADDLE_ENFORCE_EQ(out_dims[0], in_dims[0],
Y
yangyaming 已提交
104 105
                      "The 1st dimension of Input(Out@Grad) must be "
                      "same as input.");
Y
yangyaming 已提交
106
    PADDLE_ENFORCE_EQ(out_dims[1], 1,
Y
yangyaming 已提交
107
                      "The 2nd dimension of Input(Out@Grad) must be 1.");
Y
yangyaming 已提交
108

Q
Qiao Longfei 已提交
109 110 111 112 113 114 115 116
    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 已提交
117 118 119 120 121 122 123 124
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP(smooth_l1_loss, ops::SmoothL1LossOp,
Y
yangyaming 已提交
125 126
            ops::SmoothL1LossOpMaker<float>, smooth_l1_loss_grad,
            ops::SmoothL1LossGradOp);
Y
yangyaming 已提交
127 128 129 130 131
REGISTER_OP_CPU_KERNEL(
    smooth_l1_loss, ops::SmoothL1LossKernel<paddle::platform::CPUPlace, float>);
REGISTER_OP_CPU_KERNEL(
    smooth_l1_loss_grad,
    ops::SmoothL1LossGradKernel<paddle::platform::CPUPlace, float>);