collect_fpn_proposals_op.cc 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
 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/fluid/operators/detection/collect_fpn_proposals_op.h"
13
#include "paddle/fluid/framework/op_version_registry.h"
14 15 16 17 18 19 20 21 22 23 24

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
class CollectFpnProposalsOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *context) const override {
25 26 27 28 29 30 31 32 33 34 35 36
    PADDLE_ENFORCE_EQ(
        context->HasInputs("MultiLevelRois"), true,
        platform::errors::NotFound("Inputs(MultiLevelRois) of "
                                   "CollectFpnProposalsOp is not found"));
    PADDLE_ENFORCE_EQ(
        context->HasInputs("MultiLevelScores"), true,
        platform::errors::NotFound("Inputs(MultiLevelScores) of "
                                   "CollectFpnProposalsOp is not found"));
    PADDLE_ENFORCE_EQ(
        context->HasOutput("FpnRois"), true,
        platform::errors::NotFound("Outputs(MultiFpnRois) of "
                                   "CollectFpnProposalsOp is not found"));
37 38 39 40 41
    auto roi_dims = context->GetInputsDim("MultiLevelRois");
    auto score_dims = context->GetInputsDim("MultiLevelScores");
    auto post_nms_topN = context->Attrs().Get<int>("post_nms_topN");
    std::vector<int64_t> out_dims;
    for (auto &roi_dim : roi_dims) {
42 43 44 45 46 47
      PADDLE_ENFORCE_EQ(
          roi_dim[1], 4,
          platform::errors::InvalidArgument(
              "Second dimension of Input"
              "(MultiLevelRois) must be 4. But received dimension = %d",
              roi_dim[1]));
48 49 50 51
    }
    for (auto &score_dim : score_dims) {
      PADDLE_ENFORCE_EQ(
          score_dim[1], 1,
52 53 54 55
          platform::errors::InvalidArgument(
              "Second dimension of Input"
              "(MultiLevelScores) must be 1. But received dimension = %d",
              score_dim[1]));
56 57
    }
    context->SetOutputDim("FpnRois", {post_nms_topN, 4});
58 59 60
    if (context->HasOutput("RoisNum")) {
      context->SetOutputDim("RoisNum", {-1});
    }
61 62 63 64
    if (!context->IsRuntime()) {  // Runtime LoD infershape will be computed
      // in Kernel.
      context->ShareLoD("MultiLevelRois", "FpnRois");
    }
65
    if (context->IsRuntime() && !context->HasInputs("MultiLevelRoIsNum")) {
66 67
      auto roi_inputs = context->GetInputVarPtrs("MultiLevelRois");
      auto score_inputs = context->GetInputVarPtrs("MultiLevelScores");
68 69
      for (size_t i = 0; i < roi_inputs.size(); ++i) {
        framework::Variable *roi_var =
70
            BOOST_GET(framework::Variable *, roi_inputs[i]);
71
        framework::Variable *score_var =
72
            BOOST_GET(framework::Variable *, score_inputs[i]);
73 74
        auto &roi_lod = roi_var->Get<LoDTensor>().lod();
        auto &score_lod = score_var->Get<LoDTensor>().lod();
75 76 77 78 79
        PADDLE_ENFORCE_EQ(
            roi_lod, score_lod,
            platform::errors::InvalidArgument(
                "Inputs(MultiLevelRois) and "
                "Inputs(MultiLevelScores) should have same lod."));
80 81 82 83 84 85 86 87
      }
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    auto data_type =
88
        OperatorWithKernel::IndicateVarDataType(ctx, "MultiLevelRois");
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    return framework::OpKernelType(data_type, ctx.GetPlace());
  }
};

class CollectFpnProposalsOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("MultiLevelRois",
             "(LoDTensor) Multiple roi LoDTensors from each level in shape "
             "(N, 4), N is the number of RoIs")
        .AsDuplicable();
    AddInput("MultiLevelScores",
             "(LoDTensor) Multiple score LoDTensors from each level in shape"
             " (N, 1), N is the number of RoIs.")
        .AsDuplicable();
104 105 106 107 108 109 110
    AddInput(
        "MultiLevelRoIsNum",
        "(List of Tensor) The RoIs' number of each image on multiple levels."
        "The number on each level has the shape of (N), N is the number of "
        "images.")
        .AsDuplicable()
        .AsDispensable();
111
    AddOutput("FpnRois", "(LoDTensor) All selected RoIs with highest scores");
112 113
    AddOutput("RoisNum", "(Tensor), Number of RoIs in each images.")
        .AsDispensable();
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    AddAttr<int>("post_nms_topN",
                 "Select post_nms_topN RoIs from"
                 " all images and all fpn layers");
    AddComment(R"DOC(
This operator concats all proposals from different images
 and different FPN levels. Then sort all of those proposals
by objectness confidence. Select the post_nms_topN RoIs in
 total. Finally, re-sort the RoIs in the order of batch index. 
)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
129 130 131 132 133
REGISTER_OPERATOR(
    collect_fpn_proposals, ops::CollectFpnProposalsOp,
    ops::CollectFpnProposalsOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
134 135 136
REGISTER_OP_CPU_KERNEL(collect_fpn_proposals,
                       ops::CollectFpnProposalsOpKernel<float>,
                       ops::CollectFpnProposalsOpKernel<double>);
137 138 139 140 141 142 143 144 145 146 147
REGISTER_OP_VERSION(collect_fpn_proposals)
    .AddCheckpoint(
        R"ROC(
              Upgrade collect_fpn_proposals add a new input 
              [MultiLevelRoIsNum] and add a new output [RoisNum].)ROC",
        paddle::framework::compatible::OpVersionDesc()
            .NewInput("MultiLevelRoIsNum",
                      "The RoIs' number of each image on multiple levels."
                      "The number on each level has the shape of (N), "
                      "N is the number of images.")
            .NewOutput("RoisNum", "The number of RoIs in each image."));