prior_box_op.cc 10.4 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. */

B
baiyf 已提交
15
#include "paddle/fluid/operators/detection/prior_box_op.h"
W
wanghaox 已提交
16

17 18 19 20
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif

W
wanghaox 已提交
21 22 23 24 25 26 27 28 29
namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Input"),
W
wanghaox 已提交
30
                   "Input(Input) of PriorBoxOp should not be null.");
W
wanghaox 已提交
31
    PADDLE_ENFORCE(ctx->HasInput("Image"),
W
wanghaox 已提交
32
                   "Input(Image) of PriorBoxOp should not be null.");
W
wanghaox 已提交
33 34 35

    auto image_dims = ctx->GetInputDim("Image");
    auto input_dims = ctx->GetInputDim("Input");
W
wanghaox 已提交
36 37
    PADDLE_ENFORCE(image_dims.size() == 4, "The layout of image is NCHW.");
    PADDLE_ENFORCE(input_dims.size() == 4, "The layout of input is NCHW.");
W
wanghaox 已提交
38 39 40 41 42 43

    PADDLE_ENFORCE_LT(input_dims[2], image_dims[2],
                      "The height of input must smaller than image.");

    PADDLE_ENFORCE_LT(input_dims[3], image_dims[3],
                      "The width of input must smaller than image.");
W
wanghaox 已提交
44

C
chengduoZH 已提交
45 46
    auto min_sizes = ctx->Attrs().Get<std::vector<float>>("min_sizes");
    auto max_sizes = ctx->Attrs().Get<std::vector<float>>("max_sizes");
W
wanghaox 已提交
47
    auto variances = ctx->Attrs().Get<std::vector<float>>("variances");
W
wanghaox 已提交
48
    auto aspect_ratios = ctx->Attrs().Get<std::vector<float>>("aspect_ratios");
W
wanghaox 已提交
49 50
    bool flip = ctx->Attrs().Get<bool>("flip");

W
wanghaox 已提交
51
    std::vector<float> aspect_ratios_vec;
52
    ExpandAspectRatios(aspect_ratios, flip, &aspect_ratios_vec);
W
wanghaox 已提交
53

C
chengduoZH 已提交
54
    size_t num_priors = aspect_ratios_vec.size() * min_sizes.size();
W
wanghaox 已提交
55 56
    if (max_sizes.size() > 0) {
      PADDLE_ENFORCE_EQ(max_sizes.size(), min_sizes.size(),
W
wanghaox 已提交
57
                        "The number of min_size and max_size must be equal.");
C
chengduoZH 已提交
58 59
      num_priors += max_sizes.size();
      for (size_t i = 0; i < max_sizes.size(); ++i) {
W
wanghaox 已提交
60 61 62 63 64 65
        PADDLE_ENFORCE_GT(max_sizes[i], min_sizes[i],
                          "max_size[%d] must be greater than min_size[%d].", i,
                          i);
      }
    }

W
wanghaox 已提交
66 67 68 69 70 71 72
    std::vector<int64_t> dim_vec(4);
    dim_vec[0] = input_dims[2];
    dim_vec[1] = input_dims[3];
    dim_vec[2] = num_priors;
    dim_vec[3] = 4;
    ctx->SetOutputDim("Boxes", framework::make_ddim(dim_vec));
    ctx->SetOutputDim("Variances", framework::make_ddim(dim_vec));
W
wanghaox 已提交
73
  }
74 75 76 77

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    auto input_input_type = ctx.Input<framework::Tensor>("Input")->type();

    framework::LibraryType library_{framework::LibraryType::kPlain};
    framework::DataLayout layout_ = framework::DataLayout::kAnyLayout;
#ifdef PADDLE_WITH_MKLDNN
    if (library_ == framework::LibraryType::kPlain &&
        platform::CanMKLDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kMKLDNN;
      layout_ = framework::DataLayout::kMKLDNN;
      auto input_image_type = ctx.Input<framework::Tensor>("Image")->type();
      int customized_type_value =
          framework::OpKernelType::kDefaultCustomizedTypeValue;
      if (input_image_type == framework::DataTypeTrait<float>::DataType) {
        customized_type_value = kPriorBoxFLOAT;
      } else if (input_image_type ==
                 framework::DataTypeTrait<double>::DataType) {
        customized_type_value = kPriorBoxDOUBLE;
      }
      return framework::OpKernelType(input_input_type, ctx.GetPlace(), layout_,
                                     library_, customized_type_value);
    }
#endif
    return framework::OpKernelType(input_input_type, ctx.GetPlace(), layout_,
                                   library_);
102
  }
W
wanghaox 已提交
103 104 105 106
};

class PriorBoxOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
107
  void Make() override {
W
wanghaox 已提交
108
    AddInput("Input",
W
wanghaox 已提交
109
             "(Tensor, default Tensor<float>), "
W
wanghaox 已提交
110
             "the input feature data of PriorBoxOp, The layout is NCHW.");
W
wanghaox 已提交
111
    AddInput("Image",
W
wanghaox 已提交
112
             "(Tensor, default Tensor<float>), "
W
wanghaox 已提交
113
             "the input image data of PriorBoxOp, The layout is NCHW.");
W
wanghaox 已提交
114
    AddOutput("Boxes",
W
wanghaox 已提交
115
              "(Tensor, default Tensor<float>), the output prior boxes of "
W
wanghaox 已提交
116 117 118
              "PriorBoxOp. The layout is [H, W, num_priors, 4]. "
              "H is the height of input, W is the width of input, num_priors "
              "is the box count of each position.");
W
wanghaox 已提交
119 120
    AddOutput("Variances",
              "(Tensor, default Tensor<float>), the expanded variances of "
W
wanghaox 已提交
121 122 123
              "PriorBoxOp. The layout is [H, W, num_priors, 4]. "
              "H is the height of input, W is the width of input, num_priors "
              "is the box count of each position.");
C
fix bug  
chengduoZH 已提交
124

C
chengduoZH 已提交
125 126 127 128
    AddAttr<std::vector<float>>("min_sizes",
                                "(vector<float>) List of min sizes "
                                "of generated prior boxes.")
        .AddCustomChecker([](const std::vector<float>& min_sizes) {
C
fix bug  
chengduoZH 已提交
129 130 131
          PADDLE_ENFORCE_GT(min_sizes.size(), 0,
                            "Size of min_sizes must be at least 1.");
          for (size_t i = 0; i < min_sizes.size(); ++i) {
C
chengduoZH 已提交
132
            PADDLE_ENFORCE_GT(min_sizes[i], 0.0,
C
fix bug  
chengduoZH 已提交
133 134 135
                              "min_sizes[%d] must be positive.", i);
          }
        });
C
chengduoZH 已提交
136
    AddAttr<std::vector<float>>(
C
fix bug  
chengduoZH 已提交
137
        "max_sizes",
138 139
        "(vector<float>) List of max sizes of generated prior boxes.")
        .SetDefault(std::vector<float>{});
W
wanghaox 已提交
140
    AddAttr<std::vector<float>>(
C
fix bug  
chengduoZH 已提交
141 142 143
        "aspect_ratios",
        "(vector<float>) List of aspect ratios of generated prior boxes.");

W
wanghaox 已提交
144
    AddAttr<std::vector<float>>(
C
fix bug  
chengduoZH 已提交
145 146 147 148 149 150 151 152 153 154 155
        "variances",
        "(vector<float>) List of variances to be encoded in prior boxes.")
        .AddCustomChecker([](const std::vector<float>& variances) {
          PADDLE_ENFORCE_EQ(variances.size(), 4,
                            "Must and only provide 4 variance.");
          for (size_t i = 0; i < variances.size(); ++i) {
            PADDLE_ENFORCE_GT(variances[i], 0.0,
                              "variance[%d] must be greater than 0.", i);
          }
        });
    AddAttr<bool>("flip", "(bool) Whether to flip aspect ratios.")
W
wanghaox 已提交
156
        .SetDefault(true);
C
fix bug  
chengduoZH 已提交
157
    AddAttr<bool>("clip", "(bool) Whether to clip out-of-boundary boxes.")
W
wanghaox 已提交
158
        .SetDefault(true);
C
fix bug  
chengduoZH 已提交
159

W
wanghaox 已提交
160
    AddAttr<float>("step_w",
C
chengduoZH 已提交
161
                   "Prior boxes step across width, 0.0 for auto calculation.")
C
fix bug  
chengduoZH 已提交
162 163
        .SetDefault(0.0)
        .AddCustomChecker([](const float& step_w) {
C
chengduoZH 已提交
164
          PADDLE_ENFORCE_GE(step_w, 0.0, "step_w should be larger than 0.");
C
fix bug  
chengduoZH 已提交
165
        });
W
wanghaox 已提交
166
    AddAttr<float>("step_h",
C
chengduoZH 已提交
167
                   "Prior boxes step across height, 0.0 for auto calculation.")
C
fix bug  
chengduoZH 已提交
168 169
        .SetDefault(0.0)
        .AddCustomChecker([](const float& step_h) {
C
chengduoZH 已提交
170
          PADDLE_ENFORCE_GE(step_h, 0.0, "step_h should be larger than 0.");
C
fix bug  
chengduoZH 已提交
171 172
        });

W
wanghaox 已提交
173 174 175 176
    AddAttr<float>("offset",
                   "(float) "
                   "Prior boxes center offset.")
        .SetDefault(0.5);
177 178 179 180 181 182 183
    AddAttr<bool>(
        "min_max_aspect_ratios_order",
        "(bool) If set True, the output prior box is in order of"
        "[min, max, aspect_ratios], which is consistent with Caffe."
        "Please note, this order affects the weights order of convolution layer"
        "followed by and does not affect the final detection results.")
        .SetDefault(false);
184 185 186 187 188 189 190 191 192
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
        .SetDefault(false);
    AddAttr<bool>("use_quantizer",
                  "(bool, default false) "
                  "Set to true for operators that should be quantized and use "
                  "int8 kernel. "
                  "Only used on CPU.")
        .SetDefault(false);
W
wanghaox 已提交
193 194 195
    AddComment(R"DOC(
Prior box operator
Generate prior boxes for SSD(Single Shot MultiBox Detector) algorithm.
W
wanghaox 已提交
196 197 198 199 200
Each position of the input produce N prior boxes, N is determined by
 the count of min_sizes, max_sizes and aspect_ratios, The size of the
 box is in range(min_size, max_size) interval, which is generated in
 sequence according to the aspect_ratios.

W
wanghaox 已提交
201 202 203 204 205 206 207 208 209 210
Please get more information from the following papers:
https://arxiv.org/abs/1512.02325.
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
211 212 213
REGISTER_OPERATOR(prior_box, ops::PriorBoxOp, ops::PriorBoxOpMaker,
                  paddle::framework::EmptyGradOpMaker);

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
REGISTER_OP_CPU_KERNEL(prior_box, ops::PriorBoxOpKernel<float, float>,
                       ops::PriorBoxOpKernel<double, double>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(prior_box, MKLDNN,
                                    ::paddle::platform::CPUPlace, FF,
                                    ops::kPriorBoxFLOAT,
                                    ops::PriorBoxOpKernel<float, float>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(prior_box, MKLDNN,
                                    ::paddle::platform::CPUPlace, DD,
                                    ops::kPriorBoxDOUBLE,
                                    ops::PriorBoxOpKernel<double, double>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(prior_box, MKLDNN,
                                    ::paddle::platform::CPUPlace, U8F,
                                    ops::kPriorBoxFLOAT,
                                    ops::PriorBoxOpKernel<uint8_t, float>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(prior_box, MKLDNN,
                                    ::paddle::platform::CPUPlace, S8F,
                                    ops::kPriorBoxFLOAT,
                                    ops::PriorBoxOpKernel<int8_t, float>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(prior_box, MKLDNN,
                                    ::paddle::platform::CPUPlace, U8D,
                                    ops::kPriorBoxDOUBLE,
                                    ops::PriorBoxOpKernel<uint8_t, double>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(prior_box, MKLDNN,
                                    ::paddle::platform::CPUPlace, S8D,
                                    ops::kPriorBoxDOUBLE,
                                    ops::PriorBoxOpKernel<int8_t, double>);