blob: dad9aed6a5a2581b245196efaa1ace9112443f0b [file] [log] [blame]
Anthony Barbier2a07e182017-08-04 18:20:27 +01001/*
John Kesapidesfb68ca12019-01-21 14:13:27 +00002 * Copyright (c) 2017-2019 ARM Limited.
Anthony Barbier2a07e182017-08-04 18:20:27 +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"
hakanardof36ac352018-02-16 10:06:34 +010026
Georgios Pinitascac13b12018-04-27 19:07:19 +010027#include "arm_compute/core/Helpers.h"
28#include "arm_compute/core/Types.h"
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010029#include "arm_compute/graph/Logger.h"
hakanardof36ac352018-02-16 10:06:34 +010030#include "arm_compute/runtime/SubTensor.h"
Georgios Pinitas7c3b9242018-06-21 19:01:25 +010031#include "utils/ImageLoader.h"
Anthony Barbier2a07e182017-08-04 18:20:27 +010032#include "utils/Utils.h"
33
Gian Marco44ec2e72017-10-19 14:13:38 +010034#include <iomanip>
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010035#include <limits>
Anthony Barbier2a07e182017-08-04 18:20:27 +010036
37using namespace arm_compute::graph_utils;
38
Georgios Pinitascac13b12018-04-27 19:07:19 +010039namespace
40{
Anthony Barbier4ead11a2018-08-06 09:25:36 +010041std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_parameters(const arm_compute::TensorShape &shape,
Georgios Pinitascac13b12018-04-27 19:07:19 +010042 arm_compute::DataLayout data_layout)
43{
44 // Set permutation parameters if needed
45 arm_compute::TensorShape permuted_shape = shape;
46 arm_compute::PermutationVector perm;
47 // Permute only if num_dimensions greater than 2
48 if(shape.num_dimensions() > 2)
49 {
50 perm = (data_layout == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
51
52 arm_compute::PermutationVector perm_shape = (data_layout == arm_compute::DataLayout::NCHW) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
53 arm_compute::permute(permuted_shape, perm_shape);
54 }
55
56 return std::make_pair(permuted_shape, perm);
57}
58} // namespace
59
Georgios Pinitasbe2772a2018-08-17 15:33:39 +010060TFPreproccessor::TFPreproccessor(float min_range, float max_range)
61 : _min_range(min_range), _max_range(max_range)
62{
63}
Georgios Pinitas140fdc72018-02-16 11:42:38 +000064void TFPreproccessor::preprocess(ITensor &tensor)
65{
66 Window window;
67 window.use_tensor_dimensions(tensor.info()->tensor_shape());
68
Georgios Pinitasbe2772a2018-08-17 15:33:39 +010069 const float range = _max_range - _min_range;
70
Georgios Pinitas140fdc72018-02-16 11:42:38 +000071 execute_window_loop(window, [&](const Coordinates & id)
72 {
73 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id));
Georgios Pinitasbe2772a2018-08-17 15:33:39 +010074 float res = value / 255.f; // Normalize to [0, 1]
75 res = res * range + _min_range; // Map to [min_range, max_range]
Georgios Pinitas140fdc72018-02-16 11:42:38 +000076 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = res;
77 });
78}
79
Georgios Pinitasb54c6442019-04-03 13:18:14 +010080CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr, float scale)
81 : _mean(mean), _bgr(bgr), _scale(scale)
Georgios Pinitas140fdc72018-02-16 11:42:38 +000082{
83 if(_bgr)
84 {
85 std::swap(_mean[0], _mean[2]);
86 }
87}
88
89void CaffePreproccessor::preprocess(ITensor &tensor)
90{
91 Window window;
92 window.use_tensor_dimensions(tensor.info()->tensor_shape());
93
Georgios Pinitas7d66a8e2018-07-17 12:28:42 +010094 const int channel_idx = get_data_layout_dimension_index(tensor.info()->data_layout(), DataLayoutDimension::CHANNEL);
95
Georgios Pinitas140fdc72018-02-16 11:42:38 +000096 execute_window_loop(window, [&](const Coordinates & id)
97 {
Georgios Pinitas7d66a8e2018-07-17 12:28:42 +010098 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - _mean[id[channel_idx]];
Pablo Tello32521432018-11-15 14:43:10 +000099 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value * _scale;
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000100 });
101}
102
Anthony Barbier2a07e182017-08-04 18:20:27 +0100103PPMWriter::PPMWriter(std::string name, unsigned int maximum)
104 : _name(std::move(name)), _iterator(0), _maximum(maximum)
105{
106}
107
108bool PPMWriter::access_tensor(ITensor &tensor)
109{
110 std::stringstream ss;
111 ss << _name << _iterator << ".ppm";
Gian Marco44ec2e72017-10-19 14:13:38 +0100112
113 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100114
115 _iterator++;
116 if(_maximum == 0)
117 {
118 return true;
119 }
120 return _iterator < _maximum;
121}
122
123DummyAccessor::DummyAccessor(unsigned int maximum)
124 : _iterator(0), _maximum(maximum)
125{
126}
127
128bool DummyAccessor::access_tensor(ITensor &tensor)
129{
130 ARM_COMPUTE_UNUSED(tensor);
Anthony Barbier8a042112018-08-21 18:16:53 +0100131 bool ret = _maximum == 0 || _iterator < _maximum;
Anthony Barbier2a07e182017-08-04 18:20:27 +0100132 if(_iterator == _maximum)
133 {
134 _iterator = 0;
135 }
136 else
137 {
138 _iterator++;
139 }
140 return ret;
141}
142
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100143NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, std::ostream &output_stream)
144 : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
145{
146 NumPyBinLoader loader(_filename);
147
148 TensorInfo info(shape, 1, data_type);
149 _npy_tensor.allocator()->init(info);
150 _npy_tensor.allocator()->allocate();
151
152 loader.access_tensor(_npy_tensor);
153}
154
155template <typename T>
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000156void NumPyAccessor::access_numpy_tensor(ITensor &tensor, T tolerance)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100157{
Gian Marco Iodicead486e22018-08-07 17:17:06 +0100158 const int num_elements = tensor.info()->tensor_shape().total_size();
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000159 int num_mismatches = utils::compare_tensor<T>(tensor, _npy_tensor, tolerance);
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100160 float percentage_mismatches = static_cast<float>(num_mismatches) / num_elements;
161
162 _output_stream << "Results: " << 100.f - (percentage_mismatches * 100) << " % matches with the provided output[" << _filename << "]." << std::endl;
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000163 _output_stream << " " << num_elements - num_mismatches << " out of " << num_elements << " matches with the provided output[" << _filename << "]." << std::endl
164 << std::endl;
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100165}
166
167bool NumPyAccessor::access_tensor(ITensor &tensor)
168{
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000169 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100170 ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
171
172 switch(tensor.info()->data_type())
173 {
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000174 case DataType::QASYMM8:
175 access_numpy_tensor<qasymm8_t>(tensor, 0);
176 break;
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100177 case DataType::F32:
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000178 access_numpy_tensor<float>(tensor, 0.0001f);
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100179 break;
180 default:
181 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
182 }
183
184 return false;
185}
186
Isabella Gottardi2ea37612019-07-16 11:48:51 +0100187SaveNumPyAccessor::SaveNumPyAccessor(std::string npy_name, const bool is_fortran)
188 : _npy_name(std::move(npy_name)), _is_fortran(is_fortran)
189{
190}
191
192bool SaveNumPyAccessor::access_tensor(ITensor &tensor)
193{
194 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
195
196 utils::save_to_npy(tensor, _npy_name, _is_fortran);
197
198 return false;
199}
200
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100201ImageAccessor::ImageAccessor(std::string filename, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
Anthony Barbier8a042112018-08-21 18:16:53 +0100202 : _already_loaded(false), _filename(std::move(filename)), _bgr(bgr), _preprocessor(std::move(preprocessor))
Gian Marco44ec2e72017-10-19 14:13:38 +0100203{
204}
205
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100206bool ImageAccessor::access_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100207{
Anthony Barbier8a042112018-08-21 18:16:53 +0100208 if(!_already_loaded)
Georgios Pinitascac13b12018-04-27 19:07:19 +0100209 {
Anthony Barbier8a042112018-08-21 18:16:53 +0100210 auto image_loader = utils::ImageLoaderFactory::create(_filename);
211 ARM_COMPUTE_EXIT_ON_MSG(image_loader == nullptr, "Unsupported image type");
Isabella Gottardia4c61882017-11-03 12:11:55 +0000212
Anthony Barbier8a042112018-08-21 18:16:53 +0100213 // Open image file
214 image_loader->open(_filename);
Gian Marco44ec2e72017-10-19 14:13:38 +0100215
Anthony Barbier8a042112018-08-21 18:16:53 +0100216 // Get permutated shape and permutation parameters
217 TensorShape permuted_shape = tensor.info()->tensor_shape();
218 arm_compute::PermutationVector perm;
219 if(tensor.info()->data_layout() != DataLayout::NCHW)
220 {
221 std::tie(permuted_shape, perm) = compute_permutation_parameters(tensor.info()->tensor_shape(), tensor.info()->data_layout());
222 }
223 ARM_COMPUTE_EXIT_ON_MSG(image_loader->width() != permuted_shape.x() || image_loader->height() != permuted_shape.y(),
224 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].",
225 image_loader->width(), image_loader->height(), permuted_shape.x(), permuted_shape.y());
226
227 // Fill the tensor with the PPM content (BGR)
228 image_loader->fill_planar_tensor(tensor, _bgr);
229
230 // Preprocess tensor
231 if(_preprocessor)
232 {
233 _preprocessor->preprocess(tensor);
234 }
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000235 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100236
Anthony Barbier8a042112018-08-21 18:16:53 +0100237 _already_loaded = !_already_loaded;
238 return _already_loaded;
Gian Marco44ec2e72017-10-19 14:13:38 +0100239}
240
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100241ValidationInputAccessor::ValidationInputAccessor(const std::string &image_list,
242 std::string images_path,
243 std::unique_ptr<IPreprocessor> preprocessor,
244 bool bgr,
245 unsigned int start,
Anthony Barbier40606df2018-07-23 14:41:59 +0100246 unsigned int end,
247 std::ostream &output_stream)
248 : _path(std::move(images_path)), _images(), _preprocessor(std::move(preprocessor)), _bgr(bgr), _offset(0), _output_stream(output_stream)
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100249{
Anthony Barbier40606df2018-07-23 14:41:59 +0100250 ARM_COMPUTE_EXIT_ON_MSG(start > end, "Invalid validation range!");
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100251
252 std::ifstream ifs;
253 try
254 {
255 ifs.exceptions(std::ifstream::badbit);
256 ifs.open(image_list, std::ios::in | std::ios::binary);
257
258 // Parse image names
259 unsigned int counter = 0;
260 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
261 {
262 // Add image to process if withing range
263 if(counter >= start)
264 {
265 std::stringstream linestream(line);
266 std::string image_name;
267
268 linestream >> image_name;
269 _images.emplace_back(std::move(image_name));
270 }
271 }
272 }
273 catch(const std::ifstream::failure &e)
274 {
275 ARM_COMPUTE_ERROR("Accessing %s: %s", image_list.c_str(), e.what());
276 }
277}
278
279bool ValidationInputAccessor::access_tensor(arm_compute::ITensor &tensor)
280{
281 bool ret = _offset < _images.size();
282 if(ret)
283 {
284 utils::JPEGLoader jpeg;
285
286 // Open JPEG file
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100287 std::string image_name = _path + _images[_offset++];
288 jpeg.open(image_name);
Anthony Barbier40606df2018-07-23 14:41:59 +0100289 _output_stream << "[" << _offset << "/" << _images.size() << "] Validating " << image_name << std::endl;
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100290
291 // Get permutated shape and permutation parameters
292 TensorShape permuted_shape = tensor.info()->tensor_shape();
293 arm_compute::PermutationVector perm;
294 if(tensor.info()->data_layout() != DataLayout::NCHW)
295 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100296 std::tie(permuted_shape, perm) = compute_permutation_parameters(tensor.info()->tensor_shape(),
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100297 tensor.info()->data_layout());
298 }
Anthony Barbier40606df2018-07-23 14:41:59 +0100299 ARM_COMPUTE_EXIT_ON_MSG(jpeg.width() != permuted_shape.x() || jpeg.height() != permuted_shape.y(),
300 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].",
301 jpeg.width(), jpeg.height(), permuted_shape.x(), permuted_shape.y());
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100302
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100303 // Fill the tensor with the JPEG content (BGR)
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100304 jpeg.fill_planar_tensor(tensor, _bgr);
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100305
306 // Preprocess tensor
307 if(_preprocessor)
308 {
309 _preprocessor->preprocess(tensor);
310 }
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100311 }
312
313 return ret;
314}
315
Georgios Pinitas7908de72018-06-27 12:34:20 +0100316ValidationOutputAccessor::ValidationOutputAccessor(const std::string &image_list,
Georgios Pinitas7908de72018-06-27 12:34:20 +0100317 std::ostream &output_stream,
318 unsigned int start,
319 unsigned int end)
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100320 : _results(), _output_stream(output_stream), _offset(0), _positive_samples_top1(0), _positive_samples_top5(0)
Georgios Pinitas7908de72018-06-27 12:34:20 +0100321{
Anthony Barbier40606df2018-07-23 14:41:59 +0100322 ARM_COMPUTE_EXIT_ON_MSG(start > end, "Invalid validation range!");
Georgios Pinitas7908de72018-06-27 12:34:20 +0100323
324 std::ifstream ifs;
325 try
326 {
327 ifs.exceptions(std::ifstream::badbit);
328 ifs.open(image_list, std::ios::in | std::ios::binary);
329
330 // Parse image correctly classified labels
331 unsigned int counter = 0;
332 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
333 {
334 // Add label if within range
335 if(counter >= start)
336 {
337 std::stringstream linestream(line);
338 std::string image_name;
339 int result;
340
341 linestream >> image_name >> result;
342 _results.emplace_back(result);
343 }
344 }
345 }
346 catch(const std::ifstream::failure &e)
347 {
348 ARM_COMPUTE_ERROR("Accessing %s: %s", image_list.c_str(), e.what());
349 }
350}
351
352void ValidationOutputAccessor::reset()
353{
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100354 _offset = 0;
355 _positive_samples_top1 = 0;
356 _positive_samples_top5 = 0;
Georgios Pinitas7908de72018-06-27 12:34:20 +0100357}
358
359bool ValidationOutputAccessor::access_tensor(arm_compute::ITensor &tensor)
360{
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100361 bool ret = _offset < _results.size();
362 if(ret)
Georgios Pinitas7908de72018-06-27 12:34:20 +0100363 {
364 // Get results
365 std::vector<size_t> tensor_results;
366 switch(tensor.info()->data_type())
367 {
368 case DataType::QASYMM8:
369 tensor_results = access_predictions_tensor<uint8_t>(tensor);
370 break;
371 case DataType::F32:
372 tensor_results = access_predictions_tensor<float>(tensor);
373 break;
374 default:
375 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
376 }
377
378 // Check if tensor results are within top-n accuracy
379 size_t correct_label = _results[_offset++];
Georgios Pinitas7908de72018-06-27 12:34:20 +0100380
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100381 aggregate_sample(tensor_results, _positive_samples_top1, 1, correct_label);
382 aggregate_sample(tensor_results, _positive_samples_top5, 5, correct_label);
Georgios Pinitas7908de72018-06-27 12:34:20 +0100383 }
384
385 // Report top_n accuracy
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100386 if(_offset >= _results.size())
Georgios Pinitas7908de72018-06-27 12:34:20 +0100387 {
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100388 report_top_n(1, _results.size(), _positive_samples_top1);
389 report_top_n(5, _results.size(), _positive_samples_top5);
Georgios Pinitas7908de72018-06-27 12:34:20 +0100390 }
391
392 return ret;
393}
394
395template <typename T>
396std::vector<size_t> ValidationOutputAccessor::access_predictions_tensor(arm_compute::ITensor &tensor)
397{
398 // Get the predicted class
399 std::vector<size_t> index;
400
401 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
402 const size_t num_classes = tensor.info()->dimension(0);
403
404 index.resize(num_classes);
405
406 // Sort results
407 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
408 std::sort(std::begin(index), std::end(index),
409 [&](size_t a, size_t b)
410 {
411 return output_net[a] > output_net[b];
412 });
413
414 return index;
415}
416
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100417void ValidationOutputAccessor::aggregate_sample(const std::vector<size_t> &res, size_t &positive_samples, size_t top_n, size_t correct_label)
418{
419 auto is_valid_label = [correct_label](size_t label)
420 {
421 return label == correct_label;
422 };
423
424 if(std::any_of(std::begin(res), std::begin(res) + top_n, is_valid_label))
425 {
426 ++positive_samples;
427 }
428}
429
430void ValidationOutputAccessor::report_top_n(size_t top_n, size_t total_samples, size_t positive_samples)
431{
432 size_t negative_samples = total_samples - positive_samples;
433 float accuracy = positive_samples / static_cast<float>(total_samples);
434
435 _output_stream << "----------Top " << top_n << " accuracy ----------" << std::endl
436 << std::endl;
437 _output_stream << "Positive samples : " << positive_samples << std::endl;
438 _output_stream << "Negative samples : " << negative_samples << std::endl;
439 _output_stream << "Accuracy : " << accuracy << std::endl;
440}
441
Isabella Gottardi7234ed82018-11-27 08:51:10 +0000442DetectionOutputAccessor::DetectionOutputAccessor(const std::string &labels_path, std::vector<TensorShape> &imgs_tensor_shapes, std::ostream &output_stream)
443 : _labels(), _tensor_shapes(std::move(imgs_tensor_shapes)), _output_stream(output_stream)
444{
445 _labels.clear();
446
447 std::ifstream ifs;
448
449 try
450 {
451 ifs.exceptions(std::ifstream::badbit);
452 ifs.open(labels_path, std::ios::in | std::ios::binary);
453
454 for(std::string line; !std::getline(ifs, line).fail();)
455 {
456 _labels.emplace_back(line);
457 }
458 }
459 catch(const std::ifstream::failure &e)
460 {
461 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
462 }
463}
464
465template <typename T>
466void DetectionOutputAccessor::access_predictions_tensor(ITensor &tensor)
467{
468 const size_t num_detection = tensor.info()->valid_region().shape.y();
469 const auto output_prt = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
470
471 if(num_detection > 0)
472 {
473 _output_stream << "---------------------- Detections ----------------------" << std::endl
474 << std::endl;
475
476 _output_stream << std::left << std::setprecision(4) << std::setw(8) << "Image | " << std::setw(8) << "Label | " << std::setw(12) << "Confidence | "
477 << "[ xmin, ymin, xmax, ymax ]" << std::endl;
478
479 for(size_t i = 0; i < num_detection; ++i)
480 {
481 auto im = static_cast<const int>(output_prt[i * 7]);
482 _output_stream << std::setw(8) << im << std::setw(8)
483 << _labels[output_prt[i * 7 + 1]] << std::setw(12) << output_prt[i * 7 + 2]
484 << " [" << (output_prt[i * 7 + 3] * _tensor_shapes[im].x())
485 << ", " << (output_prt[i * 7 + 4] * _tensor_shapes[im].y())
486 << ", " << (output_prt[i * 7 + 5] * _tensor_shapes[im].x())
487 << ", " << (output_prt[i * 7 + 6] * _tensor_shapes[im].y())
488 << "]" << std::endl;
489 }
490 }
491 else
492 {
493 _output_stream << "No detection found." << std::endl;
494 }
495}
496
497bool DetectionOutputAccessor::access_tensor(ITensor &tensor)
498{
499 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
500
501 switch(tensor.info()->data_type())
502 {
503 case DataType::F32:
504 access_predictions_tensor<float>(tensor);
505 break;
506 default:
507 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
508 }
509
510 return false;
511}
512
Gian Marco44ec2e72017-10-19 14:13:38 +0100513TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
514 : _labels(), _output_stream(output_stream), _top_n(top_n)
515{
516 _labels.clear();
517
518 std::ifstream ifs;
519
520 try
521 {
522 ifs.exceptions(std::ifstream::badbit);
523 ifs.open(labels_path, std::ios::in | std::ios::binary);
524
525 for(std::string line; !std::getline(ifs, line).fail();)
526 {
527 _labels.emplace_back(line);
528 }
529 }
530 catch(const std::ifstream::failure &e)
531 {
532 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
533 }
534}
535
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000536template <typename T>
537void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100538{
Gian Marco44ec2e72017-10-19 14:13:38 +0100539 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000540 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100541 std::vector<size_t> index;
542
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000543 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100544 const size_t num_classes = tensor.info()->dimension(0);
545
546 classes_prob.resize(num_classes);
547 index.resize(num_classes);
548
549 std::copy(output_net, output_net + num_classes, classes_prob.begin());
550
551 // Sort results
552 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
553 std::sort(std::begin(index), std::end(index),
554 [&](size_t a, size_t b)
555 {
556 return classes_prob[a] > classes_prob[b];
557 });
558
559 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
560 << std::endl;
561 for(size_t i = 0; i < _top_n; ++i)
562 {
563 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000564 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100565 << " - [id = " << index.at(i) << "]"
566 << ", " << _labels[index.at(i)] << std::endl;
567 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000568}
569
570bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
571{
572 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
573 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
574
575 switch(tensor.info()->data_type())
576 {
577 case DataType::QASYMM8:
578 access_predictions_tensor<uint8_t>(tensor);
579 break;
580 case DataType::F32:
581 access_predictions_tensor<float>(tensor);
582 break;
583 default:
584 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
585 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100586
587 return false;
588}
589
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100590RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
591 : _lower(lower), _upper(upper), _seed(seed)
592{
593}
594
595template <typename T, typename D>
596void RandomAccessor::fill(ITensor &tensor, D &&distribution)
597{
598 std::mt19937 gen(_seed);
599
hakanardof36ac352018-02-16 10:06:34 +0100600 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100601 {
602 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
603 {
Michele Di Giorgio88731f02018-09-25 16:49:27 +0100604 const auto value = static_cast<T>(distribution(gen));
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100605 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
606 }
607 }
608 else
609 {
610 // If tensor has padding accessing tensor elements through execution window.
611 Window window;
612 window.use_tensor_dimensions(tensor.info()->tensor_shape());
613
614 execute_window_loop(window, [&](const Coordinates & id)
615 {
Michele Di Giorgio88731f02018-09-25 16:49:27 +0100616 const auto value = static_cast<T>(distribution(gen));
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100617 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
618 });
619 }
620}
621
622bool RandomAccessor::access_tensor(ITensor &tensor)
623{
624 switch(tensor.info()->data_type())
625 {
John Kesapidesfb68ca12019-01-21 14:13:27 +0000626 case DataType::QASYMM8:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100627 case DataType::U8:
628 {
629 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
630 fill<uint8_t>(tensor, distribution_u8);
631 break;
632 }
633 case DataType::S8:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100634 {
635 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
636 fill<int8_t>(tensor, distribution_s8);
637 break;
638 }
639 case DataType::U16:
640 {
641 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
642 fill<uint16_t>(tensor, distribution_u16);
643 break;
644 }
645 case DataType::S16:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100646 {
647 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
648 fill<int16_t>(tensor, distribution_s16);
649 break;
650 }
651 case DataType::U32:
652 {
653 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
654 fill<uint32_t>(tensor, distribution_u32);
655 break;
656 }
657 case DataType::S32:
658 {
659 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
660 fill<int32_t>(tensor, distribution_s32);
661 break;
662 }
663 case DataType::U64:
664 {
665 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
666 fill<uint64_t>(tensor, distribution_u64);
667 break;
668 }
669 case DataType::S64:
670 {
671 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
672 fill<int64_t>(tensor, distribution_s64);
673 break;
674 }
675 case DataType::F16:
676 {
John Kesapidesfb68ca12019-01-21 14:13:27 +0000677 std::uniform_real_distribution<float> distribution_f16(_lower.get<half>(), _upper.get<half>());
Michele Di Giorgio88731f02018-09-25 16:49:27 +0100678 fill<half>(tensor, distribution_f16);
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100679 break;
680 }
681 case DataType::F32:
682 {
683 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
684 fill<float>(tensor, distribution_f32);
685 break;
686 }
687 case DataType::F64:
688 {
689 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
690 fill<double>(tensor, distribution_f64);
691 break;
692 }
693 default:
694 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
695 }
696 return true;
697}
698
Georgios Pinitascac13b12018-04-27 19:07:19 +0100699NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
Anthony Barbier8a042112018-08-21 18:16:53 +0100700 : _already_loaded(false), _filename(std::move(filename)), _file_layout(file_layout)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100701{
702}
703
704bool NumPyBinLoader::access_tensor(ITensor &tensor)
705{
Anthony Barbier8a042112018-08-21 18:16:53 +0100706 if(!_already_loaded)
707 {
708 utils::NPYLoader loader;
709 loader.open(_filename, _file_layout);
710 loader.fill_tensor(tensor);
711 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100712
Anthony Barbier8a042112018-08-21 18:16:53 +0100713 _already_loaded = !_already_loaded;
714 return _already_loaded;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000715}