detection_postprocess.cc 34 KB

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