target_assign_op.cc 6.7 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
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. */

B
baiyf 已提交
15
#include "paddle/fluid/operators/detection/target_assign_op.h"
16 17 18 19 20 21 22 23 24

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
25 26 27 28 29 30 31
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
                      platform::errors::InvalidArgument(
                          "Input(X) of TargetAssignOp should not be null"));
    PADDLE_ENFORCE_EQ(
        ctx->HasInput("MatchIndices"), true,
        platform::errors::InvalidArgument(
            "Input(MatchIndices) of TargetAssignOp should not be null"));
32

33 34 35 36 37 38 39
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
                      platform::errors::InvalidArgument(
                          "Output(Out) of TargetAssignOp should not be null."));
    PADDLE_ENFORCE_EQ(
        ctx->HasOutput("OutWeight"), true,
        platform::errors::InvalidArgument(
            "Output(OutWeight) of TargetAssignOp should not be null."));
40 41

    auto in_dims = ctx->GetInputDim("X");
42 43
    auto mi_dims = ctx->GetInputDim("MatchIndices");

44 45
    PADDLE_ENFORCE_EQ(
        in_dims.size(), 3,
46 47 48
        platform::errors::InvalidArgument(
            "Expected the rank of Input(X) is 3. But received %d.",
            in_dims.size()));
49
    PADDLE_ENFORCE_EQ(mi_dims.size(), 2,
50 51
                      platform::errors::InvalidArgument(
                          "The rank of Input(MatchIndices) must be 2."));
52 53 54 55

    if (ctx->HasInput("NegIndices")) {
      auto neg_dims = ctx->GetInputDim("NegIndices");
      PADDLE_ENFORCE_EQ(neg_dims.size(), 2,
56 57 58 59 60 61
                        platform::errors::InvalidArgument(
                            "The rank of Input(NegIndices) must be 2."));
      PADDLE_ENFORCE_EQ(
          neg_dims[1], 1,
          platform::errors::InvalidArgument(
              "The last dimension of Out(NegIndices) must be 1."));
62
    }
63 64

    auto n = mi_dims[0];
65 66 67 68
    auto m = mi_dims[1];
    auto k = in_dims[in_dims.size() - 1];
    ctx->SetOutputDim("Out", {n, m, k});
    ctx->SetOutputDim("OutWeight", {n, m, 1});
69 70 71 72 73
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
74 75 76
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
77 78 79 80 81
  }
};

class TargetAssignOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
82
  void Make() override {
83 84 85 86
    AddInput("X",
             "(LoDTensor), This input is a 3D LoDTensor with shape [M, P, K]. "
             "Some elements in X will be assigned to Out based on the "
             "MatchIndices and NegIndices.");
87
    AddInput("MatchIndices",
D
dangqingqing 已提交
88
             "(Tensor, default Tensor<int>), The input matched indices "
89 90
             "with shape [N, P], If MatchIndices[i][j] is -1, the j-th entity "
             "of column is not matched to any entity of row in i-th instance.");
91 92
    AddInput("NegIndices",
             "(LoDTensor, default LoDTensor<int>), The input negative example "
93 94 95 96 97 98
             "indices are an optional input with shape [Neg, 1], where Neg is "
             "the total number of negative example indices.")
        .AsDispensable();
    AddAttr<int>("mismatch_value",
                 "(int, default 0), Fill this value to the "
                 "mismatched location.")
99
        .SetDefault(0);
100 101 102 103 104 105 106
    AddOutput("Out",
              "(Tensor), The output is a 3D Tensor with shape [N, P, K], "
              "N and P is the same as they are in NegIndices, K is the "
              "same as it in input of X. If MatchIndices[i][j] "
              "is -1, the Out[i][j][0 : K] is the mismatch_value.");
    AddOutput("OutWeight",
              "(Tensor), The weight for output with the shape of [N, P, 1]");
107
    AddComment(R"DOC(
108 109 110 111 112 113 114 115 116
This operator can be, for given the target bounding boxes or labels,
to assign classification and regression targets to each prediction as well as
weights to prediction. The weights is used to specify which prediction would
not contribute to training loss.

For each instance, the output `Out` and`OutWeight` are assigned based on
`MatchIndices` and `NegIndices`.
Assumed that the row offset for each instance in `X` is called lod,
this operator assigns classification/regression targets by performing the
D
dangqingqing 已提交
117 118 119 120 121 122
following steps:

1. Assigning all outpts based on `MatchIndices`:

If id = MatchIndices[i][j] > 0,

123 124
    Out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]
    OutWeight[i][j] = 1.
D
dangqingqing 已提交
125 126 127

Otherwise, 

128 129
    Out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}
    OutWeight[i][j] = 0.
D
dangqingqing 已提交
130

131
2. Assigning OutWeight based on `NegIndices` if `NegIndices` is provided:
D
dangqingqing 已提交
132

133 134
Assumed that the row offset for each instance in `NegIndices` is called neg_lod,
for i-th instance and each `id` of NegIndices in this instance:
D
dangqingqing 已提交
135

136 137
    Out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
    OutWeight[i][id] = 1.0
138 139 140 141 142

    )DOC");
  }
};

143 144
template <typename T, typename WT>
struct NegTargetAssignFunctor<platform::CPUDeviceContext, T, WT> {
145
  void operator()(const platform::CPUDeviceContext& ctx, const int* neg_indices,
146 147 148
                  const size_t* lod, const int N, const int M, const int K,
                  const int mismatch_value, T* out, WT* out_wt) {
    for (int i = 0; i < N; ++i) {
D
dangqingqing 已提交
149
      for (size_t j = lod[i]; j < lod[i + 1]; ++j) {
150
        int id = neg_indices[j];
151 152 153 154 155
        int off = (i * M + id) * K;
        for (int k = 0; k < K; ++k) {
          out[off + k] = mismatch_value;
          out_wt[off + k] = static_cast<WT>(1.0);
        }
156 157 158 159 160
      }
    }
  }
};

161 162 163
template struct NegTargetAssignFunctor<platform::CPUDeviceContext, int, float>;
template struct NegTargetAssignFunctor<platform::CPUDeviceContext, float,
                                       float>;
164 165 166 167 168

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
169 170 171 172
REGISTER_OPERATOR(
    target_assign, ops::TargetAssignOp, ops::TargetAssignOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
173 174
REGISTER_OP_CPU_KERNEL(
    target_assign,
175 176
    ops::TargetAssignKernel<paddle::platform::CPUDeviceContext, int, float>,
    ops::TargetAssignKernel<paddle::platform::CPUDeviceContext, float, float>);