Caffe2 - C++ API
A deep learning, cross platform ML framework
roi_align_rotated_op.cc
1 #ifdef _MSC_VER
2 #define _USE_MATH_DEFINES // For M_PI
3 #endif // _MSC_VER
4 #include <cmath>
5 
6 #include "roi_align_rotated_op.h"
7 
8 #include "caffe2/utils/eigen_utils.h"
9 #include "caffe2/utils/math.h"
10 
11 namespace caffe2 {
12 namespace {
13 
14 template <typename T>
15 struct PreCalc {
16  int pos1;
17  int pos2;
18  int pos3;
19  int pos4;
20  T w1;
21  T w2;
22  T w3;
23  T w4;
24 };
25 
26 template <typename T>
27 void pre_calc_for_bilinear_interpolate(
28  const int height,
29  const int width,
30  const int pooled_height,
31  const int pooled_width,
32  const int iy_upper,
33  const int ix_upper,
34  T roi_start_h,
35  T roi_start_w,
36  T bin_size_h,
37  T bin_size_w,
38  int roi_bin_grid_h,
39  int roi_bin_grid_w,
40  T roi_center_h,
41  T roi_center_w,
42  T theta,
43  std::vector<PreCalc<T>>& pre_calc) {
44  int pre_calc_index = 0;
45  T cosTheta = cos(theta);
46  T sinTheta = sin(theta);
47  for (int ph = 0; ph < pooled_height; ph++) {
48  for (int pw = 0; pw < pooled_width; pw++) {
49  for (int iy = 0; iy < iy_upper; iy++) {
50  const T yy = roi_start_h + ph * bin_size_h +
51  static_cast<T>(iy + .5f) * bin_size_h /
52  static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5
53  for (int ix = 0; ix < ix_upper; ix++) {
54  const T xx = roi_start_w + pw * bin_size_w +
55  static_cast<T>(ix + .5f) * bin_size_w /
56  static_cast<T>(roi_bin_grid_w);
57 
58  // Rotate by theta around the center and translate
59  T x = xx * cosTheta + yy * sinTheta + roi_center_w;
60  T y = yy * cosTheta - xx * sinTheta + roi_center_h;
61 
62  // deal with: inverse elements are out of feature map boundary
63  if (y < -1.0 || y > height || x < -1.0 || x > width) {
64  // empty
65  PreCalc<T> pc;
66  pc.pos1 = 0;
67  pc.pos2 = 0;
68  pc.pos3 = 0;
69  pc.pos4 = 0;
70  pc.w1 = 0;
71  pc.w2 = 0;
72  pc.w3 = 0;
73  pc.w4 = 0;
74  pre_calc[pre_calc_index] = pc;
75  pre_calc_index += 1;
76  continue;
77  }
78 
79  if (y <= 0) {
80  y = 0;
81  }
82  if (x <= 0) {
83  x = 0;
84  }
85 
86  int y_low = (int)y;
87  int x_low = (int)x;
88  int y_high;
89  int x_high;
90 
91  if (y_low >= height - 1) {
92  y_high = y_low = height - 1;
93  y = (T)y_low;
94  } else {
95  y_high = y_low + 1;
96  }
97 
98  if (x_low >= width - 1) {
99  x_high = x_low = width - 1;
100  x = (T)x_low;
101  } else {
102  x_high = x_low + 1;
103  }
104 
105  T ly = y - y_low;
106  T lx = x - x_low;
107  T hy = 1. - ly, hx = 1. - lx;
108  T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx;
109 
110  // Save weights and indices
111  PreCalc<T> pc;
112  pc.pos1 = y_low * width + x_low;
113  pc.pos2 = y_low * width + x_high;
114  pc.pos3 = y_high * width + x_low;
115  pc.pos4 = y_high * width + x_high;
116  pc.w1 = w1;
117  pc.w2 = w2;
118  pc.w3 = w3;
119  pc.w4 = w4;
120  pre_calc[pre_calc_index] = pc;
121 
122  pre_calc_index += 1;
123  }
124  }
125  }
126  }
127 }
128 
129 template <typename T>
130 void ROIAlignRotatedForward(
131  const int nthreads,
132  const T* bottom_data,
133  const T& spatial_scale,
134  const int channels,
135  const int height,
136  const int width,
137  const int pooled_height,
138  const int pooled_width,
139  const int sampling_ratio,
140  const T* bottom_rois,
141  int roi_cols,
142  T* top_data,
143  StorageOrder order) {
144  DCHECK(roi_cols == 5 || roi_cols == 6);
145 
146  int n_rois = nthreads / channels / pooled_width / pooled_height;
147 
148 #ifdef _OPENMP
149 #pragma omp parallel for
150 #endif
151  for (int n = 0; n < n_rois; n++) {
152  int index_n = n * channels * pooled_width * pooled_height;
153  // roi could have 5 or 6 columns
154  const T* offset_bottom_rois = bottom_rois + n * roi_cols;
155  int roi_batch_ind = 0;
156  if (roi_cols == 6) {
157  roi_batch_ind = offset_bottom_rois[0];
158  offset_bottom_rois++;
159  }
160 
161  // Do not round
162  T roi_center_w = offset_bottom_rois[0] * spatial_scale;
163  T roi_center_h = offset_bottom_rois[1] * spatial_scale;
164  T roi_width = offset_bottom_rois[2] * spatial_scale;
165  T roi_height = offset_bottom_rois[3] * spatial_scale;
166  T theta = offset_bottom_rois[4] * M_PI / 180.0;
167 
168  // Force malformed ROIs to be 1x1
169  roi_width = std::max(roi_width, (T)1.);
170  roi_height = std::max(roi_height, (T)1.);
171  T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height);
172  T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width);
173 
174  // We use roi_bin_grid to sample the grid and mimic integral
175  int roi_bin_grid_h = (sampling_ratio > 0)
176  ? sampling_ratio
177  : ceil(roi_height / pooled_height); // e.g., = 2
178  int roi_bin_grid_w =
179  (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width);
180 
181  // We do average (integral) pooling inside a bin
182  const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4
183 
184  // We want to precalculate indices and weights shared by all channels,
185  // this is the key point of optimization.
186  std::vector<PreCalc<T>> pre_calc(
187  roi_bin_grid_h * roi_bin_grid_w * pooled_width * pooled_height);
188 
189  // roi_start_h and roi_start_w are computed wrt the center of RoI (x, y).
190  // Appropriate translation needs to be applied after.
191  T roi_start_h = -roi_height / 2.0;
192  T roi_start_w = -roi_width / 2.0;
193  pre_calc_for_bilinear_interpolate(
194  height,
195  width,
196  pooled_height,
197  pooled_width,
198  roi_bin_grid_h,
199  roi_bin_grid_w,
200  roi_start_h,
201  roi_start_w,
202  bin_size_h,
203  bin_size_w,
204  roi_bin_grid_h,
205  roi_bin_grid_w,
206  roi_center_h,
207  roi_center_w,
208  theta,
209  pre_calc);
210 
211  if (order == StorageOrder::NCHW) {
212  for (int c = 0; c < channels; c++) {
213  int index_n_c = index_n + c * pooled_width * pooled_height;
214  const T* offset_bottom_data =
215  bottom_data + (roi_batch_ind * channels + c) * height * width;
216  int pre_calc_index = 0;
217 
218  for (int ph = 0; ph < pooled_height; ph++) {
219  for (int pw = 0; pw < pooled_width; pw++) {
220  int index = index_n_c + ph * pooled_width + pw;
221 
222  T output_val = 0.;
223  for (int iy = 0; iy < roi_bin_grid_h; iy++) {
224  for (int ix = 0; ix < roi_bin_grid_w; ix++) {
225  PreCalc<T> pc = pre_calc[pre_calc_index];
226  output_val += pc.w1 * offset_bottom_data[pc.pos1] +
227  pc.w2 * offset_bottom_data[pc.pos2] +
228  pc.w3 * offset_bottom_data[pc.pos3] +
229  pc.w4 * offset_bottom_data[pc.pos4];
230 
231  pre_calc_index += 1;
232  }
233  }
234  output_val /= count;
235 
236  top_data[index] = output_val;
237  } // for pw
238  } // for ph
239  } // for c
240  } // if nchw
241 
242  if (order == StorageOrder::NHWC) {
243  const T* offset_bottom_data =
244  bottom_data + roi_batch_ind * channels * height * width;
245  int pre_calc_index = 0;
246 
247  for (int ph = 0; ph < pooled_height; ph++) {
248  for (int pw = 0; pw < pooled_width; pw++) {
249  EVecXf output_vals = EVecXf::Zero(channels);
250 
251  for (int iy = 0; iy < roi_bin_grid_h; iy++) {
252  for (int ix = 0; ix < roi_bin_grid_w; ix++) {
253  PreCalc<T> pc = pre_calc[pre_calc_index];
254 
255  ConstEigenVectorMap<T> data_1(
256  offset_bottom_data + channels * pc.pos1, channels);
257  ConstEigenVectorMap<T> data_2(
258  offset_bottom_data + channels * pc.pos2, channels);
259  ConstEigenVectorMap<T> data_3(
260  offset_bottom_data + channels * pc.pos3, channels);
261  ConstEigenVectorMap<T> data_4(
262  offset_bottom_data + channels * pc.pos4, channels);
263 
264  output_vals += pc.w1 * data_1 + pc.w2 * data_2 + pc.w3 * data_3 +
265  pc.w4 * data_4;
266 
267  pre_calc_index += 1;
268  }
269  }
270  output_vals /= count;
271 
272  int index_nhw = index_n + (ph * pooled_width + pw) * channels;
273  std::memcpy(
274  top_data + index_nhw, output_vals.data(), channels * sizeof(T));
275  } // for pw
276  } // for ph
277  } // if nhwc
278  } // for n
279 }
280 
281 } // namespace
282 
283 template <>
284 bool RoIAlignRotatedOp<float, CPUContext>::RunOnDevice() {
285  auto& X = Input(0); // Input data to pool
286  auto& R = Input(1); // RoIs
287 
288  if (R.numel() == 0) {
289  std::vector<int64_t> sizes;
290  // Handle empty rois
291  if (order_ == StorageOrder::NCHW) {
292  sizes = {0, X.dim32(1), pooled_height_, pooled_width_};
293  } else if (order_ == StorageOrder::NHWC) {
294  sizes = {0, pooled_height_, pooled_width_, X.dim32(3)};
295  }
296  // Output tensor is inititalized with proper sizes and data type
297  Output(0, sizes, at::dtype<float>());
298  return true;
299  }
300 
301  CAFFE_ENFORCE_EQ(R.dim(), 2);
302  // Each element of R is [batch_id center_x center_y width height angle].
303  // If R has 6 columns, the first column is the index, otherwise 0.
304  CAFFE_ENFORCE(R.dim32(1) == 5 || R.dim32(1) == 6);
305 
306  assert(sampling_ratio_ >= 0);
307 
308  if (order_ == StorageOrder::NCHW) {
309  auto* Y = Output(
310  0,
311  {R.dim32(0), X.dim32(1), pooled_height_, pooled_width_},
312  at::dtype<float>()); // RoI pooled data
313 
314  int output_size = Y->numel();
315  ROIAlignRotatedForward<float>(
316  output_size,
317  X.data<float>(),
318  spatial_scale_,
319  X.dim32(1),
320  X.dim32(2),
321  X.dim32(3),
322  pooled_height_,
323  pooled_width_,
324  sampling_ratio_,
325  R.data<float>(),
326  R.dim32(1),
327  Y->mutable_data<float>(),
328  order_);
329  } else if (order_ == StorageOrder::NHWC) {
330  auto* Y = Output(
331  0,
332  {R.dim32(0), pooled_height_, pooled_width_, X.dim32(3)},
333  at::dtype<float>()); // RoI pooled data
334  int output_size = Y->numel();
335  ROIAlignRotatedForward<float>(
336  output_size,
337  X.data<float>(),
338  spatial_scale_,
339  X.dim32(3),
340  X.dim32(1),
341  X.dim32(2),
342  pooled_height_,
343  pooled_width_,
344  sampling_ratio_,
345  R.data<float>(),
346  R.dim32(1),
347  Y->mutable_data<float>(),
348  order_);
349  }
350 
351  return true;
352 }
353 
354 REGISTER_CPU_OPERATOR(RoIAlignRotated, RoIAlignRotatedOp<float, CPUContext>);
355 
356 // Input: X, rois; Output: Y
357 OPERATOR_SCHEMA(RoIAlignRotated)
358  .NumInputs(2)
359  .NumOutputs(1)
360  .SetDoc(R"DOC(
361 Similar to RoIAlign but can handle rotated region proposals.
362 Based on https://arxiv.org/abs/1703.01086.
363 )DOC")
364  .Arg(
365  "spatial_scale",
366  "(float) default 1.0; Spatial scale of the input feature map X "
367  "relative to the input image. E.g., 0.0625 if X has a stride of 16 "
368  "w.r.t. the input image.")
369  .Arg("pooled_h", "(int) default 1; Pooled output Y's height.")
370  .Arg("pooled_w", "(int) default 1; Pooled output Y's width.")
371  .Arg(
372  "sampling_ratio",
373  "(int) default -1; number of sampling points in the interpolation grid "
374  "used to compute the output value of each pooled output bin. If > 0, "
375  "then exactly sampling_ratio x sampling_ratio grid points are used. If "
376  "<= 0, then an adaptive number of grid points are used (computed as "
377  "ceil(roi_width / pooled_w), and likewise for height).")
378  .Input(0, "X", "4D feature map input of shape (N, C, H, W).")
379  .Input(
380  1,
381  "RoIs",
382  "2D input of shape (R, 5 or 6) specifying R RoIs "
383  "representing: batch index in [0, N - 1], center_x, center_y, width, "
384  "height, angle. The RoI coordinates are in the coordinate system of "
385  "the input image. `angle` should be specified in degrees and "
386  "represents the RoI rotated counter-clockwise. For inputs "
387  "corresponding to a single image, batch index can be excluded to "
388  "have just 5 columns.")
389  .Output(
390  0,
391  "Y",
392  "4D output of shape (R, C, pooled_h, pooled_w). The r-th batch element "
393  "is a pooled feature map cooresponding to the r-th RoI.");
394 
395 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13