xref: /aosp_15_r20/external/ComputeLibrary/src/runtime/NEON/functions/NEGenerateProposalsLayer.cpp (revision c217d954acce2dbc11938adb493fc0abd69584f3)
1 /*
2  * Copyright (c) 2019-2021 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include "arm_compute/runtime/NEON/functions/NEGenerateProposalsLayer.h"
25 
26 #include "arm_compute/core/Types.h"
27 #include "arm_compute/runtime/NEON/NEScheduler.h"
28 #include "src/common/utils/Log.h"
29 #include "src/core/NEON/kernels/NEFillBorderKernel.h"
30 #include "src/core/NEON/kernels/NEGenerateProposalsLayerKernel.h"
31 #include "src/core/NEON/kernels/NEPadLayerKernel.h"
32 #include "src/core/helpers/AutoConfiguration.h"
33 
34 namespace arm_compute
35 {
NEGenerateProposalsLayer(std::shared_ptr<IMemoryManager> memory_manager)36 NEGenerateProposalsLayer::NEGenerateProposalsLayer(std::shared_ptr<IMemoryManager> memory_manager)
37     : _memory_group(memory_manager),
38       _permute_deltas(),
39       _flatten_deltas(),
40       _permute_scores(),
41       _flatten_scores(),
42       _compute_anchors(nullptr),
43       _bounding_box(),
44       _pad(),
45       _dequantize_anchors(),
46       _dequantize_deltas(),
47       _quantize_all_proposals(),
48       _cpp_nms(memory_manager),
49       _is_nhwc(false),
50       _is_qasymm8(false),
51       _deltas_permuted(),
52       _deltas_flattened(),
53       _deltas_flattened_f32(),
54       _scores_permuted(),
55       _scores_flattened(),
56       _all_anchors(),
57       _all_anchors_f32(),
58       _all_proposals(),
59       _all_proposals_quantized(),
60       _keeps_nms_unused(),
61       _classes_nms_unused(),
62       _proposals_4_roi_values(),
63       _all_proposals_to_use(nullptr),
64       _num_valid_proposals(nullptr),
65       _scores_out(nullptr)
66 {
67 }
68 
69 NEGenerateProposalsLayer::~NEGenerateProposalsLayer() = default;
70 
configure(const ITensor * scores,const ITensor * deltas,const ITensor * anchors,ITensor * proposals,ITensor * scores_out,ITensor * num_valid_proposals,const GenerateProposalsInfo & info)71 void NEGenerateProposalsLayer::configure(const ITensor *scores, const ITensor *deltas, const ITensor *anchors, ITensor *proposals, ITensor *scores_out, ITensor *num_valid_proposals,
72                                          const GenerateProposalsInfo &info)
73 {
74     ARM_COMPUTE_ERROR_ON_NULLPTR(scores, deltas, anchors, proposals, scores_out, num_valid_proposals);
75     ARM_COMPUTE_ERROR_THROW_ON(NEGenerateProposalsLayer::validate(scores->info(), deltas->info(), anchors->info(), proposals->info(), scores_out->info(), num_valid_proposals->info(), info));
76     ARM_COMPUTE_LOG_PARAMS(scores, deltas, anchors, proposals, scores_out, num_valid_proposals, info);
77 
78     _is_nhwc                        = scores->info()->data_layout() == DataLayout::NHWC;
79     const DataType scores_data_type = scores->info()->data_type();
80     _is_qasymm8                     = scores_data_type == DataType::QASYMM8;
81     const int    num_anchors        = scores->info()->dimension(get_data_layout_dimension_index(scores->info()->data_layout(), DataLayoutDimension::CHANNEL));
82     const int    feat_width         = scores->info()->dimension(get_data_layout_dimension_index(scores->info()->data_layout(), DataLayoutDimension::WIDTH));
83     const int    feat_height        = scores->info()->dimension(get_data_layout_dimension_index(scores->info()->data_layout(), DataLayoutDimension::HEIGHT));
84     const int    total_num_anchors  = num_anchors * feat_width * feat_height;
85     const int    pre_nms_topN       = info.pre_nms_topN();
86     const int    post_nms_topN      = info.post_nms_topN();
87     const size_t values_per_roi     = info.values_per_roi();
88 
89     const QuantizationInfo scores_qinfo   = scores->info()->quantization_info();
90     const DataType         rois_data_type = (_is_qasymm8) ? DataType::QASYMM16 : scores_data_type;
91     const QuantizationInfo rois_qinfo     = (_is_qasymm8) ? QuantizationInfo(0.125f, 0) : scores->info()->quantization_info();
92 
93     // Compute all the anchors
94     _memory_group.manage(&_all_anchors);
95     _compute_anchors = std::make_unique<NEComputeAllAnchorsKernel>();
96     _compute_anchors->configure(anchors, &_all_anchors, ComputeAnchorsInfo(feat_width, feat_height, info.spatial_scale()));
97 
98     const TensorShape flatten_shape_deltas(values_per_roi, total_num_anchors);
99     _deltas_flattened.allocator()->init(TensorInfo(flatten_shape_deltas, 1, scores_data_type, deltas->info()->quantization_info()));
100 
101     // Permute and reshape deltas
102     _memory_group.manage(&_deltas_flattened);
103     if(!_is_nhwc)
104     {
105         _memory_group.manage(&_deltas_permuted);
106         _permute_deltas.configure(deltas, &_deltas_permuted, PermutationVector{ 2, 0, 1 });
107         _flatten_deltas.configure(&_deltas_permuted, &_deltas_flattened);
108         _deltas_permuted.allocator()->allocate();
109     }
110     else
111     {
112         _flatten_deltas.configure(deltas, &_deltas_flattened);
113     }
114 
115     const TensorShape flatten_shape_scores(1, total_num_anchors);
116     _scores_flattened.allocator()->init(TensorInfo(flatten_shape_scores, 1, scores_data_type, scores_qinfo));
117 
118     // Permute and reshape scores
119     _memory_group.manage(&_scores_flattened);
120     if(!_is_nhwc)
121     {
122         _memory_group.manage(&_scores_permuted);
123         _permute_scores.configure(scores, &_scores_permuted, PermutationVector{ 2, 0, 1 });
124         _flatten_scores.configure(&_scores_permuted, &_scores_flattened);
125         _scores_permuted.allocator()->allocate();
126     }
127     else
128     {
129         _flatten_scores.configure(scores, &_scores_flattened);
130     }
131 
132     Tensor *anchors_to_use = &_all_anchors;
133     Tensor *deltas_to_use  = &_deltas_flattened;
134     if(_is_qasymm8)
135     {
136         _all_anchors_f32.allocator()->init(TensorInfo(_all_anchors.info()->tensor_shape(), 1, DataType::F32));
137         _deltas_flattened_f32.allocator()->init(TensorInfo(_deltas_flattened.info()->tensor_shape(), 1, DataType::F32));
138         _memory_group.manage(&_all_anchors_f32);
139         _memory_group.manage(&_deltas_flattened_f32);
140         // Dequantize anchors to float
141         _dequantize_anchors.configure(&_all_anchors, &_all_anchors_f32);
142         _all_anchors.allocator()->allocate();
143         anchors_to_use = &_all_anchors_f32;
144         // Dequantize deltas to float
145         _dequantize_deltas.configure(&_deltas_flattened, &_deltas_flattened_f32);
146         _deltas_flattened.allocator()->allocate();
147         deltas_to_use = &_deltas_flattened_f32;
148     }
149     // Bounding box transform
150     _memory_group.manage(&_all_proposals);
151     BoundingBoxTransformInfo bbox_info(info.im_width(), info.im_height(), 1.f);
152     _bounding_box.configure(anchors_to_use, &_all_proposals, deltas_to_use, bbox_info);
153     deltas_to_use->allocator()->allocate();
154     anchors_to_use->allocator()->allocate();
155 
156     _all_proposals_to_use = &_all_proposals;
157     if(_is_qasymm8)
158     {
159         _memory_group.manage(&_all_proposals_quantized);
160         // Requantize all_proposals to QASYMM16 with 0.125 scale and 0 offset
161         _all_proposals_quantized.allocator()->init(TensorInfo(_all_proposals.info()->tensor_shape(), 1, DataType::QASYMM16, QuantizationInfo(0.125f, 0)));
162         _quantize_all_proposals.configure(&_all_proposals, &_all_proposals_quantized);
163         _all_proposals.allocator()->allocate();
164         _all_proposals_to_use = &_all_proposals_quantized;
165     }
166     // The original layer implementation first selects the best pre_nms_topN anchors (thus having a lightweight sort)
167     // that are then transformed by bbox_transform. The boxes generated are then fed into a non-sorting NMS operation.
168     // Since we are reusing the NMS layer and we don't implement any CL/sort, we let NMS do the sorting (of all the input)
169     // and the filtering
170     const int   scores_nms_size = std::min<int>(std::min<int>(post_nms_topN, pre_nms_topN), total_num_anchors);
171     const float min_size_scaled = info.min_size() * info.im_scale();
172     _memory_group.manage(&_classes_nms_unused);
173     _memory_group.manage(&_keeps_nms_unused);
174 
175     // Note that NMS needs outputs preinitialized.
176     auto_init_if_empty(*scores_out->info(), TensorShape(scores_nms_size), 1, scores_data_type, scores_qinfo);
177     auto_init_if_empty(*_proposals_4_roi_values.info(), TensorShape(values_per_roi, scores_nms_size), 1, rois_data_type, rois_qinfo);
178     auto_init_if_empty(*num_valid_proposals->info(), TensorShape(1), 1, DataType::U32);
179 
180     // Initialize temporaries (unused) outputs
181     _classes_nms_unused.allocator()->init(TensorInfo(TensorShape(scores_nms_size), 1, scores_data_type, scores_qinfo));
182     _keeps_nms_unused.allocator()->init(*scores_out->info());
183 
184     // Save the output (to map and unmap them at run)
185     _scores_out          = scores_out;
186     _num_valid_proposals = num_valid_proposals;
187 
188     _memory_group.manage(&_proposals_4_roi_values);
189 
190     const BoxNMSLimitInfo box_nms_info(0.0f, info.nms_thres(), scores_nms_size, false, NMSType::LINEAR, 0.5f, 0.001f, true, min_size_scaled, info.im_width(), info.im_height());
191     _cpp_nms.configure(&_scores_flattened /*scores_in*/,
192                        _all_proposals_to_use /*boxes_in,*/,
193                        nullptr /* batch_splits_in*/,
194                        scores_out /* scores_out*/,
195                        &_proposals_4_roi_values /*boxes_out*/,
196                        &_classes_nms_unused /*classes*/,
197                        nullptr /*batch_splits_out*/,
198                        &_keeps_nms_unused /*keeps*/,
199                        num_valid_proposals /* keeps_size*/,
200                        box_nms_info);
201 
202     _keeps_nms_unused.allocator()->allocate();
203     _classes_nms_unused.allocator()->allocate();
204     _all_proposals_to_use->allocator()->allocate();
205     _scores_flattened.allocator()->allocate();
206 
207     // Add the first column that represents the batch id. This will be all zeros, as we don't support multiple images
208     _pad.configure(&_proposals_4_roi_values, proposals, PaddingList{ { 1, 0 } });
209     _proposals_4_roi_values.allocator()->allocate();
210 }
211 
validate(const ITensorInfo * scores,const ITensorInfo * deltas,const ITensorInfo * anchors,const ITensorInfo * proposals,const ITensorInfo * scores_out,const ITensorInfo * num_valid_proposals,const GenerateProposalsInfo & info)212 Status NEGenerateProposalsLayer::validate(const ITensorInfo *scores, const ITensorInfo *deltas, const ITensorInfo *anchors, const ITensorInfo *proposals, const ITensorInfo *scores_out,
213                                           const ITensorInfo *num_valid_proposals, const GenerateProposalsInfo &info)
214 {
215     ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(scores, deltas, anchors, proposals, scores_out, num_valid_proposals);
216     ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(scores, 1, DataType::QASYMM8, DataType::F16, DataType::F32);
217     ARM_COMPUTE_RETURN_ERROR_ON_DATA_LAYOUT_NOT_IN(scores, DataLayout::NCHW, DataLayout::NHWC);
218     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(scores, deltas);
219     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(scores, deltas);
220 
221     const int num_anchors       = scores->dimension(get_data_layout_dimension_index(scores->data_layout(), DataLayoutDimension::CHANNEL));
222     const int feat_width        = scores->dimension(get_data_layout_dimension_index(scores->data_layout(), DataLayoutDimension::WIDTH));
223     const int feat_height       = scores->dimension(get_data_layout_dimension_index(scores->data_layout(), DataLayoutDimension::HEIGHT));
224     const int num_images        = scores->dimension(3);
225     const int total_num_anchors = num_anchors * feat_width * feat_height;
226     const int values_per_roi    = info.values_per_roi();
227 
228     const bool is_qasymm8 = scores->data_type() == DataType::QASYMM8;
229 
230     ARM_COMPUTE_RETURN_ERROR_ON(num_images > 1);
231 
232     if(is_qasymm8)
233     {
234         ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(anchors, 1, DataType::QSYMM16);
235         const UniformQuantizationInfo anchors_qinfo = anchors->quantization_info().uniform();
236         ARM_COMPUTE_RETURN_ERROR_ON(anchors_qinfo.scale != 0.125f);
237     }
238 
239     TensorInfo all_anchors_info(anchors->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true));
240     ARM_COMPUTE_RETURN_ON_ERROR(NEComputeAllAnchorsKernel::validate(anchors, &all_anchors_info, ComputeAnchorsInfo(feat_width, feat_height, info.spatial_scale())));
241 
242     TensorInfo deltas_permuted_info = deltas->clone()->set_tensor_shape(TensorShape(values_per_roi * num_anchors, feat_width, feat_height)).set_is_resizable(true);
243     TensorInfo scores_permuted_info = scores->clone()->set_tensor_shape(TensorShape(num_anchors, feat_width, feat_height)).set_is_resizable(true);
244     if(scores->data_layout() == DataLayout::NHWC)
245     {
246         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(deltas, &deltas_permuted_info);
247         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(scores, &scores_permuted_info);
248     }
249     else
250     {
251         ARM_COMPUTE_RETURN_ON_ERROR(NEPermute::validate(deltas, &deltas_permuted_info, PermutationVector{ 2, 0, 1 }));
252         ARM_COMPUTE_RETURN_ON_ERROR(NEPermute::validate(scores, &scores_permuted_info, PermutationVector{ 2, 0, 1 }));
253     }
254 
255     TensorInfo deltas_flattened_info(deltas->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true));
256     ARM_COMPUTE_RETURN_ON_ERROR(NEReshapeLayer::validate(&deltas_permuted_info, &deltas_flattened_info));
257 
258     TensorInfo scores_flattened_info(scores->clone()->set_tensor_shape(TensorShape(1, total_num_anchors)).set_is_resizable(true));
259     TensorInfo proposals_4_roi_values(deltas->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true));
260 
261     ARM_COMPUTE_RETURN_ON_ERROR(NEReshapeLayer::validate(&scores_permuted_info, &scores_flattened_info));
262 
263     TensorInfo *proposals_4_roi_values_to_use = &proposals_4_roi_values;
264     TensorInfo  proposals_4_roi_values_quantized(deltas->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true));
265     proposals_4_roi_values_quantized.set_data_type(DataType::QASYMM16).set_quantization_info(QuantizationInfo(0.125f, 0));
266     if(is_qasymm8)
267     {
268         TensorInfo all_anchors_f32_info(anchors->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true).set_data_type(DataType::F32));
269         ARM_COMPUTE_RETURN_ON_ERROR(NEDequantizationLayer::validate(&all_anchors_info, &all_anchors_f32_info));
270 
271         TensorInfo deltas_flattened_f32_info(deltas->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true).set_data_type(DataType::F32));
272         ARM_COMPUTE_RETURN_ON_ERROR(NEDequantizationLayer::validate(&deltas_flattened_info, &deltas_flattened_f32_info));
273 
274         TensorInfo proposals_4_roi_values_f32(deltas->clone()->set_tensor_shape(TensorShape(values_per_roi, total_num_anchors)).set_is_resizable(true).set_data_type(DataType::F32));
275         ARM_COMPUTE_RETURN_ON_ERROR(NEBoundingBoxTransform::validate(&all_anchors_f32_info, &proposals_4_roi_values_f32, &deltas_flattened_f32_info,
276                                                                      BoundingBoxTransformInfo(info.im_width(), info.im_height(), 1.f)));
277 
278         ARM_COMPUTE_RETURN_ON_ERROR(NEQuantizationLayer::validate(&proposals_4_roi_values_f32, &proposals_4_roi_values_quantized));
279         proposals_4_roi_values_to_use = &proposals_4_roi_values_quantized;
280     }
281     else
282     {
283         ARM_COMPUTE_RETURN_ON_ERROR(NEBoundingBoxTransform::validate(&all_anchors_info, &proposals_4_roi_values, &deltas_flattened_info,
284                                                                      BoundingBoxTransformInfo(info.im_width(), info.im_height(), 1.f)));
285     }
286 
287     ARM_COMPUTE_RETURN_ON_ERROR(NEPadLayer::validate(proposals_4_roi_values_to_use, proposals, PaddingList{ { 1, 0 } }));
288 
289     if(num_valid_proposals->total_size() > 0)
290     {
291         ARM_COMPUTE_RETURN_ERROR_ON(num_valid_proposals->num_dimensions() > 1);
292         ARM_COMPUTE_RETURN_ERROR_ON(num_valid_proposals->dimension(0) > 1);
293         ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(num_valid_proposals, 1, DataType::U32);
294     }
295 
296     if(proposals->total_size() > 0)
297     {
298         ARM_COMPUTE_RETURN_ERROR_ON(proposals->num_dimensions() > 2);
299         ARM_COMPUTE_RETURN_ERROR_ON(proposals->dimension(0) != size_t(values_per_roi) + 1);
300         ARM_COMPUTE_RETURN_ERROR_ON(proposals->dimension(1) != size_t(total_num_anchors));
301         if(is_qasymm8)
302         {
303             ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(proposals, 1, DataType::QASYMM16);
304             const UniformQuantizationInfo proposals_qinfo = proposals->quantization_info().uniform();
305             ARM_COMPUTE_RETURN_ERROR_ON(proposals_qinfo.scale != 0.125f);
306             ARM_COMPUTE_RETURN_ERROR_ON(proposals_qinfo.offset != 0);
307         }
308         else
309         {
310             ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(proposals, scores);
311         }
312     }
313 
314     if(scores_out->total_size() > 0)
315     {
316         ARM_COMPUTE_RETURN_ERROR_ON(scores_out->num_dimensions() > 1);
317         ARM_COMPUTE_RETURN_ERROR_ON(scores_out->dimension(0) != size_t(total_num_anchors));
318         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(scores_out, scores);
319     }
320 
321     return Status{};
322 }
323 
run()324 void NEGenerateProposalsLayer::run()
325 {
326     // Acquire all the temporaries
327     MemoryGroupResourceScope scope_mg(_memory_group);
328 
329     // Compute all the anchors
330     NEScheduler::get().schedule(_compute_anchors.get(), Window::DimY);
331 
332     // Transpose and reshape the inputs
333     if(!_is_nhwc)
334     {
335         _permute_deltas.run();
336         _permute_scores.run();
337     }
338 
339     _flatten_deltas.run();
340     _flatten_scores.run();
341 
342     if(_is_qasymm8)
343     {
344         _dequantize_anchors.run();
345         _dequantize_deltas.run();
346     }
347 
348     // Build the boxes
349     _bounding_box.run();
350 
351     if(_is_qasymm8)
352     {
353         _quantize_all_proposals.run();
354     }
355 
356     // Non maxima suppression
357     _cpp_nms.run();
358 
359     // Add dummy batch indexes
360     _pad.run();
361 }
362 } // namespace arm_compute
363