File: collect_and_distribute_fpn_rpn_proposals_op.cc

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (678 lines) | stat: -rw-r--r-- 23,414 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#include "caffe2/operators/collect_and_distribute_fpn_rpn_proposals_op.h"

namespace caffe2 {

namespace utils {

// Compute the area of an array of boxes.
ERArrXXf BoxesArea(const ERArrXXf& boxes, const bool legacy_plus_one) {
  // equivalent to python code
  //   w = (boxes[:, 2] - boxes[:, 0] + 1)
  //   h = (boxes[:, 3] - boxes[:, 1] + 1)
  //   areas = w * h
  //   assert np.all(areas >= 0), 'Negative areas founds'
  const auto w = boxes.col(2) - boxes.col(0) + int(legacy_plus_one);
  const auto h = boxes.col(3) - boxes.col(1) + int(legacy_plus_one);
  const ERArrXXf areas = w * h;
  CAFFE_ENFORCE((areas >= 0).all(), "Negative areas founds: ", boxes);
  // NOLINTNEXTLINE(performance-no-automatic-move)
  return areas;
}

// Determine which FPN level each RoI in a set of RoIs should map to based
// on the heuristic in the FPN paper.
ERArrXXf MapRoIsToFpnLevels(
    Eigen::Ref<const ERArrXXf> rois,
    const float k_min,
    const float k_max,
    const float s0,
    const float lvl0,
    const bool legacy_plus_one) {
  // Compute level ids
  ERArrXXf s = BoxesArea(rois, legacy_plus_one).sqrt();
  // s0 = cfg.FPN.ROI_CANONICAL_SCALE  # default: 224
  // lvl0 = cfg.FPN.ROI_CANONICAL_LEVEL  # default: 4

  // Eqn.(1) in FPN paper
  // equivalent to python code
  //   target_lvls = np.floor(lvl0 + np.log2(s / s0 + 1e-6))
  //   target_lvls = np.clip(target_lvls, k_min, k_max)
  auto target_lvls = (lvl0 + (s / s0 + 1e-6).log() / log(2)).floor();
  auto target_lvls_clipped = target_lvls.min(k_max).max(k_min);
  return target_lvls_clipped;
}

// Sort RoIs from highest to lowest individual RoI score based on
// values from scores array and limit to n results
void SortAndLimitRoIsByScores(
    Eigen::Ref<const EArrXf> scores,
    int n,
    ERArrXXf& rois) {
  CAFFE_ENFORCE(rois.rows() == scores.size(), "RoIs and scores count mismatch");
  // Create index array with 0, 1, ... N
  std::vector<int> idxs(rois.rows());
  std::iota(idxs.begin(), idxs.end(), 0);
  // Reuse a comparator based on scores and store a copy of RoIs that
  // will be truncated and manipulated below
  auto comp = [&scores](int lhs, int rhs) {
    if (scores(lhs) > scores(rhs)) {
      return true;
    }
    if (scores(lhs) < scores(rhs)) {
      return false;
    }
    // To ensure the sort is stable
    return lhs < rhs;
  };
  ERArrXXf rois_copy = rois;
  // Note that people have found nth_element + sort to be much faster
  // than partial_sort so we use it here
  if (n > 0 && n < rois.rows()) {
    std::nth_element(idxs.begin(), idxs.begin() + n, idxs.end(), comp);
    rois.resize(n, rois.cols());
  } else {
    n = rois.rows();
  }
  std::sort(idxs.begin(), idxs.begin() + n, comp);
  // Update RoIs based on new order
  for (int i = 0; i < n; i++) {
    rois.row(i) = rois_copy.row(idxs[i]);
  }
}

// Updates arr to be indices that would sort the array. Implementation of
// https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
void ArgSort(EArrXi& arr) {
  // Create index array with 0, 1, ... N and sort based on array values
  std::vector<int> idxs(arr.size());
  std::iota(std::begin(idxs), std::end(idxs), 0);
  std::sort(idxs.begin(), idxs.end(), [&arr](int lhs, int rhs) {
    return arr(lhs) < arr(rhs);
  });
  // Update array to match new order
  for (int i = 0; i < arr.size(); i++) {
    arr(i) = idxs[i];
  }
}

// Update out_filtered and out_indices with rows from rois where lvl matches
// value in lvls passed in.
void RowsWhereRoILevelEquals(
    Eigen::Ref<const ERArrXXf> rois,
    const ERArrXXf& lvls,
    const int lvl,
    ERArrXXf* out_filtered,
    EArrXi* out_indices) {
  CAFFE_ENFORCE(out_filtered != nullptr, "Output filtered required");
  CAFFE_ENFORCE(out_indices != nullptr, "Output indices required");
  CAFFE_ENFORCE(rois.rows() == lvls.rows(), "RoIs and lvls count mismatch");
  // Calculate how many rows we need
  int filtered_size = (lvls == lvl).rowwise().any().count();
  // Fill in the rows and indices
  out_filtered->resize(filtered_size, rois.cols());
  out_indices->resize(filtered_size);
  for (int i = 0, filtered_idx = 0; i < rois.rows(); i++) {
    auto lvl_row = lvls.row(i);
    if ((lvl_row == lvl).any()) {
      out_filtered->row(filtered_idx) = rois.row(i);
      (*out_indices)(filtered_idx) = i;
      filtered_idx++;
    }
  }
}

} // namespace utils

template <>
bool CollectAndDistributeFpnRpnProposalsOp<CPUContext>::RunOnDevice() {
  int num_rpn_lvls = rpn_max_level_ - rpn_min_level_ + 1;
  CAFFE_ENFORCE_EQ(InputSize(), 2 * num_rpn_lvls);

  int num_roi_lvls = roi_max_level_ - roi_min_level_ + 1;
  CAFFE_ENFORCE_EQ(OutputSize(), num_roi_lvls + 2);

  // Collect rois and scores in Eigen
  // rois are in [[batch_idx, x0, y0, x1, y2], ...] format
  // Combine predictions across all levels and retain the top scoring
  //
  // equivalent to python code
  //   roi_inputs = inputs[:num_rpn_lvls]
  //   score_inputs = inputs[num_rpn_lvls:]
  //   rois = np.concatenate([blob.data for blob in roi_inputs])
  //   scores = np.concatenate([blob.data for blob in score_inputs]).squeeze()
  int proposal_num = 0;
  for (int i = 0; i < num_rpn_lvls; i++) {
    const auto& roi_in = Input(i);
    proposal_num += roi_in.size(0);
  }
  ERArrXXf rois(proposal_num, 5);
  EArrXf scores(proposal_num);
  int len = 0;
  for (int i = 0; i < num_rpn_lvls; i++) {
    const auto& roi_in = Input(i);
    const int n = roi_in.size(0);

    Eigen::Map<const ERArrXXf> roi(roi_in.data<float>(), n, 5);
    rois.block(len, 0, n, 5) = roi;

    const auto& score_in = Input(num_rpn_lvls + i);
    CAFFE_ENFORCE_EQ(score_in.size(0), n);

    // No need to squeeze, since we are reshaping when converting to Eigen
    // https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html
    Eigen::Map<const EArrXf> score(score_in.data<float>(), n);
    scores.segment(len, n) = score;

    len += n;
  }

  // Grab only top rpn_post_nms_topN rois
  // equivalent to python code
  //   inds = np.argsort(-scores)[:rpn_post_nms_topN]
  //   rois = rois[inds, :]
  utils::SortAndLimitRoIsByScores(scores, rpn_post_nms_topN_, rois);

  // Distribute
  // equivalent to python code
  //   lvl_min = cfg.FPN.ROI_MIN_LEVEL
  //   lvl_max = cfg.FPN.ROI_MAX_LEVEL
  //   lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:5], lvl_min, lvl_max)
  const int lvl_min = roi_min_level_;
  const int lvl_max = roi_max_level_;
  const int canon_scale = roi_canonical_scale_;
  const int canon_level = roi_canonical_level_;
  auto rois_block = rois.block(0, 1, rois.rows(), 4);
  auto lvls = utils::MapRoIsToFpnLevels(
      // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions)
      rois_block, lvl_min, lvl_max, canon_scale, canon_level, legacy_plus_one_);

  // equivalent to python code
  //   outputs[0].reshape(rois.shape)
  //   outputs[0].data[...] = rois

  auto* rois_out = Output(0, {rois.rows(), rois.cols()}, at::dtype<float>());
  Eigen::Map<ERArrXXf> rois_out_mat(
      rois_out->template mutable_data<float>(), rois.rows(), rois.cols());
  rois_out_mat = rois;

  // Create new roi blobs for each FPN level
  // (See: modeling.FPN.add_multilevel_roi_blobs which is similar but annoying
  // to generalize to support this particular case.)
  //
  // equivalent to python code
  //   rois_idx_order = np.empty((0, ))
  //   for (output_idx, lvl in enumerate(range(lvl_min, lvl_max + 1)))
  //       idx_lvl = np.where(lvls == lvl)[0]
  //       blob_roi_level = rois[idx_lvl, :]
  //       outputs[output_idx + 1].reshape(blob_roi_level.shape)
  //       outputs[output_idx + 1].data[...] = blob_roi_level
  //       rois_idx_order = np.concatenate((rois_idx_order, idx_lvl))
  //   rois_idx_restore = np.argsort(rois_idx_order)
  //   blob_utils.py_op_copy_blob(rois_idx_restore.astype(np.int32),
  //   outputs[-1])
  EArrXi rois_idx_restore;
  for (int i = 0, lvl = lvl_min; i < num_roi_lvls; i++, lvl++) {
    ERArrXXf blob_roi_level;
    EArrXi idx_lvl;
    utils::RowsWhereRoILevelEquals(rois, lvls, lvl, &blob_roi_level, &idx_lvl);

    // Output blob_roi_level

    auto* roi_out = Output(
        i + 1,
        {blob_roi_level.rows(), blob_roi_level.cols()},
        at::dtype<float>());
    Eigen::Map<ERArrXXf> roi_out_mat(
        roi_out->template mutable_data<float>(),
        blob_roi_level.rows(),
        blob_roi_level.cols());
    roi_out_mat = blob_roi_level;

    // Append indices from idx_lvl to rois_idx_restore
    rois_idx_restore.conservativeResize(
        rois_idx_restore.size() + idx_lvl.size());
    rois_idx_restore.tail(idx_lvl.size()) = idx_lvl;
  }
  utils::ArgSort(rois_idx_restore);

  auto* rois_idx_restore_out =
      Output(OutputSize() - 1, {rois_idx_restore.size()}, at::dtype<int>());
  Eigen::Map<EArrXi> rois_idx_restore_out_mat(
      rois_idx_restore_out->template mutable_data<int>(),
      rois_idx_restore.size());
  rois_idx_restore_out_mat = rois_idx_restore;

  return true;
}

template <>
bool CollectRpnProposalsOp<CPUContext>::RunOnDevice() {
  int num_rpn_lvls = rpn_max_level_ - rpn_min_level_ + 1;
  CAFFE_ENFORCE_EQ(InputSize(), 2 * num_rpn_lvls);

  // Collect rois and scores in Eigen
  // rois are in [[batch_idx, x0, y0, x1, y2], ...] format
  // Combine predictions across all levels and retain the top scoring
  //
  // equivalent to python code
  //   roi_inputs = inputs[:num_rpn_lvls]
  //   score_inputs = inputs[num_rpn_lvls:]
  //   rois = np.concatenate([blob.data for blob in roi_inputs])
  //   scores = np.concatenate([blob.data for blob in score_inputs]).squeeze()
  int proposal_num = 0;
  for (int i = 0; i < num_rpn_lvls; i++) {
    const auto& roi_in = Input(i);
    proposal_num += roi_in.size(0);
  }
  ERArrXXf rois(proposal_num, 5);
  EArrXf scores(proposal_num);
  int len = 0;
  for (int i = 0; i < num_rpn_lvls; i++) {
    const auto& roi_in = Input(i);
    const int n = roi_in.size(0);

    Eigen::Map<const ERArrXXf> roi(roi_in.data<float>(), n, 5);
    rois.block(len, 0, n, 5) = roi;

    const auto& score_in = Input(num_rpn_lvls + i);
    CAFFE_ENFORCE_EQ(score_in.size(0), n);

    // No need to squeeze, since we are reshaping when converting to Eigen
    // https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html
    Eigen::Map<const EArrXf> score(score_in.data<float>(), n);
    scores.segment(len, n) = score;

    len += n;
  }

  // Grab only top rpn_post_nms_topN rois
  // equivalent to python code
  //   inds = np.argsort(-scores)[:rpn_post_nms_topN]
  //   rois = rois[inds, :]
  utils::SortAndLimitRoIsByScores(scores, rpn_post_nms_topN_, rois);

  // equivalent to python code
  //   outputs[0].reshape(rois.shape)
  //   outputs[0].data[...] = rois

  auto* rois_out = Output(0, {rois.rows(), rois.cols()}, at::dtype<float>());
  Eigen::Map<ERArrXXf> rois_out_mat(
      rois_out->template mutable_data<float>(), rois.rows(), rois.cols());
  rois_out_mat = rois;

  return true;
}

template <>
bool DistributeFpnProposalsOp<CPUContext>::RunOnDevice() {
  int num_roi_lvls = roi_max_level_ - roi_min_level_ + 1;
  CAFFE_ENFORCE_EQ(OutputSize(), num_roi_lvls + 1);

  // Load Input(0) to rois
  const auto& rois_in = Input(0);
  const int num_rois = rois_in.size(0);
  const int dim_rois = rois_in.size(1);
  CAFFE_ENFORCE(dim_rois == 4 || dim_rois == 5);
  Eigen::Map<const ERArrXXf> rois_4or5(
      rois_in.data<float>(), num_rois, dim_rois);
  ERArrXXf rois = ERArrXXf::Zero(num_rois, 5);
  rois.rightCols(dim_rois) = rois_4or5;

  // Distribute
  // equivalent to python code
  //   lvl_min = cfg.FPN.ROI_MIN_LEVEL
  //   lvl_max = cfg.FPN.ROI_MAX_LEVEL
  //   lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:5], lvl_min, lvl_max)
  const int lvl_min = roi_min_level_;
  const int lvl_max = roi_max_level_;
  const int canon_scale = roi_canonical_scale_;
  const int canon_level = roi_canonical_level_;
  auto rois_block = rois.block(0, 1, rois.rows(), 4);
  auto lvls = utils::MapRoIsToFpnLevels(
      // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions)
      rois_block, lvl_min, lvl_max, canon_scale, canon_level, legacy_plus_one_);

  // Create new roi blobs for each FPN level
  // (See: modeling.FPN.add_multilevel_roi_blobs which is similar but annoying
  // to generalize to support this particular case.)
  //
  // equivalent to python code
  //   rois_idx_order = np.empty((0, ))
  //   for (output_idx, lvl in enumerate(range(lvl_min, lvl_max + 1)))
  //       idx_lvl = np.where(lvls == lvl)[0]
  //       blob_roi_level = rois[idx_lvl, :]
  //       outputs[output_idx + 1].reshape(blob_roi_level.shape)
  //       outputs[output_idx + 1].data[...] = blob_roi_level
  //       rois_idx_order = np.concatenate((rois_idx_order, idx_lvl))
  //   rois_idx_restore = np.argsort(rois_idx_order)
  //   blob_utils.py_op_copy_blob(rois_idx_restore.astype(np.int32),
  //   outputs[-1])
  EArrXi rois_idx_restore;
  for (int i = 0, lvl = lvl_min; i < num_roi_lvls; i++, lvl++) {
    ERArrXXf blob_roi_level;
    EArrXi idx_lvl;
    utils::RowsWhereRoILevelEquals(rois, lvls, lvl, &blob_roi_level, &idx_lvl);

    // Output blob_roi_level

    auto* roi_out = Output(
        i + 0,
        {blob_roi_level.rows(), blob_roi_level.cols()},
        at::dtype<float>());
    Eigen::Map<ERArrXXf> roi_out_mat(
        roi_out->template mutable_data<float>(),
        blob_roi_level.rows(),
        blob_roi_level.cols());
    roi_out_mat = blob_roi_level;

    // Append indices from idx_lvl to rois_idx_restore
    rois_idx_restore.conservativeResize(
        rois_idx_restore.size() + idx_lvl.size());
    rois_idx_restore.tail(idx_lvl.size()) = idx_lvl;
  }
  utils::ArgSort(rois_idx_restore);

  auto* rois_idx_restore_out =
      Output(OutputSize() - 1, {rois_idx_restore.size()}, at::dtype<int>());
  Eigen::Map<EArrXi> rois_idx_restore_out_mat(
      rois_idx_restore_out->template mutable_data<int>(),
      rois_idx_restore.size());
  rois_idx_restore_out_mat = rois_idx_restore;

  return true;
}

namespace {

REGISTER_CPU_OPERATOR(
    CollectAndDistributeFpnRpnProposals,
    CollectAndDistributeFpnRpnProposalsOp<CPUContext>);
REGISTER_CPU_OPERATOR(CollectRpnProposals, CollectRpnProposalsOp<CPUContext>);
REGISTER_CPU_OPERATOR(
    DistributeFpnProposals,
    DistributeFpnProposalsOp<CPUContext>);

OPERATOR_SCHEMA(CollectAndDistributeFpnRpnProposals)
    .NumInputs(2, INT_MAX)
    .NumOutputs(3, INT_MAX)
    .SetDoc(R"DOC(
Merge RPN proposals generated at multiple FPN levels and then
distribute those proposals to their appropriate FPN levels for Faster RCNN.
An anchor at one FPN level may predict an RoI that will map to another level,
hence the need to redistribute the proposals.

Only inference is supported. To train, please use the original Python
operator in Detectron.

Inputs and outputs are examples only; if min/max levels change,
the number of inputs and outputs, as well as their level numbering,
will change.
)DOC")
    .Arg("roi_canonical_scale", "(int) ROI_CANONICAL_SCALE")
    .Arg("roi_canonical_level", "(int) ROI_CANONICAL_LEVEL")
    .Arg("roi_max_level", "(int) ROI_MAX_LEVEL")
    .Arg("roi_min_level", "(int) ROI_MIN_LEVEL")
    .Arg("rpn_max_level", "(int) RPN_MAX_LEVEL")
    .Arg("rpn_min_level", "(int) RPN_MIN_LEVEL")
    .Arg("rpn_post_nms_topN", "(int) RPN_POST_NMS_TOP_N")
    .Input(
        0,
        "rpn_rois_fpn2",
        "RPN proposals for FPN level 2, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        1,
        "rpn_rois_fpn3",
        "RPN proposals for FPN level 3, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        2,
        "rpn_rois_fpn4",
        "RPN proposals for FPN level 4, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        3,
        "rpn_rois_fpn5",
        "RPN proposals for FPN level 5, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        4,
        "rpn_rois_fpn6",
        "RPN proposals for FPN level 6, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        5,
        "rpn_roi_probs_fpn2",
        "RPN objectness probabilities for FPN level 2. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        6,
        "rpn_roi_probs_fpn3",
        "RPN objectness probabilities for FPN level 3. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        7,
        "rpn_roi_probs_fpn4",
        "RPN objectness probabilities for FPN level 4. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        8,
        "rpn_roi_probs_fpn5",
        "RPN objectness probabilities for FPN level 5. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        9,
        "rpn_roi_probs_fpn6",
        "RPN objectness probabilities for FPN level 6. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Output(
        0,
        "rois",
        "Top proposals limited to rpn_post_nms_topN total, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        1,
        "rois_fpn2",
        "RPN proposals for ROI level 2, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        2,
        "rois_fpn3",
        "RPN proposals for ROI level 3, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        3,
        "rois_fpn4",
        "RPN proposals for ROI level 4, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        4,
        "rois_fpn5",
        "RPN proposals for ROI level 5, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        5,
        "rois_idx_restore",
        "Permutation on the concatenation of all "
        "rois_fpni, i=min...max, such that when applied the RPN RoIs are "
        "restored to their original order in the input blobs.");

SHOULD_NOT_DO_GRADIENT(CollectAndDistributeFpnRpnProposals);

OPERATOR_SCHEMA(CollectRpnProposals)
    .NumInputs(2, INT_MAX)
    .NumOutputs(1)
    .SetDoc(R"DOC(
...
)DOC")
    .Arg("rpn_max_level", "(int) RPN_MAX_LEVEL")
    .Arg("rpn_min_level", "(int) RPN_MIN_LEVEL")
    .Arg("rpn_post_nms_topN", "(int) RPN_POST_NMS_TOP_N")
    .Input(
        0,
        "rpn_rois_fpn2",
        "RPN proposals for FPN level 2, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        1,
        "rpn_rois_fpn3",
        "RPN proposals for FPN level 3, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        2,
        "rpn_rois_fpn4",
        "RPN proposals for FPN level 4, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        3,
        "rpn_rois_fpn5",
        "RPN proposals for FPN level 5, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        4,
        "rpn_rois_fpn6",
        "RPN proposals for FPN level 6, "
        "format (image_index, x1, y1, x2, y2). See rpn_rois "
        "documentation from GenerateProposals.")
    .Input(
        5,
        "rpn_roi_probs_fpn2",
        "RPN objectness probabilities for FPN level 2. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        6,
        "rpn_roi_probs_fpn3",
        "RPN objectness probabilities for FPN level 3. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        7,
        "rpn_roi_probs_fpn4",
        "RPN objectness probabilities for FPN level 4. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        8,
        "rpn_roi_probs_fpn5",
        "RPN objectness probabilities for FPN level 5. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Input(
        9,
        "rpn_roi_probs_fpn6",
        "RPN objectness probabilities for FPN level 6. "
        "See rpn_roi_probs documentation from GenerateProposals.")
    .Output(
        0,
        "rois",
        "Top proposals limited to rpn_post_nms_topN total, "
        "format (image_index, x1, y1, x2, y2)");

SHOULD_NOT_DO_GRADIENT(CollectRpnProposals);

OPERATOR_SCHEMA(DistributeFpnProposals)
    .NumInputs(1)
    .NumOutputs(2, INT_MAX)
    .SetDoc(R"DOC(
...
)DOC")
    .Arg("roi_canonical_scale", "(int) ROI_CANONICAL_SCALE")
    .Arg("roi_canonical_level", "(int) ROI_CANONICAL_LEVEL")
    .Arg("roi_max_level", "(int) ROI_MAX_LEVEL")
    .Arg("roi_min_level", "(int) ROI_MIN_LEVEL")
    .Input(
        0,
        "rois",
        "Top proposals limited to rpn_post_nms_topN total, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        0,
        "rois_fpn2",
        "RPN proposals for ROI level 2, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        1,
        "rois_fpn3",
        "RPN proposals for ROI level 3, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        2,
        "rois_fpn4",
        "RPN proposals for ROI level 4, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        3,
        "rois_fpn5",
        "RPN proposals for ROI level 5, "
        "format (image_index, x1, y1, x2, y2)")
    .Output(
        4,
        "rois_idx_restore",
        "Permutation on the concatenation of all "
        "rois_fpni, i=min...max, such that when applied the RPN RoIs are "
        "restored to their original order in the input blobs.");

SHOULD_NOT_DO_GRADIENT(DistributeFpnProposals);

} // namespace
} // namespace caffe2

// clang-format off
C10_EXPORT_CAFFE2_OP_TO_C10_CPU(
    CollectAndDistributeFpnRpnProposals,
    "_caffe2::CollectAndDistributeFpnRpnProposals("
      "Tensor[] input_list, "
      "int roi_canonical_scale, "
      "int roi_canonical_level, "
      "int roi_max_level, "
      "int roi_min_level, "
      "int rpn_max_level, "
      "int rpn_min_level, "
      "int rpn_post_nms_topN, "
      "bool legacy_plus_one"
    ") -> ("
      "Tensor rois, "
      "Tensor rois_fpn2, "
      "Tensor rois_fpn3, "
      "Tensor rois_fpn4, "
      "Tensor rois_fpn5, "
      "Tensor rois_idx_restore_int32"
    ")",
    caffe2::CollectAndDistributeFpnRpnProposalsOp<caffe2::CPUContext>);

C10_EXPORT_CAFFE2_OP_TO_C10_CPU(
    CollectRpnProposals,
    "_caffe2::CollectRpnProposals("
      "Tensor[] input_list, "
      "int rpn_max_level, "
      "int rpn_min_level, "
      "int rpn_post_nms_topN"
    ") -> ("
      "Tensor rois"
    ")",
    caffe2::CollectRpnProposalsOp<caffe2::CPUContext>);

C10_EXPORT_CAFFE2_OP_TO_C10_CPU(
    DistributeFpnProposals,
    "_caffe2::DistributeFpnProposals("
      "Tensor rois, "
      "int roi_canonical_scale, "
      "int roi_canonical_level, "
      "int roi_max_level, "
      "int roi_min_level, "
      "bool legacy_plus_one"
    ") -> ("
      "Tensor rois_fpn2, "
      "Tensor rois_fpn3, "
      "Tensor rois_fpn4, "
      "Tensor rois_fpn5, "
      "Tensor rois_idx_restore_int32"
    ")",
    caffe2::DistributeFpnProposalsOp<caffe2::CPUContext>);
// clang-format on