blob: 1d18fb5f9ca8f2ca709afd3d693d43d5f2db438f [file] [log] [blame]
Kaizen8938bd32017-09-28 14:38:23 +01001/*
Jenkins49b8f902020-11-27 12:49:11 +00002 * Copyright (c) 2017-2020 Arm Limited.
Kaizen8938bd32017-09-28 14:38:23 +01003 *
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"
Anthony Barbier06ea0482018-02-22 15:45:35 +000026
Jenkinsb3a371b2018-05-23 11:36:53 +010027#include "arm_compute/core/Helpers.h"
28#include "arm_compute/core/Types.h"
Jenkins52ba29e2018-08-29 15:32:11 +000029#include "arm_compute/graph/Logger.h"
hakanardo29222792018-02-16 10:06:34 +010030#include "arm_compute/runtime/SubTensor.h"
Jenkins0e205f72019-11-28 16:53:35 +000031
32#pragma GCC diagnostic push
33#pragma GCC diagnostic ignored "-Wunused-parameter"
Jenkins52ba29e2018-08-29 15:32:11 +000034#include "utils/ImageLoader.h"
Jenkins0e205f72019-11-28 16:53:35 +000035#pragma GCC diagnostic pop
Anthony Barbier06ea0482018-02-22 15:45:35 +000036#include "utils/Utils.h"
Kaizen8938bd32017-09-28 14:38:23 +010037
Jenkins0e205f72019-11-28 16:53:35 +000038#include <inttypes.h>
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010039#include <iomanip>
Jenkins52ba29e2018-08-29 15:32:11 +000040#include <limits>
Kaizen8938bd32017-09-28 14:38:23 +010041
42using namespace arm_compute::graph_utils;
43
Jenkinsb3a371b2018-05-23 11:36:53 +010044namespace
45{
Jenkins52ba29e2018-08-29 15:32:11 +000046std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_parameters(const arm_compute::TensorShape &shape,
Jenkinsb3a371b2018-05-23 11:36:53 +010047 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
Jenkinsb9abeae2018-11-22 11:58:08 +000065TFPreproccessor::TFPreproccessor(float min_range, float max_range)
66 : _min_range(min_range), _max_range(max_range)
67{
68}
Anthony Barbier06ea0482018-02-22 15:45:35 +000069void TFPreproccessor::preprocess(ITensor &tensor)
70{
Jenkins0e205f72019-11-28 16:53:35 +000071 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
85template <typename T>
86void TFPreproccessor::preprocess_typed(ITensor &tensor)
87{
Anthony Barbier06ea0482018-02-22 15:45:35 +000088 Window window;
89 window.use_tensor_dimensions(tensor.info()->tensor_shape());
90
Jenkinsb9abeae2018-11-22 11:58:08 +000091 const float range = _max_range - _min_range;
Anthony Barbier06ea0482018-02-22 15:45:35 +000092 execute_window_loop(window, [&](const Coordinates & id)
93 {
Jenkins0e205f72019-11-28 16:53:35 +000094 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;
Anthony Barbier06ea0482018-02-22 15:45:35 +000098 });
99}
100
Jenkins4ba87db2019-05-23 17:11:51 +0100101CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr, float scale)
102 : _mean(mean), _bgr(bgr), _scale(scale)
Anthony Barbier06ea0482018-02-22 15:45:35 +0000103{
104 if(_bgr)
105 {
106 std::swap(_mean[0], _mean[2]);
107 }
108}
109
110void CaffePreproccessor::preprocess(ITensor &tensor)
111{
Jenkins0e205f72019-11-28 16:53:35 +0000112 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
126template <typename T>
127void CaffePreproccessor::preprocess_typed(ITensor &tensor)
128{
Anthony Barbier06ea0482018-02-22 15:45:35 +0000129 Window window;
130 window.use_tensor_dimensions(tensor.info()->tensor_shape());
Jenkins52ba29e2018-08-29 15:32:11 +0000131 const int channel_idx = get_data_layout_dimension_index(tensor.info()->data_layout(), DataLayoutDimension::CHANNEL);
132
Anthony Barbier06ea0482018-02-22 15:45:35 +0000133 execute_window_loop(window, [&](const Coordinates & id)
134 {
Jenkins0e205f72019-11-28 16:53:35 +0000135 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);
Anthony Barbier06ea0482018-02-22 15:45:35 +0000137 });
138}
139
Kaizen8938bd32017-09-28 14:38:23 +0100140PPMWriter::PPMWriter(std::string name, unsigned int maximum)
141 : _name(std::move(name)), _iterator(0), _maximum(maximum)
142{
143}
144
145bool PPMWriter::access_tensor(ITensor &tensor)
146{
147 std::stringstream ss;
148 ss << _name << _iterator << ".ppm";
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100149
150 arm_compute::utils::save_to_ppm(tensor, ss.str());
Kaizen8938bd32017-09-28 14:38:23 +0100151
152 _iterator++;
153 if(_maximum == 0)
154 {
155 return true;
156 }
157 return _iterator < _maximum;
158}
159
160DummyAccessor::DummyAccessor(unsigned int maximum)
161 : _iterator(0), _maximum(maximum)
162{
163}
164
165bool 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
Jenkins975dfe12019-09-02 11:47:54 +0100180NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, DataLayout data_layout, std::ostream &output_stream)
Jenkinsb3a371b2018-05-23 11:36:53 +0100181 : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
182{
Jenkins975dfe12019-09-02 11:47:54 +0100183 NumPyBinLoader loader(_filename, data_layout);
Jenkinsb3a371b2018-05-23 11:36:53 +0100184
185 TensorInfo info(shape, 1, data_type);
Jenkins975dfe12019-09-02 11:47:54 +0100186 info.set_data_layout(data_layout);
187
Jenkinsb3a371b2018-05-23 11:36:53 +0100188 _npy_tensor.allocator()->init(info);
189 _npy_tensor.allocator()->allocate();
190
191 loader.access_tensor(_npy_tensor);
192}
193
194template <typename T>
Jenkins4ba87db2019-05-23 17:11:51 +0100195void NumPyAccessor::access_numpy_tensor(ITensor &tensor, T tolerance)
Jenkinsb3a371b2018-05-23 11:36:53 +0100196{
Jenkins52ba29e2018-08-29 15:32:11 +0000197 const int num_elements = tensor.info()->tensor_shape().total_size();
Jenkins4ba87db2019-05-23 17:11:51 +0100198 int num_mismatches = utils::compare_tensor<T>(tensor, _npy_tensor, tolerance);
Jenkinsb3a371b2018-05-23 11:36:53 +0100199 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;
Jenkins4ba87db2019-05-23 17:11:51 +0100202 _output_stream << " " << num_elements - num_mismatches << " out of " << num_elements << " matches with the provided output[" << _filename << "]." << std::endl
203 << std::endl;
Jenkinsb3a371b2018-05-23 11:36:53 +0100204}
205
206bool NumPyAccessor::access_tensor(ITensor &tensor)
207{
Jenkins4ba87db2019-05-23 17:11:51 +0100208 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
Jenkinsb3a371b2018-05-23 11:36:53 +0100209 ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
210
211 switch(tensor.info()->data_type())
212 {
Jenkins4ba87db2019-05-23 17:11:51 +0100213 case DataType::QASYMM8:
214 access_numpy_tensor<qasymm8_t>(tensor, 0);
215 break;
Jenkinsb3a371b2018-05-23 11:36:53 +0100216 case DataType::F32:
Jenkins4ba87db2019-05-23 17:11:51 +0100217 access_numpy_tensor<float>(tensor, 0.0001f);
Jenkinsb3a371b2018-05-23 11:36:53 +0100218 break;
219 default:
220 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
221 }
222
223 return false;
224}
225
Jenkins0e205f72019-11-28 16:53:35 +0000226#ifdef ARM_COMPUTE_ASSERTS_ENABLED
227PrintAccessor::PrintAccessor(std::ostream &output_stream, IOFormatInfo io_fmt)
228 : _output_stream(output_stream), _io_fmt(io_fmt)
229{
230}
231
232bool PrintAccessor::access_tensor(ITensor &tensor)
233{
234 tensor.print(_output_stream, _io_fmt);
235 return false;
236}
237#endif /* ARM_COMPUTE_ASSERTS_ENABLED */
238
Jenkins975dfe12019-09-02 11:47:54 +0100239SaveNumPyAccessor::SaveNumPyAccessor(std::string npy_name, const bool is_fortran)
240 : _npy_name(std::move(npy_name)), _is_fortran(is_fortran)
241{
242}
243
244bool 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
Jenkins52ba29e2018-08-29 15:32:11 +0000253ImageAccessor::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))
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100255{
256}
257
Jenkins52ba29e2018-08-29 15:32:11 +0000258bool ImageAccessor::access_tensor(ITensor &tensor)
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100259{
Jenkins52ba29e2018-08-29 15:32:11 +0000260 if(!_already_loaded)
Jenkinsb3a371b2018-05-23 11:36:53 +0100261 {
Jenkins52ba29e2018-08-29 15:32:11 +0000262 auto image_loader = utils::ImageLoaderFactory::create(_filename);
263 ARM_COMPUTE_EXIT_ON_MSG(image_loader == nullptr, "Unsupported image type");
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000264
Jenkins52ba29e2018-08-29 15:32:11 +0000265 // Open image file
266 image_loader->open(_filename);
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100267
Jenkins52ba29e2018-08-29 15:32:11 +0000268 // 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 }
Jenkins49b8f902020-11-27 12:49:11 +0000275
Jenkins0e205f72019-11-28 16:53:35 +0000276 ARM_COMPUTE_EXIT_ON_MSG_VAR(image_loader->width() != permuted_shape.x() || image_loader->height() != permuted_shape.y(),
Kevin DuBoisc2a18252021-02-23 17:55:18 -0800277 "Failed to load image file: dimensions [%d,%d] not correct, expected [%zu ,%zu ].",
Jenkins0e205f72019-11-28 16:53:35 +0000278 image_loader->width(), image_loader->height(), permuted_shape.x(), permuted_shape.y());
Jenkins52ba29e2018-08-29 15:32:11 +0000279
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 }
Anthony Barbier06ea0482018-02-22 15:45:35 +0000288 }
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100289
Jenkins52ba29e2018-08-29 15:32:11 +0000290 _already_loaded = !_already_loaded;
291 return _already_loaded;
292}
293
294ValidationInputAccessor::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 {
Jenkins0e205f72019-11-28 16:53:35 +0000328 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", image_list.c_str(), e.what());
Jenkins52ba29e2018-08-29 15:32:11 +0000329 }
330}
331
332bool 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 }
Jenkins49b8f902020-11-27 12:49:11 +0000352
Jenkins0e205f72019-11-28 16:53:35 +0000353 ARM_COMPUTE_EXIT_ON_MSG_VAR(jpeg.width() != permuted_shape.x() || jpeg.height() != permuted_shape.y(),
Kevin DuBoisc2a18252021-02-23 17:55:18 -0800354 "Failed to load image file: dimensions [%d,%d] not correct, expected [%zu,%zu ].",
Jenkins0e205f72019-11-28 16:53:35 +0000355 jpeg.width(), jpeg.height(), permuted_shape.x(), permuted_shape.y());
Jenkins52ba29e2018-08-29 15:32:11 +0000356
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
370ValidationOutputAccessor::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 {
Jenkins0e205f72019-11-28 16:53:35 +0000402 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", image_list.c_str(), e.what());
Jenkins52ba29e2018-08-29 15:32:11 +0000403 }
404}
405
406void ValidationOutputAccessor::reset()
407{
408 _offset = 0;
409 _positive_samples_top1 = 0;
410 _positive_samples_top5 = 0;
411}
412
413bool 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;
Jenkins0e205f72019-11-28 16:53:35 +0000425 case DataType::F16:
426 tensor_results = access_predictions_tensor<half>(tensor);
427 break;
Jenkins52ba29e2018-08-29 15:32:11 +0000428 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
452template <typename T>
453std::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
474void 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
487void 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;
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100497}
498
Jenkins514be652019-02-28 12:25:18 +0000499DetectionOutputAccessor::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 {
Jenkins0e205f72019-11-28 16:53:35 +0000518 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", labels_path.c_str(), e.what());
Jenkins514be652019-02-28 12:25:18 +0000519 }
520}
521
522template <typename T>
523void 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
554bool 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
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100570TopNPredictionsAccessor::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 {
Jenkins0e205f72019-11-28 16:53:35 +0000589 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", labels_path.c_str(), e.what());
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100590 }
591}
592
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000593template <typename T>
594void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100595{
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100596 // Get the predicted class
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000597 std::vector<T> classes_prob;
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100598 std::vector<size_t> index;
599
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000600 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100601 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)
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000621 << +classes_prob[index.at(i)]
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100622 << " - [id = " << index.at(i) << "]"
623 << ", " << _labels[index.at(i)] << std::endl;
624 }
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000625}
626
627bool 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 }
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100643
644 return false;
645}
646
Kaizenbf8b01d2017-10-12 14:26:51 +0100647RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
648 : _lower(lower), _upper(upper), _seed(seed)
649{
650}
651
652template <typename T, typename D>
653void RandomAccessor::fill(ITensor &tensor, D &&distribution)
654{
655 std::mt19937 gen(_seed);
656
Anthony Barbier06ea0482018-02-22 15:45:35 +0000657 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Kaizenbf8b01d2017-10-12 14:26:51 +0100658 {
659 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
660 {
Jenkinsb9abeae2018-11-22 11:58:08 +0000661 const auto value = static_cast<T>(distribution(gen));
Kaizenbf8b01d2017-10-12 14:26:51 +0100662 *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 {
Jenkinsb9abeae2018-11-22 11:58:08 +0000673 const auto value = static_cast<T>(distribution(gen));
Kaizenbf8b01d2017-10-12 14:26:51 +0100674 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
675 });
676 }
677}
678
679bool RandomAccessor::access_tensor(ITensor &tensor)
680{
681 switch(tensor.info()->data_type())
682 {
Jenkins4ba87db2019-05-23 17:11:51 +0100683 case DataType::QASYMM8:
Kaizenbf8b01d2017-10-12 14:26:51 +0100684 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:
Kaizenbf8b01d2017-10-12 14:26:51 +0100691 {
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:
Kaizenbf8b01d2017-10-12 14:26:51 +0100703 {
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 {
Jenkins4ba87db2019-05-23 17:11:51 +0100734 std::uniform_real_distribution<float> distribution_f16(_lower.get<half>(), _upper.get<half>());
Jenkinsb9abeae2018-11-22 11:58:08 +0000735 fill<half>(tensor, distribution_f16);
Kaizenbf8b01d2017-10-12 14:26:51 +0100736 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
Jenkinsb3a371b2018-05-23 11:36:53 +0100756NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
Jenkins52ba29e2018-08-29 15:32:11 +0000757 : _already_loaded(false), _filename(std::move(filename)), _file_layout(file_layout)
Kaizen8938bd32017-09-28 14:38:23 +0100758{
759}
760
761bool NumPyBinLoader::access_tensor(ITensor &tensor)
762{
Jenkins52ba29e2018-08-29 15:32:11 +0000763 if(!_already_loaded)
Kaizen8938bd32017-09-28 14:38:23 +0100764 {
Jenkins52ba29e2018-08-29 15:32:11 +0000765 utils::NPYLoader loader;
766 loader.open(_filename, _file_layout);
767 loader.fill_tensor(tensor);
Anthony Barbier06ea0482018-02-22 15:45:35 +0000768 }
769
Jenkins52ba29e2018-08-29 15:32:11 +0000770 _already_loaded = !_already_loaded;
771 return _already_loaded;
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000772}