blob: e543cabea96cc950884f16b7cf233cf612f00a5a [file] [log] [blame]
Anthony Barbier2a07e182017-08-04 18:20:27 +01001/*
Sheri Zhangd80792a2020-11-05 10:43:37 +00002 * Copyright (c) 2017-2020 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"
Michalis Spyrou6bff1952019-10-02 17:22:11 +010031
32#pragma GCC diagnostic push
33#pragma GCC diagnostic ignored "-Wunused-parameter"
Georgios Pinitas7c3b9242018-06-21 19:01:25 +010034#include "utils/ImageLoader.h"
Michalis Spyrou6bff1952019-10-02 17:22:11 +010035#pragma GCC diagnostic pop
Anthony Barbier2a07e182017-08-04 18:20:27 +010036#include "utils/Utils.h"
37
Michalis Spyrou7c60c992019-10-10 14:33:47 +010038#include <inttypes.h>
Gian Marco44ec2e72017-10-19 14:13:38 +010039#include <iomanip>
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010040#include <limits>
Anthony Barbier2a07e182017-08-04 18:20:27 +010041
42using namespace arm_compute::graph_utils;
43
Georgios Pinitascac13b12018-04-27 19:07:19 +010044namespace
45{
Anthony Barbier4ead11a2018-08-06 09:25:36 +010046std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_parameters(const arm_compute::TensorShape &shape,
Georgios Pinitascac13b12018-04-27 19:07:19 +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
Georgios Pinitasbe2772a2018-08-17 15:33:39 +010065TFPreproccessor::TFPreproccessor(float min_range, float max_range)
66 : _min_range(min_range), _max_range(max_range)
67{
68}
Georgios Pinitas140fdc72018-02-16 11:42:38 +000069void TFPreproccessor::preprocess(ITensor &tensor)
70{
giuros01351bd132019-08-23 14:27:30 +010071 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{
Georgios Pinitas140fdc72018-02-16 11:42:38 +000088 Window window;
89 window.use_tensor_dimensions(tensor.info()->tensor_shape());
90
Georgios Pinitasbe2772a2018-08-17 15:33:39 +010091 const float range = _max_range - _min_range;
Georgios Pinitas140fdc72018-02-16 11:42:38 +000092 execute_window_loop(window, [&](const Coordinates & id)
93 {
giuros01351bd132019-08-23 14:27:30 +010094 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;
Georgios Pinitas140fdc72018-02-16 11:42:38 +000098 });
99}
100
Georgios Pinitasb54c6442019-04-03 13:18:14 +0100101CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr, float scale)
102 : _mean(mean), _bgr(bgr), _scale(scale)
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000103{
104 if(_bgr)
105 {
106 std::swap(_mean[0], _mean[2]);
107 }
108}
109
110void CaffePreproccessor::preprocess(ITensor &tensor)
111{
giuros01351bd132019-08-23 14:27:30 +0100112 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{
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000129 Window window;
130 window.use_tensor_dimensions(tensor.info()->tensor_shape());
Georgios Pinitas7d66a8e2018-07-17 12:28:42 +0100131 const int channel_idx = get_data_layout_dimension_index(tensor.info()->data_layout(), DataLayoutDimension::CHANNEL);
132
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000133 execute_window_loop(window, [&](const Coordinates & id)
134 {
giuros01351bd132019-08-23 14:27:30 +0100135 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);
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000137 });
138}
139
Anthony Barbier2a07e182017-08-04 18:20:27 +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";
Gian Marco44ec2e72017-10-19 14:13:38 +0100149
150 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +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);
Anthony Barbier8a042112018-08-21 18:16:53 +0100168 bool ret = _maximum == 0 || _iterator < _maximum;
Anthony Barbier2a07e182017-08-04 18:20:27 +0100169 if(_iterator == _maximum)
170 {
171 _iterator = 0;
172 }
173 else
174 {
175 _iterator++;
176 }
177 return ret;
178}
179
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000180NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, DataLayout data_layout, std::ostream &output_stream)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100181 : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
182{
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000183 NumPyBinLoader loader(_filename, data_layout);
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100184
185 TensorInfo info(shape, 1, data_type);
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000186 info.set_data_layout(data_layout);
187
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100188 _npy_tensor.allocator()->init(info);
189 _npy_tensor.allocator()->allocate();
190
191 loader.access_tensor(_npy_tensor);
192}
193
194template <typename T>
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000195void NumPyAccessor::access_numpy_tensor(ITensor &tensor, T tolerance)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100196{
Gian Marco Iodicead486e22018-08-07 17:17:06 +0100197 const int num_elements = tensor.info()->tensor_shape().total_size();
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000198 int num_mismatches = utils::compare_tensor<T>(tensor, _npy_tensor, tolerance);
Isabella Gottardi88d5b222018-04-06 12:24:55 +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;
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000202 _output_stream << " " << num_elements - num_mismatches << " out of " << num_elements << " matches with the provided output[" << _filename << "]." << std::endl
203 << std::endl;
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100204}
205
206bool NumPyAccessor::access_tensor(ITensor &tensor)
207{
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000208 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100209 ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
210
211 switch(tensor.info()->data_type())
212 {
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000213 case DataType::QASYMM8:
214 access_numpy_tensor<qasymm8_t>(tensor, 0);
215 break;
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100216 case DataType::F32:
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000217 access_numpy_tensor<float>(tensor, 0.0001f);
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100218 break;
219 default:
220 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
221 }
222
223 return false;
224}
225
Isabella Gottardicd4e9ab2019-11-05 17:50:27 +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
Isabella Gottardi2ea37612019-07-16 11:48:51 +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
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100253ImageAccessor::ImageAccessor(std::string filename, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
Anthony Barbier8a042112018-08-21 18:16:53 +0100254 : _already_loaded(false), _filename(std::move(filename)), _bgr(bgr), _preprocessor(std::move(preprocessor))
Gian Marco44ec2e72017-10-19 14:13:38 +0100255{
256}
257
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100258bool ImageAccessor::access_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100259{
Anthony Barbier8a042112018-08-21 18:16:53 +0100260 if(!_already_loaded)
Georgios Pinitascac13b12018-04-27 19:07:19 +0100261 {
Anthony Barbier8a042112018-08-21 18:16:53 +0100262 auto image_loader = utils::ImageLoaderFactory::create(_filename);
263 ARM_COMPUTE_EXIT_ON_MSG(image_loader == nullptr, "Unsupported image type");
Isabella Gottardia4c61882017-11-03 12:11:55 +0000264
Anthony Barbier8a042112018-08-21 18:16:53 +0100265 // Open image file
266 image_loader->open(_filename);
Gian Marco44ec2e72017-10-19 14:13:38 +0100267
Anthony Barbier8a042112018-08-21 18:16:53 +0100268 // 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 }
Sheri Zhangd80792a2020-11-05 10:43:37 +0000275
276#ifdef __arm__
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100277 ARM_COMPUTE_EXIT_ON_MSG_VAR(image_loader->width() != permuted_shape.x() || image_loader->height() != permuted_shape.y(),
278 "Failed to load image file: dimensions [%d,%d] not correct, expected [%" PRIu32 ",%" PRIu32 "].",
279 image_loader->width(), image_loader->height(), permuted_shape.x(), permuted_shape.y());
Sheri Zhangd80792a2020-11-05 10:43:37 +0000280#else // __arm__
281 ARM_COMPUTE_EXIT_ON_MSG_VAR(image_loader->width() != permuted_shape.x() || image_loader->height() != permuted_shape.y(),
282 "Failed to load image file: dimensions [%d,%d] not correct, expected [%" PRIu64 ",%" PRIu64 "].",
283 image_loader->width(), image_loader->height(), permuted_shape.x(), permuted_shape.y());
284#endif // __arm__
Anthony Barbier8a042112018-08-21 18:16:53 +0100285
286 // Fill the tensor with the PPM content (BGR)
287 image_loader->fill_planar_tensor(tensor, _bgr);
288
289 // Preprocess tensor
290 if(_preprocessor)
291 {
292 _preprocessor->preprocess(tensor);
293 }
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000294 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100295
Anthony Barbier8a042112018-08-21 18:16:53 +0100296 _already_loaded = !_already_loaded;
297 return _already_loaded;
Gian Marco44ec2e72017-10-19 14:13:38 +0100298}
299
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100300ValidationInputAccessor::ValidationInputAccessor(const std::string &image_list,
301 std::string images_path,
302 std::unique_ptr<IPreprocessor> preprocessor,
303 bool bgr,
304 unsigned int start,
Anthony Barbier40606df2018-07-23 14:41:59 +0100305 unsigned int end,
306 std::ostream &output_stream)
307 : _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 +0100308{
Anthony Barbier40606df2018-07-23 14:41:59 +0100309 ARM_COMPUTE_EXIT_ON_MSG(start > end, "Invalid validation range!");
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100310
311 std::ifstream ifs;
312 try
313 {
314 ifs.exceptions(std::ifstream::badbit);
315 ifs.open(image_list, std::ios::in | std::ios::binary);
316
317 // Parse image names
318 unsigned int counter = 0;
319 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
320 {
321 // Add image to process if withing range
322 if(counter >= start)
323 {
324 std::stringstream linestream(line);
325 std::string image_name;
326
327 linestream >> image_name;
328 _images.emplace_back(std::move(image_name));
329 }
330 }
331 }
332 catch(const std::ifstream::failure &e)
333 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100334 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", image_list.c_str(), e.what());
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100335 }
336}
337
338bool ValidationInputAccessor::access_tensor(arm_compute::ITensor &tensor)
339{
340 bool ret = _offset < _images.size();
341 if(ret)
342 {
343 utils::JPEGLoader jpeg;
344
345 // Open JPEG file
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100346 std::string image_name = _path + _images[_offset++];
347 jpeg.open(image_name);
Anthony Barbier40606df2018-07-23 14:41:59 +0100348 _output_stream << "[" << _offset << "/" << _images.size() << "] Validating " << image_name << std::endl;
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100349
350 // Get permutated shape and permutation parameters
351 TensorShape permuted_shape = tensor.info()->tensor_shape();
352 arm_compute::PermutationVector perm;
353 if(tensor.info()->data_layout() != DataLayout::NCHW)
354 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100355 std::tie(permuted_shape, perm) = compute_permutation_parameters(tensor.info()->tensor_shape(),
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100356 tensor.info()->data_layout());
357 }
Sheri Zhangd80792a2020-11-05 10:43:37 +0000358
359#ifdef __arm__
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100360 ARM_COMPUTE_EXIT_ON_MSG_VAR(jpeg.width() != permuted_shape.x() || jpeg.height() != permuted_shape.y(),
361 "Failed to load image file: dimensions [%d,%d] not correct, expected [%" PRIu32 ",%" PRIu32 "].",
362 jpeg.width(), jpeg.height(), permuted_shape.x(), permuted_shape.y());
Sheri Zhangd80792a2020-11-05 10:43:37 +0000363#else // __arm__
364 ARM_COMPUTE_EXIT_ON_MSG_VAR(jpeg.width() != permuted_shape.x() || jpeg.height() != permuted_shape.y(),
365 "Failed to load image file: dimensions [%d,%d] not correct, expected [%" PRIu64 ",%" PRIu64 "].",
366 jpeg.width(), jpeg.height(), permuted_shape.x(), permuted_shape.y());
367#endif // __arm__
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100368
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100369 // Fill the tensor with the JPEG content (BGR)
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100370 jpeg.fill_planar_tensor(tensor, _bgr);
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100371
372 // Preprocess tensor
373 if(_preprocessor)
374 {
375 _preprocessor->preprocess(tensor);
376 }
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100377 }
378
379 return ret;
380}
381
Georgios Pinitas7908de72018-06-27 12:34:20 +0100382ValidationOutputAccessor::ValidationOutputAccessor(const std::string &image_list,
Georgios Pinitas7908de72018-06-27 12:34:20 +0100383 std::ostream &output_stream,
384 unsigned int start,
385 unsigned int end)
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100386 : _results(), _output_stream(output_stream), _offset(0), _positive_samples_top1(0), _positive_samples_top5(0)
Georgios Pinitas7908de72018-06-27 12:34:20 +0100387{
Anthony Barbier40606df2018-07-23 14:41:59 +0100388 ARM_COMPUTE_EXIT_ON_MSG(start > end, "Invalid validation range!");
Georgios Pinitas7908de72018-06-27 12:34:20 +0100389
390 std::ifstream ifs;
391 try
392 {
393 ifs.exceptions(std::ifstream::badbit);
394 ifs.open(image_list, std::ios::in | std::ios::binary);
395
396 // Parse image correctly classified labels
397 unsigned int counter = 0;
398 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
399 {
400 // Add label if within range
401 if(counter >= start)
402 {
403 std::stringstream linestream(line);
404 std::string image_name;
405 int result;
406
407 linestream >> image_name >> result;
408 _results.emplace_back(result);
409 }
410 }
411 }
412 catch(const std::ifstream::failure &e)
413 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100414 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", image_list.c_str(), e.what());
Georgios Pinitas7908de72018-06-27 12:34:20 +0100415 }
416}
417
418void ValidationOutputAccessor::reset()
419{
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100420 _offset = 0;
421 _positive_samples_top1 = 0;
422 _positive_samples_top5 = 0;
Georgios Pinitas7908de72018-06-27 12:34:20 +0100423}
424
425bool ValidationOutputAccessor::access_tensor(arm_compute::ITensor &tensor)
426{
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100427 bool ret = _offset < _results.size();
428 if(ret)
Georgios Pinitas7908de72018-06-27 12:34:20 +0100429 {
430 // Get results
431 std::vector<size_t> tensor_results;
432 switch(tensor.info()->data_type())
433 {
434 case DataType::QASYMM8:
435 tensor_results = access_predictions_tensor<uint8_t>(tensor);
436 break;
giuros01351bd132019-08-23 14:27:30 +0100437 case DataType::F16:
438 tensor_results = access_predictions_tensor<half>(tensor);
439 break;
Georgios Pinitas7908de72018-06-27 12:34:20 +0100440 case DataType::F32:
441 tensor_results = access_predictions_tensor<float>(tensor);
442 break;
443 default:
444 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
445 }
446
447 // Check if tensor results are within top-n accuracy
448 size_t correct_label = _results[_offset++];
Georgios Pinitas7908de72018-06-27 12:34:20 +0100449
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100450 aggregate_sample(tensor_results, _positive_samples_top1, 1, correct_label);
451 aggregate_sample(tensor_results, _positive_samples_top5, 5, correct_label);
Georgios Pinitas7908de72018-06-27 12:34:20 +0100452 }
453
454 // Report top_n accuracy
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100455 if(_offset >= _results.size())
Georgios Pinitas7908de72018-06-27 12:34:20 +0100456 {
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100457 report_top_n(1, _results.size(), _positive_samples_top1);
458 report_top_n(5, _results.size(), _positive_samples_top5);
Georgios Pinitas7908de72018-06-27 12:34:20 +0100459 }
460
461 return ret;
462}
463
464template <typename T>
465std::vector<size_t> ValidationOutputAccessor::access_predictions_tensor(arm_compute::ITensor &tensor)
466{
467 // Get the predicted class
468 std::vector<size_t> index;
469
470 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
471 const size_t num_classes = tensor.info()->dimension(0);
472
473 index.resize(num_classes);
474
475 // Sort results
476 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
477 std::sort(std::begin(index), std::end(index),
478 [&](size_t a, size_t b)
479 {
480 return output_net[a] > output_net[b];
481 });
482
483 return index;
484}
485
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100486void ValidationOutputAccessor::aggregate_sample(const std::vector<size_t> &res, size_t &positive_samples, size_t top_n, size_t correct_label)
487{
488 auto is_valid_label = [correct_label](size_t label)
489 {
490 return label == correct_label;
491 };
492
493 if(std::any_of(std::begin(res), std::begin(res) + top_n, is_valid_label))
494 {
495 ++positive_samples;
496 }
497}
498
499void ValidationOutputAccessor::report_top_n(size_t top_n, size_t total_samples, size_t positive_samples)
500{
501 size_t negative_samples = total_samples - positive_samples;
502 float accuracy = positive_samples / static_cast<float>(total_samples);
503
504 _output_stream << "----------Top " << top_n << " accuracy ----------" << std::endl
505 << std::endl;
506 _output_stream << "Positive samples : " << positive_samples << std::endl;
507 _output_stream << "Negative samples : " << negative_samples << std::endl;
508 _output_stream << "Accuracy : " << accuracy << std::endl;
509}
510
Isabella Gottardi7234ed82018-11-27 08:51:10 +0000511DetectionOutputAccessor::DetectionOutputAccessor(const std::string &labels_path, std::vector<TensorShape> &imgs_tensor_shapes, std::ostream &output_stream)
512 : _labels(), _tensor_shapes(std::move(imgs_tensor_shapes)), _output_stream(output_stream)
513{
514 _labels.clear();
515
516 std::ifstream ifs;
517
518 try
519 {
520 ifs.exceptions(std::ifstream::badbit);
521 ifs.open(labels_path, std::ios::in | std::ios::binary);
522
523 for(std::string line; !std::getline(ifs, line).fail();)
524 {
525 _labels.emplace_back(line);
526 }
527 }
528 catch(const std::ifstream::failure &e)
529 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100530 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", labels_path.c_str(), e.what());
Isabella Gottardi7234ed82018-11-27 08:51:10 +0000531 }
532}
533
534template <typename T>
535void DetectionOutputAccessor::access_predictions_tensor(ITensor &tensor)
536{
537 const size_t num_detection = tensor.info()->valid_region().shape.y();
538 const auto output_prt = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
539
540 if(num_detection > 0)
541 {
542 _output_stream << "---------------------- Detections ----------------------" << std::endl
543 << std::endl;
544
545 _output_stream << std::left << std::setprecision(4) << std::setw(8) << "Image | " << std::setw(8) << "Label | " << std::setw(12) << "Confidence | "
546 << "[ xmin, ymin, xmax, ymax ]" << std::endl;
547
548 for(size_t i = 0; i < num_detection; ++i)
549 {
550 auto im = static_cast<const int>(output_prt[i * 7]);
551 _output_stream << std::setw(8) << im << std::setw(8)
552 << _labels[output_prt[i * 7 + 1]] << std::setw(12) << output_prt[i * 7 + 2]
553 << " [" << (output_prt[i * 7 + 3] * _tensor_shapes[im].x())
554 << ", " << (output_prt[i * 7 + 4] * _tensor_shapes[im].y())
555 << ", " << (output_prt[i * 7 + 5] * _tensor_shapes[im].x())
556 << ", " << (output_prt[i * 7 + 6] * _tensor_shapes[im].y())
557 << "]" << std::endl;
558 }
559 }
560 else
561 {
562 _output_stream << "No detection found." << std::endl;
563 }
564}
565
566bool DetectionOutputAccessor::access_tensor(ITensor &tensor)
567{
568 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
569
570 switch(tensor.info()->data_type())
571 {
572 case DataType::F32:
573 access_predictions_tensor<float>(tensor);
574 break;
575 default:
576 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
577 }
578
579 return false;
580}
581
Gian Marco44ec2e72017-10-19 14:13:38 +0100582TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
583 : _labels(), _output_stream(output_stream), _top_n(top_n)
584{
585 _labels.clear();
586
587 std::ifstream ifs;
588
589 try
590 {
591 ifs.exceptions(std::ifstream::badbit);
592 ifs.open(labels_path, std::ios::in | std::ios::binary);
593
594 for(std::string line; !std::getline(ifs, line).fail();)
595 {
596 _labels.emplace_back(line);
597 }
598 }
599 catch(const std::ifstream::failure &e)
600 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100601 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", labels_path.c_str(), e.what());
Gian Marco44ec2e72017-10-19 14:13:38 +0100602 }
603}
604
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000605template <typename T>
606void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100607{
Gian Marco44ec2e72017-10-19 14:13:38 +0100608 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000609 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100610 std::vector<size_t> index;
611
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000612 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100613 const size_t num_classes = tensor.info()->dimension(0);
614
615 classes_prob.resize(num_classes);
616 index.resize(num_classes);
617
618 std::copy(output_net, output_net + num_classes, classes_prob.begin());
619
620 // Sort results
621 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
622 std::sort(std::begin(index), std::end(index),
623 [&](size_t a, size_t b)
624 {
625 return classes_prob[a] > classes_prob[b];
626 });
627
628 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
629 << std::endl;
630 for(size_t i = 0; i < _top_n; ++i)
631 {
632 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000633 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100634 << " - [id = " << index.at(i) << "]"
635 << ", " << _labels[index.at(i)] << std::endl;
636 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000637}
638
639bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
640{
641 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
642 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
643
644 switch(tensor.info()->data_type())
645 {
646 case DataType::QASYMM8:
647 access_predictions_tensor<uint8_t>(tensor);
648 break;
649 case DataType::F32:
650 access_predictions_tensor<float>(tensor);
651 break;
652 default:
653 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
654 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100655
656 return false;
657}
658
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100659RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
660 : _lower(lower), _upper(upper), _seed(seed)
661{
662}
663
664template <typename T, typename D>
665void RandomAccessor::fill(ITensor &tensor, D &&distribution)
666{
667 std::mt19937 gen(_seed);
668
hakanardof36ac352018-02-16 10:06:34 +0100669 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100670 {
671 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
672 {
Michele Di Giorgio88731f02018-09-25 16:49:27 +0100673 const auto value = static_cast<T>(distribution(gen));
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100674 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
675 }
676 }
677 else
678 {
679 // If tensor has padding accessing tensor elements through execution window.
680 Window window;
681 window.use_tensor_dimensions(tensor.info()->tensor_shape());
682
683 execute_window_loop(window, [&](const Coordinates & id)
684 {
Michele Di Giorgio88731f02018-09-25 16:49:27 +0100685 const auto value = static_cast<T>(distribution(gen));
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100686 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
687 });
688 }
689}
690
691bool RandomAccessor::access_tensor(ITensor &tensor)
692{
693 switch(tensor.info()->data_type())
694 {
John Kesapidesfb68ca12019-01-21 14:13:27 +0000695 case DataType::QASYMM8:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100696 case DataType::U8:
697 {
698 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
699 fill<uint8_t>(tensor, distribution_u8);
700 break;
701 }
702 case DataType::S8:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100703 {
704 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
705 fill<int8_t>(tensor, distribution_s8);
706 break;
707 }
708 case DataType::U16:
709 {
710 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
711 fill<uint16_t>(tensor, distribution_u16);
712 break;
713 }
714 case DataType::S16:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100715 {
716 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
717 fill<int16_t>(tensor, distribution_s16);
718 break;
719 }
720 case DataType::U32:
721 {
722 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
723 fill<uint32_t>(tensor, distribution_u32);
724 break;
725 }
726 case DataType::S32:
727 {
728 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
729 fill<int32_t>(tensor, distribution_s32);
730 break;
731 }
732 case DataType::U64:
733 {
734 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
735 fill<uint64_t>(tensor, distribution_u64);
736 break;
737 }
738 case DataType::S64:
739 {
740 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
741 fill<int64_t>(tensor, distribution_s64);
742 break;
743 }
744 case DataType::F16:
745 {
John Kesapidesfb68ca12019-01-21 14:13:27 +0000746 std::uniform_real_distribution<float> distribution_f16(_lower.get<half>(), _upper.get<half>());
Michele Di Giorgio88731f02018-09-25 16:49:27 +0100747 fill<half>(tensor, distribution_f16);
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100748 break;
749 }
750 case DataType::F32:
751 {
752 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
753 fill<float>(tensor, distribution_f32);
754 break;
755 }
756 case DataType::F64:
757 {
758 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
759 fill<double>(tensor, distribution_f64);
760 break;
761 }
762 default:
763 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
764 }
765 return true;
766}
767
Georgios Pinitascac13b12018-04-27 19:07:19 +0100768NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
Anthony Barbier8a042112018-08-21 18:16:53 +0100769 : _already_loaded(false), _filename(std::move(filename)), _file_layout(file_layout)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100770{
771}
772
773bool NumPyBinLoader::access_tensor(ITensor &tensor)
774{
Anthony Barbier8a042112018-08-21 18:16:53 +0100775 if(!_already_loaded)
776 {
777 utils::NPYLoader loader;
778 loader.open(_filename, _file_layout);
779 loader.fill_tensor(tensor);
780 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100781
Anthony Barbier8a042112018-08-21 18:16:53 +0100782 _already_loaded = !_already_loaded;
783 return _already_loaded;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000784}