roi_pool_op.cc 6.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
W
wanghaox 已提交
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. */

S
sneaxiy 已提交
15
#include <memory>
16
#include "paddle/fluid/framework/infershape_utils.h"
17
#include "paddle/fluid/framework/op_registry.h"
18
#include "paddle/fluid/framework/op_version_registry.h"
19 20
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/ternary.h"
W
wanghaox 已提交
21 22 23 24

namespace paddle {
namespace operators {

W
wanghaox 已提交
25
using Tensor = framework::Tensor;
26
using LoDTensor = framework::LoDTensor;
W
wanghaox 已提交
27

W
wanghaox 已提交
28
class ROIPoolOp : public framework::OperatorWithKernel {
W
wanghaox 已提交
29 30 31 32
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
33
  framework::OpKernelType GetExpectedKernelType(
W
wanghaox 已提交
34
      const framework::ExecutionContext& ctx) const override {
35 36 37
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
W
wanghaox 已提交
38 39 40
  }
};

W
wanghaox 已提交
41
class ROIPoolGradOp : public framework::OperatorWithKernel {
W
wanghaox 已提交
42 43 44 45
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
46 47 48 49
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   framework::GradVarName("Out"), "roi_pool");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output",
                   framework::GradVarName("X"), "roi_pool");
W
wanghaox 已提交
50 51 52 53
    ctx->SetOutputsDim(framework::GradVarName("X"), ctx->GetInputsDim("X"));
  }

 protected:
54
  framework::OpKernelType GetExpectedKernelType(
W
wanghaox 已提交
55
      const framework::ExecutionContext& ctx) const override {
56 57 58
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
W
wanghaox 已提交
59 60 61
  }
};

W
wanghaox 已提交
62
class ROIPoolOpMaker : public framework::OpProtoAndCheckerMaker {
W
wanghaox 已提交
63
 public:
Y
Yu Yang 已提交
64
  void Make() override {
W
wanghaox 已提交
65 66
    AddInput("X",
             "(Tensor), "
W
wanghaox 已提交
67 68 69 70 71 72
             "the input of ROIPoolOp. "
             "The format of input tensor is NCHW. Where N is batch size, "
             "C is the number of input channels, "
             "H is the height of the feature, and "
             "W is the width of the feature.");
    AddInput("ROIs",
73
             "(LoDTensor), "
W
wanghaox 已提交
74
             "ROIs (Regions of Interest) to pool over. "
75
             "should be a 2-D LoDTensor of shape (num_rois, 4)"
W
wopeizl 已提交
76
             "given as [[x1, y1, x2, y2], ...]. "
W
wanghaox 已提交
77 78 79
             "Where batch_id is the id of the data, "
             "(x1, y1) is the top left coordinates, and "
             "(x2, y2) is the bottom right coordinates.");
80 81
    AddInput("RoisNum", "(Tensor), The number of RoIs in each image.")
        .AsDispensable();
W
wanghaox 已提交
82 83
    AddOutput("Out",
              "(Tensor), "
W
wanghaox 已提交
84 85
              "The output of ROIPoolOp is a 4-D tensor with shape "
              "(num_rois, channels, pooled_h, pooled_w).");
W
wanghaox 已提交
86 87 88 89
    AddOutput("Argmax",
              "(Tensor), "
              "Argmaxes corresponding to indices in X used "
              "for gradient computation. Only output "
P
peizhilin 已提交
90
              "if arg \"is_test\" is false.")
91
        .AsIntermediate();
W
wanghaox 已提交
92
    AddAttr<float>("spatial_scale",
W
wanghaox 已提交
93 94 95 96
                   "(float, default 1.0), "
                   "Multiplicative spatial scale factor "
                   "to translate ROI coords from their input scale "
                   "to the scale used when pooling.")
97
        .SetDefault(1.0);
W
wanghaox 已提交
98
    AddAttr<int>("pooled_height",
W
wanghaox 已提交
99 100
                 "(int, default 1), "
                 "The pooled output height.")
101
        .SetDefault(1);
W
wanghaox 已提交
102
    AddAttr<int>("pooled_width",
W
wanghaox 已提交
103 104
                 "(int, default 1), "
                 "The pooled output width.")
105
        .SetDefault(1);
W
wanghaox 已提交
106
    AddComment(R"DOC(
Y
yi.wu 已提交
107
**ROIPool Operator**
W
wanghaox 已提交
108

Y
yi.wu 已提交
109 110 111 112 113
Region of interest pooling (also known as RoI pooling) is to perform
is to perform max pooling on inputs of nonuniform sizes to obtain
fixed-size feature maps (e.g. 7*7).

The operator has three steps:
Y
yi.wu 已提交
114

Y
yi.wu 已提交
115 116
1. Dividing each region proposal into equal-sized sections with
   the pooled_width and pooled_height
Y
update  
yi.wu 已提交
117

Y
yi.wu 已提交
118
2. Finding the largest value in each section
Y
update  
yi.wu 已提交
119

Y
yi.wu 已提交
120 121
3. Copying these max values to the output buffer

W
wanghaox 已提交
122 123 124 125 126 127
ROI Pooling for Faster-RCNN. The link below is a further introduction: 
https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn
    )DOC");
  }
};

H
hong 已提交
128 129
template <typename T>
class ROIPoolGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
130
 public:
H
hong 已提交
131
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
132 133

 protected:
134
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
135
    op->SetType("roi_pool_grad");
H
hong 已提交
136 137
    op->SetInput("X", this->Input("X"));
    op->SetInput("ROIs", this->Input("ROIs"));
138
    op->SetInput("RoisNum", this->Input("RoisNum"));
H
hong 已提交
139 140 141 142
    op->SetInput("Argmax", this->Output("Argmax"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
143 144 145
  }
};

W
wanghaox 已提交
146 147 148 149
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
150 151 152
DECLARE_INFER_SHAPE_FUNCTOR(roi_pool, RoiPoolInferShapeFunctor,
                            PD_INFER_META(phi::RoiPoolInferMeta));

Y
Yang Yang 已提交
153
REGISTER_OPERATOR(roi_pool, ops::ROIPoolOp, ops::ROIPoolOpMaker,
H
hong 已提交
154
                  ops::ROIPoolGradMaker<paddle::framework::OpDesc>,
155 156
                  ops::ROIPoolGradMaker<paddle::imperative::OpBase>,
                  RoiPoolInferShapeFunctor);
157
REGISTER_OPERATOR(roi_pool_grad, ops::ROIPoolGradOp);
158

159
REGISTER_OP_VERSION(roi_pool)
160 161 162 163 164 165 166
    .AddCheckpoint(
        R"ROC(
              Incompatible upgrade of input [RpnRoisLod])ROC",
        paddle::framework::compatible::OpVersionDesc().DeleteInput(
            "RpnRoisLod",
            "Delete RpnRoisLod due to incorrect input name and "
            "it is not used in object detection models yet."))
167 168 169 170 171 172
    .AddCheckpoint(
        R"ROC(
              Upgrade roi_pool add a new input [RoisNum])ROC",
        paddle::framework::compatible::OpVersionDesc().NewInput(
            "RoisNum",
            "The number of RoIs in each image. RoisNum is dispensable."));