1 /*
2 * Copyright (c) 2017-2020 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
25 #include "utils/GraphUtils.h"
26
27 #include "arm_compute/core/Helpers.h"
28 #include "arm_compute/core/Types.h"
29 #include "arm_compute/graph/Logger.h"
30 #include "arm_compute/runtime/SubTensor.h"
31
32 #pragma GCC diagnostic push
33 #pragma GCC diagnostic ignored "-Wunused-parameter"
34 #include "utils/ImageLoader.h"
35 #pragma GCC diagnostic pop
36 #include "utils/Utils.h"
37
38 #include <inttypes.h>
39 #include <iomanip>
40 #include <limits>
41
42 using namespace arm_compute::graph_utils;
43
44 namespace
45 {
compute_permutation_parameters(const arm_compute::TensorShape & shape,arm_compute::DataLayout data_layout)46 std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_parameters(const arm_compute::TensorShape &shape,
47 arm_compute::DataLayout data_layout)
48 {
49 // Set permutation parameters if needed
50 arm_compute::TensorShape permuted_shape = shape;
51 arm_compute::PermutationVector perm;
52 // Permute only if num_dimensions greater than 2
53 if(shape.num_dimensions() > 2)
54 {
55 perm = (data_layout == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
56
57 arm_compute::PermutationVector perm_shape = (data_layout == arm_compute::DataLayout::NCHW) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
58 arm_compute::permute(permuted_shape, perm_shape);
59 }
60
61 return std::make_pair(permuted_shape, perm);
62 }
63 } // namespace
64
TFPreproccessor(float min_range,float max_range)65 TFPreproccessor::TFPreproccessor(float min_range, float max_range)
66 : _min_range(min_range), _max_range(max_range)
67 {
68 }
preprocess(ITensor & tensor)69 void TFPreproccessor::preprocess(ITensor &tensor)
70 {
71 if(tensor.info()->data_type() == DataType::F32)
72 {
73 preprocess_typed<float>(tensor);
74 }
75 else if(tensor.info()->data_type() == DataType::F16)
76 {
77 preprocess_typed<half>(tensor);
78 }
79 else
80 {
81 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
82 }
83 }
84
85 template <typename T>
preprocess_typed(ITensor & tensor)86 void TFPreproccessor::preprocess_typed(ITensor &tensor)
87 {
88 Window window;
89 window.use_tensor_dimensions(tensor.info()->tensor_shape());
90
91 const float range = _max_range - _min_range;
92 execute_window_loop(window, [&](const Coordinates & id)
93 {
94 const T value = *reinterpret_cast<T *>(tensor.ptr_to_element(id));
95 float res = value / 255.f; // Normalize to [0, 1]
96 res = res * range + _min_range; // Map to [min_range, max_range]
97 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = res;
98 });
99 }
100
CaffePreproccessor(std::array<float,3> mean,bool bgr,float scale)101 CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr, float scale)
102 : _mean(mean), _bgr(bgr), _scale(scale)
103 {
104 if(_bgr)
105 {
106 std::swap(_mean[0], _mean[2]);
107 }
108 }
109
preprocess(ITensor & tensor)110 void CaffePreproccessor::preprocess(ITensor &tensor)
111 {
112 if(tensor.info()->data_type() == DataType::F32)
113 {
114 preprocess_typed<float>(tensor);
115 }
116 else if(tensor.info()->data_type() == DataType::F16)
117 {
118 preprocess_typed<half>(tensor);
119 }
120 else
121 {
122 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
123 }
124 }
125
126 template <typename T>
preprocess_typed(ITensor & tensor)127 void CaffePreproccessor::preprocess_typed(ITensor &tensor)
128 {
129 Window window;
130 window.use_tensor_dimensions(tensor.info()->tensor_shape());
131 const int channel_idx = get_data_layout_dimension_index(tensor.info()->data_layout(), DataLayoutDimension::CHANNEL);
132
133 execute_window_loop(window, [&](const Coordinates & id)
134 {
135 const T value = *reinterpret_cast<T *>(tensor.ptr_to_element(id)) - T(_mean[id[channel_idx]]);
136 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value * T(_scale);
137 });
138 }
139
PPMWriter(std::string name,unsigned int maximum)140 PPMWriter::PPMWriter(std::string name, unsigned int maximum)
141 : _name(std::move(name)), _iterator(0), _maximum(maximum)
142 {
143 }
144
access_tensor(ITensor & tensor)145 bool PPMWriter::access_tensor(ITensor &tensor)
146 {
147 std::stringstream ss;
148 ss << _name << _iterator << ".ppm";
149
150 arm_compute::utils::save_to_ppm(tensor, ss.str());
151
152 _iterator++;
153 if(_maximum == 0)
154 {
155 return true;
156 }
157 return _iterator < _maximum;
158 }
159
DummyAccessor(unsigned int maximum)160 DummyAccessor::DummyAccessor(unsigned int maximum)
161 : _iterator(0), _maximum(maximum)
162 {
163 }
164
access_tensor(ITensor & tensor)165 bool DummyAccessor::access_tensor(ITensor &tensor)
166 {
167 ARM_COMPUTE_UNUSED(tensor);
168 bool ret = _maximum == 0 || _iterator < _maximum;
169 if(_iterator == _maximum)
170 {
171 _iterator = 0;
172 }
173 else
174 {
175 _iterator++;
176 }
177 return ret;
178 }
179
NumPyAccessor(std::string npy_path,TensorShape shape,DataType data_type,DataLayout data_layout,std::ostream & output_stream)180 NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, DataLayout data_layout, std::ostream &output_stream)
181 : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
182 {
183 NumPyBinLoader loader(_filename, data_layout);
184
185 TensorInfo info(shape, 1, data_type);
186 info.set_data_layout(data_layout);
187
188 _npy_tensor.allocator()->init(info);
189 _npy_tensor.allocator()->allocate();
190
191 loader.access_tensor(_npy_tensor);
192 }
193
194 template <typename T>
access_numpy_tensor(ITensor & tensor,T tolerance)195 void NumPyAccessor::access_numpy_tensor(ITensor &tensor, T tolerance)
196 {
197 const int num_elements = tensor.info()->tensor_shape().total_size();
198 int num_mismatches = utils::compare_tensor<T>(tensor, _npy_tensor, tolerance);
199 float percentage_mismatches = static_cast<float>(num_mismatches) / num_elements;
200
201 _output_stream << "Results: " << 100.f - (percentage_mismatches * 100) << " % matches with the provided output[" << _filename << "]." << std::endl;
202 _output_stream << " " << num_elements - num_mismatches << " out of " << num_elements << " matches with the provided output[" << _filename << "]." << std::endl
203 << std::endl;
204 }
205
access_tensor(ITensor & tensor)206 bool NumPyAccessor::access_tensor(ITensor &tensor)
207 {
208 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
209 ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
210
211 switch(tensor.info()->data_type())
212 {
213 case DataType::QASYMM8:
214 access_numpy_tensor<qasymm8_t>(tensor, 0);
215 break;
216 case DataType::F32:
217 access_numpy_tensor<float>(tensor, 0.0001f);
218 break;
219 default:
220 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
221 }
222
223 return false;
224 }
225
226 #ifdef ARM_COMPUTE_ASSERTS_ENABLED
PrintAccessor(std::ostream & output_stream,IOFormatInfo io_fmt)227 PrintAccessor::PrintAccessor(std::ostream &output_stream, IOFormatInfo io_fmt)
228 : _output_stream(output_stream), _io_fmt(io_fmt)
229 {
230 }
231
access_tensor(ITensor & tensor)232 bool PrintAccessor::access_tensor(ITensor &tensor)
233 {
234 tensor.print(_output_stream, _io_fmt);
235 return false;
236 }
237 #endif /* ARM_COMPUTE_ASSERTS_ENABLED */
238
SaveNumPyAccessor(std::string npy_name,const bool is_fortran)239 SaveNumPyAccessor::SaveNumPyAccessor(std::string npy_name, const bool is_fortran)
240 : _npy_name(std::move(npy_name)), _is_fortran(is_fortran)
241 {
242 }
243
access_tensor(ITensor & tensor)244 bool SaveNumPyAccessor::access_tensor(ITensor &tensor)
245 {
246 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
247
248 utils::save_to_npy(tensor, _npy_name, _is_fortran);
249
250 return false;
251 }
252
ImageAccessor(std::string filename,bool bgr,std::unique_ptr<IPreprocessor> preprocessor)253 ImageAccessor::ImageAccessor(std::string filename, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
254 : _already_loaded(false), _filename(std::move(filename)), _bgr(bgr), _preprocessor(std::move(preprocessor))
255 {
256 }
257
access_tensor(ITensor & tensor)258 bool ImageAccessor::access_tensor(ITensor &tensor)
259 {
260 if(!_already_loaded)
261 {
262 auto image_loader = utils::ImageLoaderFactory::create(_filename);
263 ARM_COMPUTE_EXIT_ON_MSG(image_loader == nullptr, "Unsupported image type");
264
265 // Open image file
266 image_loader->open(_filename);
267
268 // Get permutated shape and permutation parameters
269 TensorShape permuted_shape = tensor.info()->tensor_shape();
270 arm_compute::PermutationVector perm;
271 if(tensor.info()->data_layout() != DataLayout::NCHW)
272 {
273 std::tie(permuted_shape, perm) = compute_permutation_parameters(tensor.info()->tensor_shape(), tensor.info()->data_layout());
274 }
275
276 ARM_COMPUTE_EXIT_ON_MSG_VAR(image_loader->width() != permuted_shape.x() || image_loader->height() != permuted_shape.y(),
277 "Failed to load image file: dimensions [%d,%d] not correct, expected [%zu ,%zu ].",
278 image_loader->width(), image_loader->height(), permuted_shape.x(), permuted_shape.y());
279
280 // Fill the tensor with the PPM content (BGR)
281 image_loader->fill_planar_tensor(tensor, _bgr);
282
283 // Preprocess tensor
284 if(_preprocessor)
285 {
286 _preprocessor->preprocess(tensor);
287 }
288 }
289
290 _already_loaded = !_already_loaded;
291 return _already_loaded;
292 }
293
ValidationInputAccessor(const std::string & image_list,std::string images_path,std::unique_ptr<IPreprocessor> preprocessor,bool bgr,unsigned int start,unsigned int end,std::ostream & output_stream)294 ValidationInputAccessor::ValidationInputAccessor(const std::string &image_list,
295 std::string images_path,
296 std::unique_ptr<IPreprocessor> preprocessor,
297 bool bgr,
298 unsigned int start,
299 unsigned int end,
300 std::ostream &output_stream)
301 : _path(std::move(images_path)), _images(), _preprocessor(std::move(preprocessor)), _bgr(bgr), _offset(0), _output_stream(output_stream)
302 {
303 ARM_COMPUTE_EXIT_ON_MSG(start > end, "Invalid validation range!");
304
305 std::ifstream ifs;
306 try
307 {
308 ifs.exceptions(std::ifstream::badbit);
309 ifs.open(image_list, std::ios::in | std::ios::binary);
310
311 // Parse image names
312 unsigned int counter = 0;
313 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
314 {
315 // Add image to process if withing range
316 if(counter >= start)
317 {
318 std::stringstream linestream(line);
319 std::string image_name;
320
321 linestream >> image_name;
322 _images.emplace_back(std::move(image_name));
323 }
324 }
325 }
326 catch(const std::ifstream::failure &e)
327 {
328 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", image_list.c_str(), e.what());
329 }
330 }
331
access_tensor(arm_compute::ITensor & tensor)332 bool ValidationInputAccessor::access_tensor(arm_compute::ITensor &tensor)
333 {
334 bool ret = _offset < _images.size();
335 if(ret)
336 {
337 utils::JPEGLoader jpeg;
338
339 // Open JPEG file
340 std::string image_name = _path + _images[_offset++];
341 jpeg.open(image_name);
342 _output_stream << "[" << _offset << "/" << _images.size() << "] Validating " << image_name << std::endl;
343
344 // Get permutated shape and permutation parameters
345 TensorShape permuted_shape = tensor.info()->tensor_shape();
346 arm_compute::PermutationVector perm;
347 if(tensor.info()->data_layout() != DataLayout::NCHW)
348 {
349 std::tie(permuted_shape, perm) = compute_permutation_parameters(tensor.info()->tensor_shape(),
350 tensor.info()->data_layout());
351 }
352
353 ARM_COMPUTE_EXIT_ON_MSG_VAR(jpeg.width() != permuted_shape.x() || jpeg.height() != permuted_shape.y(),
354 "Failed to load image file: dimensions [%d,%d] not correct, expected [%zu,%zu ].",
355 jpeg.width(), jpeg.height(), permuted_shape.x(), permuted_shape.y());
356
357 // Fill the tensor with the JPEG content (BGR)
358 jpeg.fill_planar_tensor(tensor, _bgr);
359
360 // Preprocess tensor
361 if(_preprocessor)
362 {
363 _preprocessor->preprocess(tensor);
364 }
365 }
366
367 return ret;
368 }
369
ValidationOutputAccessor(const std::string & image_list,std::ostream & output_stream,unsigned int start,unsigned int end)370 ValidationOutputAccessor::ValidationOutputAccessor(const std::string &image_list,
371 std::ostream &output_stream,
372 unsigned int start,
373 unsigned int end)
374 : _results(), _output_stream(output_stream), _offset(0), _positive_samples_top1(0), _positive_samples_top5(0)
375 {
376 ARM_COMPUTE_EXIT_ON_MSG(start > end, "Invalid validation range!");
377
378 std::ifstream ifs;
379 try
380 {
381 ifs.exceptions(std::ifstream::badbit);
382 ifs.open(image_list, std::ios::in | std::ios::binary);
383
384 // Parse image correctly classified labels
385 unsigned int counter = 0;
386 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
387 {
388 // Add label if within range
389 if(counter >= start)
390 {
391 std::stringstream linestream(line);
392 std::string image_name;
393 int result;
394
395 linestream >> image_name >> result;
396 _results.emplace_back(result);
397 }
398 }
399 }
400 catch(const std::ifstream::failure &e)
401 {
402 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", image_list.c_str(), e.what());
403 }
404 }
405
reset()406 void ValidationOutputAccessor::reset()
407 {
408 _offset = 0;
409 _positive_samples_top1 = 0;
410 _positive_samples_top5 = 0;
411 }
412
access_tensor(arm_compute::ITensor & tensor)413 bool ValidationOutputAccessor::access_tensor(arm_compute::ITensor &tensor)
414 {
415 bool ret = _offset < _results.size();
416 if(ret)
417 {
418 // Get results
419 std::vector<size_t> tensor_results;
420 switch(tensor.info()->data_type())
421 {
422 case DataType::QASYMM8:
423 tensor_results = access_predictions_tensor<uint8_t>(tensor);
424 break;
425 case DataType::F16:
426 tensor_results = access_predictions_tensor<half>(tensor);
427 break;
428 case DataType::F32:
429 tensor_results = access_predictions_tensor<float>(tensor);
430 break;
431 default:
432 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
433 }
434
435 // Check if tensor results are within top-n accuracy
436 size_t correct_label = _results[_offset++];
437
438 aggregate_sample(tensor_results, _positive_samples_top1, 1, correct_label);
439 aggregate_sample(tensor_results, _positive_samples_top5, 5, correct_label);
440 }
441
442 // Report top_n accuracy
443 if(_offset >= _results.size())
444 {
445 report_top_n(1, _results.size(), _positive_samples_top1);
446 report_top_n(5, _results.size(), _positive_samples_top5);
447 }
448
449 return ret;
450 }
451
452 template <typename T>
access_predictions_tensor(arm_compute::ITensor & tensor)453 std::vector<size_t> ValidationOutputAccessor::access_predictions_tensor(arm_compute::ITensor &tensor)
454 {
455 // Get the predicted class
456 std::vector<size_t> index;
457
458 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
459 const size_t num_classes = tensor.info()->dimension(0);
460
461 index.resize(num_classes);
462
463 // Sort results
464 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
465 std::sort(std::begin(index), std::end(index),
466 [&](size_t a, size_t b)
467 {
468 return output_net[a] > output_net[b];
469 });
470
471 return index;
472 }
473
aggregate_sample(const std::vector<size_t> & res,size_t & positive_samples,size_t top_n,size_t correct_label)474 void ValidationOutputAccessor::aggregate_sample(const std::vector<size_t> &res, size_t &positive_samples, size_t top_n, size_t correct_label)
475 {
476 auto is_valid_label = [correct_label](size_t label)
477 {
478 return label == correct_label;
479 };
480
481 if(std::any_of(std::begin(res), std::begin(res) + top_n, is_valid_label))
482 {
483 ++positive_samples;
484 }
485 }
486
report_top_n(size_t top_n,size_t total_samples,size_t positive_samples)487 void ValidationOutputAccessor::report_top_n(size_t top_n, size_t total_samples, size_t positive_samples)
488 {
489 size_t negative_samples = total_samples - positive_samples;
490 float accuracy = positive_samples / static_cast<float>(total_samples);
491
492 _output_stream << "----------Top " << top_n << " accuracy ----------" << std::endl
493 << std::endl;
494 _output_stream << "Positive samples : " << positive_samples << std::endl;
495 _output_stream << "Negative samples : " << negative_samples << std::endl;
496 _output_stream << "Accuracy : " << accuracy << std::endl;
497 }
498
DetectionOutputAccessor(const std::string & labels_path,std::vector<TensorShape> & imgs_tensor_shapes,std::ostream & output_stream)499 DetectionOutputAccessor::DetectionOutputAccessor(const std::string &labels_path, std::vector<TensorShape> &imgs_tensor_shapes, std::ostream &output_stream)
500 : _labels(), _tensor_shapes(std::move(imgs_tensor_shapes)), _output_stream(output_stream)
501 {
502 _labels.clear();
503
504 std::ifstream ifs;
505
506 try
507 {
508 ifs.exceptions(std::ifstream::badbit);
509 ifs.open(labels_path, std::ios::in | std::ios::binary);
510
511 for(std::string line; !std::getline(ifs, line).fail();)
512 {
513 _labels.emplace_back(line);
514 }
515 }
516 catch(const std::ifstream::failure &e)
517 {
518 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", labels_path.c_str(), e.what());
519 }
520 }
521
522 template <typename T>
access_predictions_tensor(ITensor & tensor)523 void DetectionOutputAccessor::access_predictions_tensor(ITensor &tensor)
524 {
525 const size_t num_detection = tensor.info()->valid_region().shape.y();
526 const auto output_prt = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
527
528 if(num_detection > 0)
529 {
530 _output_stream << "---------------------- Detections ----------------------" << std::endl
531 << std::endl;
532
533 _output_stream << std::left << std::setprecision(4) << std::setw(8) << "Image | " << std::setw(8) << "Label | " << std::setw(12) << "Confidence | "
534 << "[ xmin, ymin, xmax, ymax ]" << std::endl;
535
536 for(size_t i = 0; i < num_detection; ++i)
537 {
538 auto im = static_cast<const int>(output_prt[i * 7]);
539 _output_stream << std::setw(8) << im << std::setw(8)
540 << _labels[output_prt[i * 7 + 1]] << std::setw(12) << output_prt[i * 7 + 2]
541 << " [" << (output_prt[i * 7 + 3] * _tensor_shapes[im].x())
542 << ", " << (output_prt[i * 7 + 4] * _tensor_shapes[im].y())
543 << ", " << (output_prt[i * 7 + 5] * _tensor_shapes[im].x())
544 << ", " << (output_prt[i * 7 + 6] * _tensor_shapes[im].y())
545 << "]" << std::endl;
546 }
547 }
548 else
549 {
550 _output_stream << "No detection found." << std::endl;
551 }
552 }
553
access_tensor(ITensor & tensor)554 bool DetectionOutputAccessor::access_tensor(ITensor &tensor)
555 {
556 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
557
558 switch(tensor.info()->data_type())
559 {
560 case DataType::F32:
561 access_predictions_tensor<float>(tensor);
562 break;
563 default:
564 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
565 }
566
567 return false;
568 }
569
TopNPredictionsAccessor(const std::string & labels_path,size_t top_n,std::ostream & output_stream)570 TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
571 : _labels(), _output_stream(output_stream), _top_n(top_n)
572 {
573 _labels.clear();
574
575 std::ifstream ifs;
576
577 try
578 {
579 ifs.exceptions(std::ifstream::badbit);
580 ifs.open(labels_path, std::ios::in | std::ios::binary);
581
582 for(std::string line; !std::getline(ifs, line).fail();)
583 {
584 _labels.emplace_back(line);
585 }
586 }
587 catch(const std::ifstream::failure &e)
588 {
589 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", labels_path.c_str(), e.what());
590 }
591 }
592
593 template <typename T>
access_predictions_tensor(ITensor & tensor)594 void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
595 {
596 // Get the predicted class
597 std::vector<T> classes_prob;
598 std::vector<size_t> index;
599
600 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
601 const size_t num_classes = tensor.info()->dimension(0);
602
603 classes_prob.resize(num_classes);
604 index.resize(num_classes);
605
606 std::copy(output_net, output_net + num_classes, classes_prob.begin());
607
608 // Sort results
609 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
610 std::sort(std::begin(index), std::end(index),
611 [&](size_t a, size_t b)
612 {
613 return classes_prob[a] > classes_prob[b];
614 });
615
616 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
617 << std::endl;
618 for(size_t i = 0; i < _top_n; ++i)
619 {
620 _output_stream << std::fixed << std::setprecision(4)
621 << +classes_prob[index.at(i)]
622 << " - [id = " << index.at(i) << "]"
623 << ", " << _labels[index.at(i)] << std::endl;
624 }
625 }
626
access_tensor(ITensor & tensor)627 bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
628 {
629 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
630 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
631
632 switch(tensor.info()->data_type())
633 {
634 case DataType::QASYMM8:
635 access_predictions_tensor<uint8_t>(tensor);
636 break;
637 case DataType::F32:
638 access_predictions_tensor<float>(tensor);
639 break;
640 default:
641 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
642 }
643
644 return false;
645 }
646
RandomAccessor(PixelValue lower,PixelValue upper,std::random_device::result_type seed)647 RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
648 : _lower(lower), _upper(upper), _seed(seed)
649 {
650 }
651
652 template <typename T, typename D>
fill(ITensor & tensor,D && distribution)653 void RandomAccessor::fill(ITensor &tensor, D &&distribution)
654 {
655 std::mt19937 gen(_seed);
656
657 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
658 {
659 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
660 {
661 const auto value = static_cast<T>(distribution(gen));
662 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
663 }
664 }
665 else
666 {
667 // If tensor has padding accessing tensor elements through execution window.
668 Window window;
669 window.use_tensor_dimensions(tensor.info()->tensor_shape());
670
671 execute_window_loop(window, [&](const Coordinates & id)
672 {
673 const auto value = static_cast<T>(distribution(gen));
674 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
675 });
676 }
677 }
678
access_tensor(ITensor & tensor)679 bool RandomAccessor::access_tensor(ITensor &tensor)
680 {
681 switch(tensor.info()->data_type())
682 {
683 case DataType::QASYMM8:
684 case DataType::U8:
685 {
686 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
687 fill<uint8_t>(tensor, distribution_u8);
688 break;
689 }
690 case DataType::S8:
691 {
692 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
693 fill<int8_t>(tensor, distribution_s8);
694 break;
695 }
696 case DataType::U16:
697 {
698 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
699 fill<uint16_t>(tensor, distribution_u16);
700 break;
701 }
702 case DataType::S16:
703 {
704 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
705 fill<int16_t>(tensor, distribution_s16);
706 break;
707 }
708 case DataType::U32:
709 {
710 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
711 fill<uint32_t>(tensor, distribution_u32);
712 break;
713 }
714 case DataType::S32:
715 {
716 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
717 fill<int32_t>(tensor, distribution_s32);
718 break;
719 }
720 case DataType::U64:
721 {
722 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
723 fill<uint64_t>(tensor, distribution_u64);
724 break;
725 }
726 case DataType::S64:
727 {
728 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
729 fill<int64_t>(tensor, distribution_s64);
730 break;
731 }
732 case DataType::F16:
733 {
734 std::uniform_real_distribution<float> distribution_f16(_lower.get<half>(), _upper.get<half>());
735 fill<half>(tensor, distribution_f16);
736 break;
737 }
738 case DataType::F32:
739 {
740 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
741 fill<float>(tensor, distribution_f32);
742 break;
743 }
744 case DataType::F64:
745 {
746 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
747 fill<double>(tensor, distribution_f64);
748 break;
749 }
750 default:
751 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
752 }
753 return true;
754 }
755
NumPyBinLoader(std::string filename,DataLayout file_layout)756 NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
757 : _already_loaded(false), _filename(std::move(filename)), _file_layout(file_layout)
758 {
759 }
760
access_tensor(ITensor & tensor)761 bool NumPyBinLoader::access_tensor(ITensor &tensor)
762 {
763 if(!_already_loaded)
764 {
765 utils::NPYLoader loader;
766 loader.open(_filename, _file_layout);
767 loader.fill_tensor(tensor);
768 }
769
770 _already_loaded = !_already_loaded;
771 return _already_loaded;
772 }
773