detection_postprocess.cc 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include <algorithm>
  13. #include <numeric>
  14. #include <tuple>
  15. #include "flatbuffers/flexbuffers.h"
  16. #include "tensorflow/lite/c/builtin_op_data.h"
  17. #include "tensorflow/lite/c/common.h"
  18. #include "tensorflow/lite/kernels/internal/common.h"
  19. #include "tensorflow/lite/kernels/internal/quantization_util.h"
  20. #include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
  21. #include "tensorflow/lite/kernels/kernel_util.h"
  22. #include "tensorflow/lite/kernels/op_macros.h"
  23. #include "tensorflow/lite/micro/kernels/kernel_util.h"
  24. #include "tensorflow/lite/micro/micro_utils.h"
  25. namespace tflite {
  26. namespace {
  27. /**
  28. * This version of detection_postprocess is specific to TFLite Micro. It
  29. * contains the following differences between the TFLite version:
  30. *
  31. * 1.) Temporaries (temporary tensors) - Micro use instead scratch buffer API.
  32. * 2.) Output dimensions - the TFLite version does not support undefined out
  33. * dimensions. So model must have static out dimensions.
  34. */
  35. // Input tensors
  36. constexpr int kInputTensorBoxEncodings = 0;
  37. constexpr int kInputTensorClassPredictions = 1;
  38. constexpr int kInputTensorAnchors = 2;
  39. // Output tensors
  40. constexpr int kOutputTensorDetectionBoxes = 0;
  41. constexpr int kOutputTensorDetectionClasses = 1;
  42. constexpr int kOutputTensorDetectionScores = 2;
  43. constexpr int kOutputTensorNumDetections = 3;
  44. constexpr int kNumCoordBox = 4;
  45. constexpr int kBatchSize = 1;
  46. constexpr int kNumDetectionsPerClass = 100;
  47. // Object Detection model produces axis-aligned boxes in two formats:
  48. // BoxCorner represents the lower left corner (xmin, ymin) and
  49. // the upper right corner (xmax, ymax).
  50. // CenterSize represents the center (xcenter, ycenter), height and width.
  51. // BoxCornerEncoding and CenterSizeEncoding are related as follows:
  52. // ycenter = y / y_scale * anchor.h + anchor.y;
  53. // xcenter = x / x_scale * anchor.w + anchor.x;
  54. // half_h = 0.5*exp(h/ h_scale)) * anchor.h;
  55. // half_w = 0.5*exp(w / w_scale)) * anchor.w;
  56. // ymin = ycenter - half_h
  57. // ymax = ycenter + half_h
  58. // xmin = xcenter - half_w
  59. // xmax = xcenter + half_w
  60. struct BoxCornerEncoding {
  61. float ymin;
  62. float xmin;
  63. float ymax;
  64. float xmax;
  65. };
  66. struct CenterSizeEncoding {
  67. float y;
  68. float x;
  69. float h;
  70. float w;
  71. };
  72. // We make sure that the memory allocations are contiguous with static_assert.
  73. static_assert(sizeof(BoxCornerEncoding) == sizeof(float) * kNumCoordBox,
  74. "Size of BoxCornerEncoding is 4 float values");
  75. static_assert(sizeof(CenterSizeEncoding) == sizeof(float) * kNumCoordBox,
  76. "Size of CenterSizeEncoding is 4 float values");
  77. struct OpData {
  78. int max_detections;
  79. int max_classes_per_detection; // Fast Non-Max-Suppression
  80. int detections_per_class; // Regular Non-Max-Suppression
  81. float non_max_suppression_score_threshold;
  82. float intersection_over_union_threshold;
  83. int num_classes;
  84. bool use_regular_non_max_suppression;
  85. CenterSizeEncoding scale_values;
  86. // Scratch buffers indexes
  87. int active_candidate_idx;
  88. int decoded_boxes_idx;
  89. int scores_idx;
  90. int score_buffer_idx;
  91. int keep_scores_idx;
  92. int scores_after_regular_non_max_suppression_idx;
  93. int sorted_values_idx;
  94. int keep_indices_idx;
  95. int sorted_indices_idx;
  96. int buffer_idx;
  97. int selected_idx;
  98. // Cached tensor scale and zero point values for quantized operations
  99. TfLiteQuantizationParams input_box_encodings;
  100. TfLiteQuantizationParams input_class_predictions;
  101. TfLiteQuantizationParams input_anchors;
  102. };
  103. void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  104. TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  105. OpData* op_data = nullptr;
  106. const uint8_t* buffer_t = reinterpret_cast<const uint8_t*>(buffer);
  107. const flexbuffers::Map& m = flexbuffers::GetRoot(buffer_t, length).AsMap();
  108. op_data = reinterpret_cast<OpData*>(
  109. context->AllocatePersistentBuffer(context, sizeof(OpData)));
  110. op_data->max_detections = m["max_detections"].AsInt32();
  111. op_data->max_classes_per_detection = m["max_classes_per_detection"].AsInt32();
  112. if (m["detections_per_class"].IsNull())
  113. op_data->detections_per_class = kNumDetectionsPerClass;
  114. else
  115. op_data->detections_per_class = m["detections_per_class"].AsInt32();
  116. if (m["use_regular_nms"].IsNull())
  117. op_data->use_regular_non_max_suppression = false;
  118. else
  119. op_data->use_regular_non_max_suppression = m["use_regular_nms"].AsBool();
  120. op_data->non_max_suppression_score_threshold =
  121. m["nms_score_threshold"].AsFloat();
  122. op_data->intersection_over_union_threshold = m["nms_iou_threshold"].AsFloat();
  123. op_data->num_classes = m["num_classes"].AsInt32();
  124. op_data->scale_values.y = m["y_scale"].AsFloat();
  125. op_data->scale_values.x = m["x_scale"].AsFloat();
  126. op_data->scale_values.h = m["h_scale"].AsFloat();
  127. op_data->scale_values.w = m["w_scale"].AsFloat();
  128. return op_data;
  129. }
  130. TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  131. auto* op_data = static_cast<OpData*>(node->user_data);
  132. MicroContext* micro_context = GetMicroContext(context);
  133. // Inputs: box_encodings, scores, anchors
  134. TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
  135. TfLiteTensor* input_box_encodings =
  136. micro_context->AllocateTempInputTensor(node, kInputTensorBoxEncodings);
  137. TfLiteTensor* input_class_predictions =
  138. micro_context->AllocateTempInputTensor(node,
  139. kInputTensorClassPredictions);
  140. TfLiteTensor* input_anchors =
  141. micro_context->AllocateTempInputTensor(node, kInputTensorAnchors);
  142. TF_LITE_ENSURE_EQ(context, NumDimensions(input_box_encodings), 3);
  143. TF_LITE_ENSURE_EQ(context, NumDimensions(input_class_predictions), 3);
  144. TF_LITE_ENSURE_EQ(context, NumDimensions(input_anchors), 2);
  145. TF_LITE_ENSURE_EQ(context, NumOutputs(node), 4);
  146. const int num_boxes = input_box_encodings->dims->data[1];
  147. const int num_classes = op_data->num_classes;
  148. op_data->input_box_encodings.scale = input_box_encodings->params.scale;
  149. op_data->input_box_encodings.zero_point =
  150. input_box_encodings->params.zero_point;
  151. op_data->input_class_predictions.scale =
  152. input_class_predictions->params.scale;
  153. op_data->input_class_predictions.zero_point =
  154. input_class_predictions->params.zero_point;
  155. op_data->input_anchors.scale = input_anchors->params.scale;
  156. op_data->input_anchors.zero_point = input_anchors->params.zero_point;
  157. // Scratch tensors
  158. context->RequestScratchBufferInArena(context, num_boxes,
  159. &op_data->active_candidate_idx);
  160. context->RequestScratchBufferInArena(context,
  161. num_boxes * kNumCoordBox * sizeof(float),
  162. &op_data->decoded_boxes_idx);
  163. context->RequestScratchBufferInArena(
  164. context,
  165. input_class_predictions->dims->data[1] *
  166. input_class_predictions->dims->data[2] * sizeof(float),
  167. &op_data->scores_idx);
  168. // Additional buffers
  169. context->RequestScratchBufferInArena(context, num_boxes * sizeof(float),
  170. &op_data->score_buffer_idx);
  171. context->RequestScratchBufferInArena(context, num_boxes * sizeof(float),
  172. &op_data->keep_scores_idx);
  173. context->RequestScratchBufferInArena(
  174. context, op_data->max_detections * num_boxes * sizeof(float),
  175. &op_data->scores_after_regular_non_max_suppression_idx);
  176. context->RequestScratchBufferInArena(
  177. context, op_data->max_detections * num_boxes * sizeof(float),
  178. &op_data->sorted_values_idx);
  179. context->RequestScratchBufferInArena(context, num_boxes * sizeof(int),
  180. &op_data->keep_indices_idx);
  181. context->RequestScratchBufferInArena(
  182. context, op_data->max_detections * num_boxes * sizeof(int),
  183. &op_data->sorted_indices_idx);
  184. int buffer_size = std::max(num_classes, op_data->max_detections);
  185. context->RequestScratchBufferInArena(
  186. context, buffer_size * num_boxes * sizeof(int), &op_data->buffer_idx);
  187. buffer_size = std::min(num_boxes, op_data->max_detections);
  188. context->RequestScratchBufferInArena(
  189. context, buffer_size * num_boxes * sizeof(int), &op_data->selected_idx);
  190. // Outputs: detection_boxes, detection_scores, detection_classes,
  191. // num_detections
  192. TF_LITE_ENSURE_EQ(context, NumOutputs(node), 4);
  193. micro_context->DeallocateTempTfLiteTensor(input_box_encodings);
  194. micro_context->DeallocateTempTfLiteTensor(input_class_predictions);
  195. micro_context->DeallocateTempTfLiteTensor(input_anchors);
  196. return kTfLiteOk;
  197. }
  198. class Dequantizer {
  199. public:
  200. Dequantizer(int zero_point, float scale)
  201. : zero_point_(zero_point), scale_(scale) {}
  202. float operator()(uint8_t x) {
  203. return (static_cast<float>(x) - zero_point_) * scale_;
  204. }
  205. private:
  206. int zero_point_;
  207. float scale_;
  208. };
  209. template <class T>
  210. T ReInterpretTensor(const TfLiteEvalTensor* tensor) {
  211. const float* tensor_base = tflite::micro::GetTensorData<float>(tensor);
  212. return reinterpret_cast<T>(tensor_base);
  213. }
  214. template <class T>
  215. T ReInterpretTensor(TfLiteEvalTensor* tensor) {
  216. float* tensor_base = tflite::micro::GetTensorData<float>(tensor);
  217. return reinterpret_cast<T>(tensor_base);
  218. }
  219. TfLiteStatus DecodeCenterSizeBoxes(TfLiteContext* context, TfLiteNode* node,
  220. OpData* op_data) {
  221. // Parse input tensor boxencodings
  222. const TfLiteEvalTensor* input_box_encodings =
  223. tflite::micro::GetEvalInput(context, node, kInputTensorBoxEncodings);
  224. TF_LITE_ENSURE_EQ(context, input_box_encodings->dims->data[0], kBatchSize);
  225. const int num_boxes = input_box_encodings->dims->data[1];
  226. TF_LITE_ENSURE(context, input_box_encodings->dims->data[2] >= kNumCoordBox);
  227. const TfLiteEvalTensor* input_anchors =
  228. tflite::micro::GetEvalInput(context, node, kInputTensorAnchors);
  229. // Decode the boxes to get (ymin, xmin, ymax, xmax) based on the anchors
  230. CenterSizeEncoding box_centersize;
  231. CenterSizeEncoding scale_values = op_data->scale_values;
  232. CenterSizeEncoding anchor;
  233. for (int idx = 0; idx < num_boxes; ++idx) {
  234. switch (input_box_encodings->type) {
  235. // Float
  236. case kTfLiteFloat32: {
  237. // Please see DequantizeBoxEncodings function for the support detail.
  238. const int box_encoding_idx = idx * input_box_encodings->dims->data[2];
  239. const float* boxes = &(tflite::micro::GetTensorData<float>(
  240. input_box_encodings)[box_encoding_idx]);
  241. box_centersize = *reinterpret_cast<const CenterSizeEncoding*>(boxes);
  242. anchor =
  243. ReInterpretTensor<const CenterSizeEncoding*>(input_anchors)[idx];
  244. break;
  245. }
  246. default:
  247. // Unsupported type.
  248. return kTfLiteError;
  249. }
  250. float ycenter = static_cast<float>(static_cast<double>(box_centersize.y) /
  251. static_cast<double>(scale_values.y) *
  252. static_cast<double>(anchor.h) +
  253. static_cast<double>(anchor.y));
  254. float xcenter = static_cast<float>(static_cast<double>(box_centersize.x) /
  255. static_cast<double>(scale_values.x) *
  256. static_cast<double>(anchor.w) +
  257. static_cast<double>(anchor.x));
  258. float half_h =
  259. static_cast<float>(0.5 *
  260. (std::exp(static_cast<double>(box_centersize.h) /
  261. static_cast<double>(scale_values.h))) *
  262. static_cast<double>(anchor.h));
  263. float half_w =
  264. static_cast<float>(0.5 *
  265. (std::exp(static_cast<double>(box_centersize.w) /
  266. static_cast<double>(scale_values.w))) *
  267. static_cast<double>(anchor.w));
  268. float* decoded_boxes = reinterpret_cast<float*>(
  269. context->GetScratchBuffer(context, op_data->decoded_boxes_idx));
  270. auto& box = reinterpret_cast<BoxCornerEncoding*>(decoded_boxes)[idx];
  271. box.ymin = ycenter - half_h;
  272. box.xmin = xcenter - half_w;
  273. box.ymax = ycenter + half_h;
  274. box.xmax = xcenter + half_w;
  275. }
  276. return kTfLiteOk;
  277. }
  278. void DecreasingPartialArgSort(const float* values, int num_values,
  279. int num_to_sort, int* indices) {
  280. std::iota(indices, indices + num_values, 0);
  281. std::partial_sort(indices, indices + num_to_sort, indices + num_values,
  282. [&values](const int i, const int j) {
  283. return std::tie(values[i], j) > std::tie(values[j], i);
  284. });
  285. }
  286. template <typename Compare>
  287. void InsertionSort(int* start, int* end, Compare compare) {
  288. for (int* i = start; i != end; ++i) {
  289. std::rotate(std::upper_bound(start, i, *i, compare), i, i + 1);
  290. }
  291. }
  292. template <typename Compare>
  293. void TopDownMerge(int* values, int* scratch, const int half_num_values,
  294. int num_values, Compare compare) {
  295. int left = 0;
  296. int right = half_num_values;
  297. for (int i = 0; i < num_values; i++) {
  298. if (left >= half_num_values ||
  299. (right < num_values && compare(values[right], values[left]))) {
  300. scratch[i] = values[right++];
  301. } else {
  302. scratch[i] = values[left++];
  303. }
  304. }
  305. memcpy(values, scratch, num_values * sizeof(int));
  306. }
  307. template <typename Compare>
  308. void MergeSort(int* values, int* scratch, const int num_values,
  309. Compare compare) {
  310. constexpr int threshold = 20;
  311. if (num_values < threshold) {
  312. InsertionSort(values, values + num_values, compare);
  313. return;
  314. }
  315. const int half_num_values = num_values / 2;
  316. MergeSort(values, scratch, half_num_values, compare);
  317. MergeSort(values + half_num_values, scratch, num_values - half_num_values,
  318. compare);
  319. TopDownMerge(values, scratch, half_num_values, num_values, compare);
  320. }
  321. void DecreasingArgSort(const float* values, int num_values, int* indices,
  322. int* scratch) {
  323. std::iota(indices, indices + num_values, 0);
  324. MergeSort(indices, scratch, num_values, [&values](const int i, const int j) {
  325. return values[i] > values[j];
  326. });
  327. }
  328. int SelectDetectionsAboveScoreThreshold(const float* values, int size,
  329. const float threshold,
  330. float* keep_values, int* keep_indices) {
  331. int counter = 0;
  332. for (int i = 0; i < size; i++) {
  333. if (values[i] >= threshold) {
  334. keep_values[counter] = values[i];
  335. keep_indices[counter] = i;
  336. counter++;
  337. }
  338. }
  339. return counter;
  340. }
  341. bool ValidateBoxes(const float* decoded_boxes, const int num_boxes) {
  342. for (int i = 0; i < num_boxes; ++i) {
  343. // ymax>=ymin, xmax>=xmin
  344. auto& box = reinterpret_cast<const BoxCornerEncoding*>(decoded_boxes)[i];
  345. if (box.ymin >= box.ymax || box.xmin >= box.xmax) {
  346. return false;
  347. }
  348. }
  349. return true;
  350. }
  351. float ComputeIntersectionOverUnion(const float* decoded_boxes, const int i,
  352. const int j) {
  353. auto& box_i = reinterpret_cast<const BoxCornerEncoding*>(decoded_boxes)[i];
  354. auto& box_j = reinterpret_cast<const BoxCornerEncoding*>(decoded_boxes)[j];
  355. const float area_i = (box_i.ymax - box_i.ymin) * (box_i.xmax - box_i.xmin);
  356. const float area_j = (box_j.ymax - box_j.ymin) * (box_j.xmax - box_j.xmin);
  357. if (area_i <= 0 || area_j <= 0) return 0.0;
  358. const float intersection_ymin = std::max<float>(box_i.ymin, box_j.ymin);
  359. const float intersection_xmin = std::max<float>(box_i.xmin, box_j.xmin);
  360. const float intersection_ymax = std::min<float>(box_i.ymax, box_j.ymax);
  361. const float intersection_xmax = std::min<float>(box_i.xmax, box_j.xmax);
  362. const float intersection_area =
  363. std::max<float>(intersection_ymax - intersection_ymin, 0.0) *
  364. std::max<float>(intersection_xmax - intersection_xmin, 0.0);
  365. return intersection_area / (area_i + area_j - intersection_area);
  366. }
  367. // NonMaxSuppressionSingleClass() prunes out the box locations with high overlap
  368. // before selecting the highest scoring boxes (max_detections in number)
  369. // It assumes all boxes are good in beginning and sorts based on the scores.
  370. // If lower-scoring box has too much overlap with a higher-scoring box,
  371. // we get rid of the lower-scoring box.
  372. // Complexity is O(N^2) pairwise comparison between boxes
  373. TfLiteStatus NonMaxSuppressionSingleClassHelper(
  374. TfLiteContext* context, TfLiteNode* node, OpData* op_data,
  375. const float* scores, int* selected, int* selected_size,
  376. int max_detections) {
  377. const TfLiteEvalTensor* input_box_encodings =
  378. tflite::micro::GetEvalInput(context, node, kInputTensorBoxEncodings);
  379. const int num_boxes = input_box_encodings->dims->data[1];
  380. const float non_max_suppression_score_threshold =
  381. op_data->non_max_suppression_score_threshold;
  382. const float intersection_over_union_threshold =
  383. op_data->intersection_over_union_threshold;
  384. // Maximum detections should be positive.
  385. TF_LITE_ENSURE(context, (max_detections >= 0));
  386. // intersection_over_union_threshold should be positive
  387. // and should be less than 1.
  388. TF_LITE_ENSURE(context, (intersection_over_union_threshold > 0.0f) &&
  389. (intersection_over_union_threshold <= 1.0f));
  390. // Validate boxes
  391. float* decoded_boxes = reinterpret_cast<float*>(
  392. context->GetScratchBuffer(context, op_data->decoded_boxes_idx));
  393. TF_LITE_ENSURE(context, ValidateBoxes(decoded_boxes, num_boxes));
  394. // threshold scores
  395. int* keep_indices = reinterpret_cast<int*>(
  396. context->GetScratchBuffer(context, op_data->keep_indices_idx));
  397. float* keep_scores = reinterpret_cast<float*>(
  398. context->GetScratchBuffer(context, op_data->keep_scores_idx));
  399. int num_scores_kept = SelectDetectionsAboveScoreThreshold(
  400. scores, num_boxes, non_max_suppression_score_threshold, keep_scores,
  401. keep_indices);
  402. int* sorted_indices = reinterpret_cast<int*>(
  403. context->GetScratchBuffer(context, op_data->sorted_indices_idx));
  404. // Reusing keep_indices for scratch buffer and write back its values
  405. // after the sorting is done.
  406. DecreasingArgSort(keep_scores, num_scores_kept, sorted_indices, keep_indices);
  407. int counter = 0;
  408. for (int i = 0; i < num_boxes; i++) {
  409. if (scores[i] >= non_max_suppression_score_threshold) {
  410. keep_indices[counter] = i;
  411. counter++;
  412. }
  413. }
  414. const int num_boxes_kept = num_scores_kept;
  415. const int output_size = std::min(num_boxes_kept, max_detections);
  416. *selected_size = 0;
  417. int num_active_candidate = num_boxes_kept;
  418. uint8_t* active_box_candidate = reinterpret_cast<uint8_t*>(
  419. context->GetScratchBuffer(context, op_data->active_candidate_idx));
  420. for (int row = 0; row < num_boxes_kept; row++) {
  421. active_box_candidate[row] = 1;
  422. }
  423. for (int i = 0; i < num_boxes_kept; ++i) {
  424. if (num_active_candidate == 0 || *selected_size >= output_size) break;
  425. if (active_box_candidate[i] == 1) {
  426. selected[(*selected_size)++] = keep_indices[sorted_indices[i]];
  427. active_box_candidate[i] = 0;
  428. num_active_candidate--;
  429. } else {
  430. continue;
  431. }
  432. for (int j = i + 1; j < num_boxes_kept; ++j) {
  433. if (active_box_candidate[j] == 1) {
  434. float intersection_over_union = ComputeIntersectionOverUnion(
  435. decoded_boxes, keep_indices[sorted_indices[i]],
  436. keep_indices[sorted_indices[j]]);
  437. if (intersection_over_union > intersection_over_union_threshold) {
  438. active_box_candidate[j] = 0;
  439. num_active_candidate--;
  440. }
  441. }
  442. }
  443. }
  444. return kTfLiteOk;
  445. }
  446. // This function implements a regular version of Non Maximal Suppression (NMS)
  447. // for multiple classes where
  448. // 1) we do NMS separately for each class across all anchors and
  449. // 2) keep only the highest anchor scores across all classes
  450. // 3) The worst runtime of the regular NMS is O(K*N^2)
  451. // where N is the number of anchors and K the number of
  452. // classes.
  453. TfLiteStatus NonMaxSuppressionMultiClassRegularHelper(TfLiteContext* context,
  454. TfLiteNode* node,
  455. OpData* op_data,
  456. const float* scores) {
  457. const TfLiteEvalTensor* input_box_encodings =
  458. tflite::micro::GetEvalInput(context, node, kInputTensorBoxEncodings);
  459. const TfLiteEvalTensor* input_class_predictions =
  460. tflite::micro::GetEvalInput(context, node, kInputTensorClassPredictions);
  461. TfLiteEvalTensor* detection_boxes =
  462. tflite::micro::GetEvalOutput(context, node, kOutputTensorDetectionBoxes);
  463. TfLiteEvalTensor* detection_classes = tflite::micro::GetEvalOutput(
  464. context, node, kOutputTensorDetectionClasses);
  465. TfLiteEvalTensor* detection_scores =
  466. tflite::micro::GetEvalOutput(context, node, kOutputTensorDetectionScores);
  467. TfLiteEvalTensor* num_detections =
  468. tflite::micro::GetEvalOutput(context, node, kOutputTensorNumDetections);
  469. const int num_boxes = input_box_encodings->dims->data[1];
  470. const int num_classes = op_data->num_classes;
  471. const int num_detections_per_class = op_data->detections_per_class;
  472. const int max_detections = op_data->max_detections;
  473. const int num_classes_with_background =
  474. input_class_predictions->dims->data[2];
  475. // The row index offset is 1 if background class is included and 0 otherwise.
  476. int label_offset = num_classes_with_background - num_classes;
  477. TF_LITE_ENSURE(context, num_detections_per_class > 0);
  478. // For each class, perform non-max suppression.
  479. float* class_scores = reinterpret_cast<float*>(
  480. context->GetScratchBuffer(context, op_data->score_buffer_idx));
  481. int* box_indices_after_regular_non_max_suppression = reinterpret_cast<int*>(
  482. context->GetScratchBuffer(context, op_data->buffer_idx));
  483. float* scores_after_regular_non_max_suppression =
  484. reinterpret_cast<float*>(context->GetScratchBuffer(
  485. context, op_data->scores_after_regular_non_max_suppression_idx));
  486. int size_of_sorted_indices = 0;
  487. int* sorted_indices = reinterpret_cast<int*>(
  488. context->GetScratchBuffer(context, op_data->sorted_indices_idx));
  489. float* sorted_values = reinterpret_cast<float*>(
  490. context->GetScratchBuffer(context, op_data->sorted_values_idx));
  491. for (int col = 0; col < num_classes; col++) {
  492. for (int row = 0; row < num_boxes; row++) {
  493. // Get scores of boxes corresponding to all anchors for single class
  494. class_scores[row] =
  495. *(scores + row * num_classes_with_background + col + label_offset);
  496. }
  497. // Perform non-maximal suppression on single class
  498. int selected_size = 0;
  499. int* selected = reinterpret_cast<int*>(
  500. context->GetScratchBuffer(context, op_data->selected_idx));
  501. TF_LITE_ENSURE_STATUS(NonMaxSuppressionSingleClassHelper(
  502. context, node, op_data, class_scores, selected, &selected_size,
  503. num_detections_per_class));
  504. // Add selected indices from non-max suppression of boxes in this class
  505. int output_index = size_of_sorted_indices;
  506. for (int i = 0; i < selected_size; i++) {
  507. int selected_index = selected[i];
  508. box_indices_after_regular_non_max_suppression[output_index] =
  509. (selected_index * num_classes_with_background + col + label_offset);
  510. scores_after_regular_non_max_suppression[output_index] =
  511. class_scores[selected_index];
  512. output_index++;
  513. }
  514. // Sort the max scores among the selected indices
  515. // Get the indices for top scores
  516. int num_indices_to_sort = std::min(output_index, max_detections);
  517. DecreasingPartialArgSort(scores_after_regular_non_max_suppression,
  518. output_index, num_indices_to_sort, sorted_indices);
  519. // Copy values to temporary vectors
  520. for (int row = 0; row < num_indices_to_sort; row++) {
  521. int temp = sorted_indices[row];
  522. sorted_indices[row] = box_indices_after_regular_non_max_suppression[temp];
  523. sorted_values[row] = scores_after_regular_non_max_suppression[temp];
  524. }
  525. // Copy scores and indices from temporary vectors
  526. for (int row = 0; row < num_indices_to_sort; row++) {
  527. box_indices_after_regular_non_max_suppression[row] = sorted_indices[row];
  528. scores_after_regular_non_max_suppression[row] = sorted_values[row];
  529. }
  530. size_of_sorted_indices = num_indices_to_sort;
  531. }
  532. // Allocate output tensors
  533. for (int output_box_index = 0; output_box_index < max_detections;
  534. output_box_index++) {
  535. if (output_box_index < size_of_sorted_indices) {
  536. const int anchor_index = floor(
  537. box_indices_after_regular_non_max_suppression[output_box_index] /
  538. num_classes_with_background);
  539. const int class_index =
  540. box_indices_after_regular_non_max_suppression[output_box_index] -
  541. anchor_index * num_classes_with_background - label_offset;
  542. const float selected_score =
  543. scores_after_regular_non_max_suppression[output_box_index];
  544. // detection_boxes
  545. float* decoded_boxes = reinterpret_cast<float*>(
  546. context->GetScratchBuffer(context, op_data->decoded_boxes_idx));
  547. ReInterpretTensor<BoxCornerEncoding*>(detection_boxes)[output_box_index] =
  548. reinterpret_cast<BoxCornerEncoding*>(decoded_boxes)[anchor_index];
  549. // detection_classes
  550. tflite::micro::GetTensorData<float>(detection_classes)[output_box_index] =
  551. class_index;
  552. // detection_scores
  553. tflite::micro::GetTensorData<float>(detection_scores)[output_box_index] =
  554. selected_score;
  555. } else {
  556. ReInterpretTensor<BoxCornerEncoding*>(
  557. detection_boxes)[output_box_index] = {0.0f, 0.0f, 0.0f, 0.0f};
  558. // detection_classes
  559. tflite::micro::GetTensorData<float>(detection_classes)[output_box_index] =
  560. 0.0f;
  561. // detection_scores
  562. tflite::micro::GetTensorData<float>(detection_scores)[output_box_index] =
  563. 0.0f;
  564. }
  565. }
  566. tflite::micro::GetTensorData<float>(num_detections)[0] =
  567. size_of_sorted_indices;
  568. return kTfLiteOk;
  569. }
  570. // This function implements a fast version of Non Maximal Suppression for
  571. // multiple classes where
  572. // 1) we keep the top-k scores for each anchor and
  573. // 2) during NMS, each anchor only uses the highest class score for sorting.
  574. // 3) Compared to standard NMS, the worst runtime of this version is O(N^2)
  575. // instead of O(KN^2) where N is the number of anchors and K the number of
  576. // classes.
  577. TfLiteStatus NonMaxSuppressionMultiClassFastHelper(TfLiteContext* context,
  578. TfLiteNode* node,
  579. OpData* op_data,
  580. const float* scores) {
  581. const TfLiteEvalTensor* input_box_encodings =
  582. tflite::micro::GetEvalInput(context, node, kInputTensorBoxEncodings);
  583. const TfLiteEvalTensor* input_class_predictions =
  584. tflite::micro::GetEvalInput(context, node, kInputTensorClassPredictions);
  585. TfLiteEvalTensor* detection_boxes =
  586. tflite::micro::GetEvalOutput(context, node, kOutputTensorDetectionBoxes);
  587. TfLiteEvalTensor* detection_classes = tflite::micro::GetEvalOutput(
  588. context, node, kOutputTensorDetectionClasses);
  589. TfLiteEvalTensor* detection_scores =
  590. tflite::micro::GetEvalOutput(context, node, kOutputTensorDetectionScores);
  591. TfLiteEvalTensor* num_detections =
  592. tflite::micro::GetEvalOutput(context, node, kOutputTensorNumDetections);
  593. const int num_boxes = input_box_encodings->dims->data[1];
  594. const int num_classes = op_data->num_classes;
  595. const int max_categories_per_anchor = op_data->max_classes_per_detection;
  596. const int num_classes_with_background =
  597. input_class_predictions->dims->data[2];
  598. // The row index offset is 1 if background class is included and 0 otherwise.
  599. int label_offset = num_classes_with_background - num_classes;
  600. TF_LITE_ENSURE(context, (max_categories_per_anchor > 0));
  601. const int num_categories_per_anchor =
  602. std::min(max_categories_per_anchor, num_classes);
  603. float* max_scores = reinterpret_cast<float*>(
  604. context->GetScratchBuffer(context, op_data->score_buffer_idx));
  605. int* sorted_class_indices = reinterpret_cast<int*>(
  606. context->GetScratchBuffer(context, op_data->buffer_idx));
  607. for (int row = 0; row < num_boxes; row++) {
  608. const float* box_scores =
  609. scores + row * num_classes_with_background + label_offset;
  610. int* class_indices = sorted_class_indices + row * num_classes;
  611. DecreasingPartialArgSort(box_scores, num_classes, num_categories_per_anchor,
  612. class_indices);
  613. max_scores[row] = box_scores[class_indices[0]];
  614. }
  615. // Perform non-maximal suppression on max scores
  616. int selected_size = 0;
  617. int* selected = reinterpret_cast<int*>(
  618. context->GetScratchBuffer(context, op_data->selected_idx));
  619. TF_LITE_ENSURE_STATUS(NonMaxSuppressionSingleClassHelper(
  620. context, node, op_data, max_scores, selected, &selected_size,
  621. op_data->max_detections));
  622. // Allocate output tensors
  623. int output_box_index = 0;
  624. for (int i = 0; i < selected_size; i++) {
  625. int selected_index = selected[i];
  626. const float* box_scores =
  627. scores + selected_index * num_classes_with_background + label_offset;
  628. const int* class_indices =
  629. sorted_class_indices + selected_index * num_classes;
  630. for (int col = 0; col < num_categories_per_anchor; ++col) {
  631. int box_offset = num_categories_per_anchor * output_box_index + col;
  632. // detection_boxes
  633. float* decoded_boxes = reinterpret_cast<float*>(
  634. context->GetScratchBuffer(context, op_data->decoded_boxes_idx));
  635. ReInterpretTensor<BoxCornerEncoding*>(detection_boxes)[box_offset] =
  636. reinterpret_cast<BoxCornerEncoding*>(decoded_boxes)[selected_index];
  637. // detection_classes
  638. tflite::micro::GetTensorData<float>(detection_classes)[box_offset] =
  639. class_indices[col];
  640. // detection_scores
  641. tflite::micro::GetTensorData<float>(detection_scores)[box_offset] =
  642. box_scores[class_indices[col]];
  643. output_box_index++;
  644. }
  645. }
  646. tflite::micro::GetTensorData<float>(num_detections)[0] = output_box_index;
  647. return kTfLiteOk;
  648. }
  649. TfLiteStatus NonMaxSuppressionMultiClass(TfLiteContext* context,
  650. TfLiteNode* node, OpData* op_data) {
  651. // Get the input tensors
  652. const TfLiteEvalTensor* input_box_encodings =
  653. tflite::micro::GetEvalInput(context, node, kInputTensorBoxEncodings);
  654. const TfLiteEvalTensor* input_class_predictions =
  655. tflite::micro::GetEvalInput(context, node, kInputTensorClassPredictions);
  656. const int num_boxes = input_box_encodings->dims->data[1];
  657. const int num_classes = op_data->num_classes;
  658. TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[0],
  659. kBatchSize);
  660. TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[1], num_boxes);
  661. const int num_classes_with_background =
  662. input_class_predictions->dims->data[2];
  663. TF_LITE_ENSURE(context, (num_classes_with_background - num_classes <= 1));
  664. TF_LITE_ENSURE(context, (num_classes_with_background >= num_classes));
  665. const float* scores;
  666. switch (input_class_predictions->type) {
  667. case kTfLiteFloat32:
  668. scores = tflite::micro::GetTensorData<float>(input_class_predictions);
  669. break;
  670. default:
  671. // Unsupported type.
  672. return kTfLiteError;
  673. }
  674. if (op_data->use_regular_non_max_suppression) {
  675. TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassRegularHelper(
  676. context, node, op_data, scores));
  677. } else {
  678. TF_LITE_ENSURE_STATUS(
  679. NonMaxSuppressionMultiClassFastHelper(context, node, op_data, scores));
  680. }
  681. return kTfLiteOk;
  682. }
  683. TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  684. TF_LITE_ENSURE(context, (kBatchSize == 1));
  685. auto* op_data = static_cast<OpData*>(node->user_data);
  686. // These two functions correspond to two blocks in the Object Detection model.
  687. // In future, we would like to break the custom op in two blocks, which is
  688. // currently not feasible because we would like to input quantized inputs
  689. // and do all calculations in float. Mixed quantized/float calculations are
  690. // currently not supported in TFLite.
  691. // This fills in temporary decoded_boxes
  692. // by transforming input_box_encodings and input_anchors from
  693. // CenterSizeEncodings to BoxCornerEncoding
  694. TF_LITE_ENSURE_STATUS(DecodeCenterSizeBoxes(context, node, op_data));
  695. // This fills in the output tensors
  696. // by choosing effective set of decoded boxes
  697. // based on Non Maximal Suppression, i.e. selecting
  698. // highest scoring non-overlapping boxes.
  699. TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClass(context, node, op_data));
  700. return kTfLiteOk;
  701. }
  702. } // namespace
  703. TfLiteRegistration* Register_DETECTION_POSTPROCESS() {
  704. static TfLiteRegistration r = tflite::micro::RegisterOp(Init, Prepare, Eval);
  705. return &r;
  706. }
  707. } // namespace tflite