roi_pool_op.cc 8.7 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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/roi_pool_op.h"
S
sneaxiy 已提交
16
#include <memory>
W
wanghaox 已提交
17 18 19 20

namespace paddle {
namespace operators {

W
wanghaox 已提交
21
using Tensor = framework::Tensor;
22
using LoDTensor = framework::LoDTensor;
W
wanghaox 已提交
23

W
wanghaox 已提交
24
class ROIPoolOp : public framework::OperatorWithKernel {
W
wanghaox 已提交
25 26 27 28
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
29 30 31 32 33
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "roi_pool");
    OP_INOUT_CHECK(ctx->HasInput("ROIs"), "Input", "ROIs", "roi_pool");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "roi_pool");
    OP_INOUT_CHECK(ctx->HasOutput("Argmax"), "Output", "Argmax", "roi_pool");

W
wanghaox 已提交
34
    auto input_dims = ctx->GetInputDim("X");
W
wanghaox 已提交
35
    auto rois_dims = ctx->GetInputDim("ROIs");
36

F
FDInSky 已提交
37 38
    if (ctx->HasInput("RoisLod")) {
      auto rois_lod_dims = ctx->GetInputDim("RoisLod");
39 40 41 42
      PADDLE_ENFORCE_EQ(rois_lod_dims.size(), 1,
                        platform::errors::InvalidArgument(
                            "The lod information tensor of ROIs should "
                            "be one-dimensional"));
F
FDInSky 已提交
43
    }
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    PADDLE_ENFORCE_EQ(input_dims.size(), 4,
                      platform::errors::InvalidArgument(
                          "The input data should be a four-dimensional "
                          "tensor with [N,C,H,W], but received input data with "
                          " %d dimension",
                          input_dims.size()));
    PADDLE_ENFORCE_EQ(
        rois_dims.size(), 2,
        platform::errors::InvalidArgument(
            "ROIs should be a 2-D LoDTensor with shape (num_rois, 4)"
            "given as [[x1, y1, x2, y2], ...], but received ROIs is "
            "%d-dimensional LoDTensor",
            rois_dims.size()));
    PADDLE_ENFORCE_EQ(
        rois_dims[1], kROISize,
        platform::errors::InvalidArgument(
            "ROIs should be a 2-D LoDTensor with shape (num_rois, 4)"
            "given as [[x1, y1, x2, y2], ...]. But the second dimension of  "
            "the received data is %d",
            rois_dims[1]));
W
wanghaox 已提交
64 65 66 67 68 69

    int pooled_height = ctx->Attrs().Get<int>("pooled_height");
    int pooled_width = ctx->Attrs().Get<int>("pooled_width");
    float spatial_scale = ctx->Attrs().Get<float>("spatial_scale");

    PADDLE_ENFORCE_GT(pooled_height, 0,
70 71 72 73
                      platform::errors::OutOfRange(
                          "The pooled output height must be greater than 0"
                          "but received height is %d",
                          pooled_height));
W
wanghaox 已提交
74
    PADDLE_ENFORCE_GT(pooled_width, 0,
75 76 77 78
                      platform::errors::OutOfRange(
                          "The pooled output width must be greater than 0"
                          "but received width is %d",
                          pooled_width));
W
wanghaox 已提交
79
    PADDLE_ENFORCE_GT(spatial_scale, 0.0f,
80 81 82 83
                      platform::errors::OutOfRange(
                          "The spatial scale must be greater than 0, "
                          "but received spatial scale is %f",
                          spatial_scale));
W
wanghaox 已提交
84 85 86 87 88 89 90 91 92

    auto out_dims = input_dims;
    out_dims[0] = rois_dims[0];
    out_dims[1] = input_dims[1];
    out_dims[2] = pooled_height;
    out_dims[3] = pooled_width;

    ctx->SetOutputDim("Out", out_dims);
    ctx->SetOutputDim("Argmax", out_dims);
93
  }
W
wanghaox 已提交
94 95

 protected:
96
  framework::OpKernelType GetExpectedKernelType(
W
wanghaox 已提交
97
      const framework::ExecutionContext& ctx) const override {
98 99 100
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
W
wanghaox 已提交
101 102 103
  }
};

W
wanghaox 已提交
104
class ROIPoolGradOp : public framework::OperatorWithKernel {
W
wanghaox 已提交
105 106 107 108
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
109 110 111 112
    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 已提交
113 114 115 116
    ctx->SetOutputsDim(framework::GradVarName("X"), ctx->GetInputsDim("X"));
  }

 protected:
117
  framework::OpKernelType GetExpectedKernelType(
W
wanghaox 已提交
118
      const framework::ExecutionContext& ctx) const override {
119 120 121
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
W
wanghaox 已提交
122 123 124
  }
};

W
wanghaox 已提交
125
class ROIPoolOpMaker : public framework::OpProtoAndCheckerMaker {
W
wanghaox 已提交
126
 public:
Y
Yu Yang 已提交
127
  void Make() override {
W
wanghaox 已提交
128 129
    AddInput("X",
             "(Tensor), "
W
wanghaox 已提交
130 131 132 133 134 135
             "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",
136
             "(LoDTensor), "
W
wanghaox 已提交
137
             "ROIs (Regions of Interest) to pool over. "
138
             "should be a 2-D LoDTensor of shape (num_rois, 4)"
W
wopeizl 已提交
139
             "given as [[x1, y1, x2, y2], ...]. "
W
wanghaox 已提交
140 141 142
             "Where batch_id is the id of the data, "
             "(x1, y1) is the top left coordinates, and "
             "(x2, y2) is the bottom right coordinates.");
F
FDInSky 已提交
143
    AddInput("RoisLod", "(Tensor), The lod info of rois.").AsDispensable();
W
wanghaox 已提交
144 145
    AddOutput("Out",
              "(Tensor), "
W
wanghaox 已提交
146 147
              "The output of ROIPoolOp is a 4-D tensor with shape "
              "(num_rois, channels, pooled_h, pooled_w).");
W
wanghaox 已提交
148 149 150 151
    AddOutput("Argmax",
              "(Tensor), "
              "Argmaxes corresponding to indices in X used "
              "for gradient computation. Only output "
P
peizhilin 已提交
152
              "if arg \"is_test\" is false.")
153
        .AsIntermediate();
W
wanghaox 已提交
154
    AddAttr<float>("spatial_scale",
W
wanghaox 已提交
155 156 157 158
                   "(float, default 1.0), "
                   "Multiplicative spatial scale factor "
                   "to translate ROI coords from their input scale "
                   "to the scale used when pooling.")
159
        .SetDefault(1.0);
W
wanghaox 已提交
160
    AddAttr<int>("pooled_height",
W
wanghaox 已提交
161 162
                 "(int, default 1), "
                 "The pooled output height.")
163
        .SetDefault(1);
W
wanghaox 已提交
164
    AddAttr<int>("pooled_width",
W
wanghaox 已提交
165 166
                 "(int, default 1), "
                 "The pooled output width.")
167
        .SetDefault(1);
W
wanghaox 已提交
168
    AddComment(R"DOC(
Y
yi.wu 已提交
169
**ROIPool Operator**
W
wanghaox 已提交
170

Y
yi.wu 已提交
171 172 173 174 175
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 已提交
176

Y
yi.wu 已提交
177 178
1. Dividing each region proposal into equal-sized sections with
   the pooled_width and pooled_height
Y
update  
yi.wu 已提交
179

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

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

W
wanghaox 已提交
184 185 186 187 188 189
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 已提交
190 191
template <typename T>
class ROIPoolGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
192
 public:
H
hong 已提交
193
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
194 195

 protected:
196
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
197
    op->SetType("roi_pool_grad");
H
hong 已提交
198 199
    op->SetInput("X", this->Input("X"));
    op->SetInput("ROIs", this->Input("ROIs"));
F
FDInSky 已提交
200
    op->SetInput("RoisLod", this->Input("RoisLod"));
H
hong 已提交
201 202 203 204
    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 已提交
205 206 207
  }
};

W
wanghaox 已提交
208 209 210 211
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
212
REGISTER_OPERATOR(roi_pool, ops::ROIPoolOp, ops::ROIPoolOpMaker,
H
hong 已提交
213 214
                  ops::ROIPoolGradMaker<paddle::framework::OpDesc>,
                  ops::ROIPoolGradMaker<paddle::imperative::OpBase>);
215
REGISTER_OPERATOR(roi_pool_grad, ops::ROIPoolGradOp);
W
wanghaox 已提交
216
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
217 218
    roi_pool,
    ops::CPUROIPoolOpKernel<paddle::platform::CPUDeviceContext, float>,
F
FDInSky 已提交
219 220
    ops::CPUROIPoolOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::CPUROIPoolOpKernel<paddle::platform::CPUDeviceContext, int>);
W
wanghaox 已提交
221 222
REGISTER_OP_CPU_KERNEL(
    roi_pool_grad,
Q
QI JUN 已提交
223
    ops::CPUROIPoolGradOpKernel<paddle::platform::CPUDeviceContext, float>,
F
FDInSky 已提交
224 225
    ops::CPUROIPoolGradOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::CPUROIPoolGradOpKernel<paddle::platform::CPUDeviceContext, int>);