blob: f8c84851b51e979ced9b4ec706a36966e9c323ac [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
Giorgio Arenab309fc22021-01-05 09:46:16 +00002 * Copyright (c) 2016-2021 Arm Limited.
Anthony Barbier6ff3b192017-09-04 18:44: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#ifndef __UTILS_UTILS_H__
25#define __UTILS_UTILS_H__
26
Michele Di Giorgio552e11d2020-09-23 15:08:38 +010027/** @dir .
28 * brief Boiler plate code used by examples. Various utilities to print types, load / store assets, etc.
29 */
30
Anthony Barbier6ff3b192017-09-04 18:44:23 +010031#include "arm_compute/core/Helpers.h"
32#include "arm_compute/core/ITensor.h"
33#include "arm_compute/core/Types.h"
steniu01bee466b2017-06-21 16:45:41 +010034#include "arm_compute/core/Window.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010035#include "arm_compute/runtime/Tensor.h"
Michalis Spyrou6bff1952019-10-02 17:22:11 +010036#pragma GCC diagnostic push
37#pragma GCC diagnostic ignored "-Wunused-parameter"
Michalis Spyroufae513c2019-10-16 17:41:33 +010038#pragma GCC diagnostic ignored "-Wstrict-overflow"
Giorgio Arenacf3935f2017-10-26 17:14:13 +010039#include "libnpy/npy.hpp"
Michalis Spyrou6bff1952019-10-02 17:22:11 +010040#pragma GCC diagnostic pop
Matthew Bentham758b5ba2020-03-05 23:37:48 +000041#include "support/StringSupport.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010042
43#ifdef ARM_COMPUTE_CL
44#include "arm_compute/core/CL/OpenCL.h"
Isabella Gottardi02aabcc2017-10-12 17:28:51 +010045#include "arm_compute/runtime/CL/CLDistribution1D.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010046#include "arm_compute/runtime/CL/CLTensor.h"
47#endif /* ARM_COMPUTE_CL */
48
49#include <cstdlib>
50#include <cstring>
51#include <fstream>
52#include <iostream>
Georgios Pinitas40f51a62020-11-21 03:04:18 +000053#include <memory>
Giorgio Arenacf3935f2017-10-26 17:14:13 +010054#include <random>
55#include <string>
56#include <tuple>
57#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010058
59namespace arm_compute
60{
61namespace utils
62{
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010063/** Supported image types */
64enum class ImageType
65{
66 UNKNOWN,
67 PPM,
68 JPEG
69};
70
Anthony Barbier6db0ff52018-01-05 10:59:12 +000071/** Abstract Example class.
72 *
73 * All examples have to inherit from this class.
74 */
75class Example
76{
77public:
Alex Gildayc357c472018-03-21 13:54:09 +000078 /** Setup the example.
79 *
80 * @param[in] argc Argument count.
81 * @param[in] argv Argument values.
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010082 *
83 * @return True in case of no errors in setup else false
Alex Gildayc357c472018-03-21 13:54:09 +000084 */
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010085 virtual bool do_setup(int argc, char **argv)
86 {
Michalis Spyrou6bff1952019-10-02 17:22:11 +010087 ARM_COMPUTE_UNUSED(argc, argv);
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010088 return true;
89 };
Alex Gildayc357c472018-03-21 13:54:09 +000090 /** Run the example. */
Anthony Barbier6db0ff52018-01-05 10:59:12 +000091 virtual void do_run() {};
Alex Gildayc357c472018-03-21 13:54:09 +000092 /** Teardown the example. */
Anthony Barbier6db0ff52018-01-05 10:59:12 +000093 virtual void do_teardown() {};
94
95 /** Default destructor. */
96 virtual ~Example() = default;
97};
98
99/** Run an example and handle the potential exceptions it throws
100 *
101 * @param[in] argc Number of command line arguments
102 * @param[in] argv Command line arguments
103 * @param[in] example Example to run
104 */
Anthony Barbier9fb0cac2018-04-20 15:46:21 +0100105int run_example(int argc, char **argv, std::unique_ptr<Example> example);
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000106
107template <typename T>
108int run_example(int argc, char **argv)
109{
Georgios Pinitas40f51a62020-11-21 03:04:18 +0000110 return run_example(argc, argv, std::make_unique<T>());
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000111}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100112
113/** Draw a RGB rectangular window for the detected object
114 *
115 * @param[in, out] tensor Input tensor where the rectangle will be drawn on. Format supported: RGB888
116 * @param[in] rect Geometry of the rectangular window
117 * @param[in] r Red colour to use
118 * @param[in] g Green colour to use
119 * @param[in] b Blue colour to use
120 */
121void draw_detection_rectangle(arm_compute::ITensor *tensor, const arm_compute::DetectionWindow &rect, uint8_t r, uint8_t g, uint8_t b);
122
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100123/** Gets image type given a file
124 *
125 * @param[in] filename File to identify its image type
126 *
127 * @return Image type
128 */
129ImageType get_image_type_from_file(const std::string &filename);
130
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100131/** Parse the ppm header from an input file stream. At the end of the execution,
132 * the file position pointer will be located at the first pixel stored in the ppm file
133 *
134 * @param[in] fs Input file stream to parse
135 *
136 * @return The width, height and max value stored in the header of the PPM file
137 */
138std::tuple<unsigned int, unsigned int, int> parse_ppm_header(std::ifstream &fs);
139
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100140/** Parse the npy header from an input file stream. At the end of the execution,
141 * the file position pointer will be located at the first pixel stored in the npy file //TODO
142 *
143 * @param[in] fs Input file stream to parse
144 *
145 * @return The width and height stored in the header of the NPY file
146 */
147std::tuple<std::vector<unsigned long>, bool, std::string> parse_npy_header(std::ifstream &fs);
148
149/** Obtain numpy type string from DataType.
150 *
151 * @param[in] data_type Data type.
152 *
153 * @return numpy type string.
154 */
155inline std::string get_typestring(DataType data_type)
156{
157 // Check endianness
158 const unsigned int i = 1;
159 const char *c = reinterpret_cast<const char *>(&i);
160 std::string endianness;
161 if(*c == 1)
162 {
163 endianness = std::string("<");
164 }
165 else
166 {
167 endianness = std::string(">");
168 }
169 const std::string no_endianness("|");
170
171 switch(data_type)
172 {
173 case DataType::U8:
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000174 case DataType::QASYMM8:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100175 return no_endianness + "u" + support::cpp11::to_string(sizeof(uint8_t));
176 case DataType::S8:
Georgios Pinitas4c5469b2019-05-21 13:32:43 +0100177 case DataType::QSYMM8:
178 case DataType::QSYMM8_PER_CHANNEL:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100179 return no_endianness + "i" + support::cpp11::to_string(sizeof(int8_t));
180 case DataType::U16:
Michele Di Giorgio35ea9a72019-08-23 12:02:06 +0100181 case DataType::QASYMM16:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100182 return endianness + "u" + support::cpp11::to_string(sizeof(uint16_t));
183 case DataType::S16:
Manuel Bottini3689fcd2019-06-14 17:18:12 +0100184 case DataType::QSYMM16:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100185 return endianness + "i" + support::cpp11::to_string(sizeof(int16_t));
186 case DataType::U32:
187 return endianness + "u" + support::cpp11::to_string(sizeof(uint32_t));
188 case DataType::S32:
189 return endianness + "i" + support::cpp11::to_string(sizeof(int32_t));
190 case DataType::U64:
191 return endianness + "u" + support::cpp11::to_string(sizeof(uint64_t));
192 case DataType::S64:
193 return endianness + "i" + support::cpp11::to_string(sizeof(int64_t));
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000194 case DataType::F16:
195 return endianness + "f" + support::cpp11::to_string(sizeof(half));
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100196 case DataType::F32:
197 return endianness + "f" + support::cpp11::to_string(sizeof(float));
198 case DataType::F64:
199 return endianness + "f" + support::cpp11::to_string(sizeof(double));
200 case DataType::SIZET:
201 return endianness + "u" + support::cpp11::to_string(sizeof(size_t));
202 default:
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100203 ARM_COMPUTE_ERROR("Data type not supported");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100204 }
205}
206
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100207/** Maps a tensor if needed
208 *
209 * @param[in] tensor Tensor to be mapped
210 * @param[in] blocking Specified if map is blocking or not
211 */
212template <typename T>
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100213inline void map(T &tensor, bool blocking)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100214{
215 ARM_COMPUTE_UNUSED(tensor);
216 ARM_COMPUTE_UNUSED(blocking);
217}
218
219/** Unmaps a tensor if needed
220 *
221 * @param tensor Tensor to be unmapped
222 */
223template <typename T>
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100224inline void unmap(T &tensor)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100225{
226 ARM_COMPUTE_UNUSED(tensor);
227}
228
229#ifdef ARM_COMPUTE_CL
230/** Maps a tensor if needed
231 *
232 * @param[in] tensor Tensor to be mapped
233 * @param[in] blocking Specified if map is blocking or not
234 */
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100235inline void map(CLTensor &tensor, bool blocking)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100236{
237 tensor.map(blocking);
238}
239
240/** Unmaps a tensor if needed
241 *
242 * @param tensor Tensor to be unmapped
243 */
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100244inline void unmap(CLTensor &tensor)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100245{
246 tensor.unmap();
247}
Isabella Gottardi02aabcc2017-10-12 17:28:51 +0100248
249/** Maps a distribution if needed
250 *
251 * @param[in] distribution Distribution to be mapped
252 * @param[in] blocking Specified if map is blocking or not
253 */
254inline void map(CLDistribution1D &distribution, bool blocking)
255{
256 distribution.map(blocking);
257}
258
259/** Unmaps a distribution if needed
260 *
261 * @param distribution Distribution to be unmapped
262 */
263inline void unmap(CLDistribution1D &distribution)
264{
265 distribution.unmap();
266}
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100267#endif /* ARM_COMPUTE_CL */
268
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000269/** Specialized class to generate random non-zero FP16 values.
270 * uniform_real_distribution<half> generates values that get rounded off to zero, causing
271 * differences between ACL and reference implementation
272*/
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000273template <typename T>
274class uniform_real_distribution_16bit
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000275{
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000276 static_assert(std::is_same<T, half>::value || std::is_same<T, bfloat16>::value, "Only half and bfloat16 data types supported");
277
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000278public:
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000279 using result_type = T;
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000280 /** Constructor
281 *
Giorgio Arena6aeb2172020-12-15 15:45:43 +0000282 * @param[in] min Minimum value of the distribution
283 * @param[in] max Maximum value of the distribution
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000284 */
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000285 explicit uniform_real_distribution_16bit(float min = 0.f, float max = 1.0)
Giorgio Arena6aeb2172020-12-15 15:45:43 +0000286 : dist(min, max)
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000287 {
288 }
289
290 /** () operator to generate next value
291 *
292 * @param[in] gen an uniform random bit generator object
293 */
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000294 T operator()(std::mt19937 &gen)
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000295 {
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000296 return T(dist(gen));
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000297 }
Giorgio Arena6aeb2172020-12-15 15:45:43 +0000298
299private:
300 std::uniform_real_distribution<float> dist;
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000301};
302
Alex Gildayc357c472018-03-21 13:54:09 +0000303/** Numpy data loader */
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100304class NPYLoader
305{
306public:
Alex Gildayc357c472018-03-21 13:54:09 +0000307 /** Default constructor */
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100308 NPYLoader()
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100309 : _fs(), _shape(), _fortran_order(false), _typestring(), _file_layout(DataLayout::NCHW)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100310 {
311 }
312
313 /** Open a NPY file and reads its metadata
314 *
315 * @param[in] npy_filename File to open
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100316 * @param[in] file_layout (Optional) Layout in which the weights are stored in the file.
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100317 */
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100318 void open(const std::string &npy_filename, DataLayout file_layout = DataLayout::NCHW)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100319 {
320 ARM_COMPUTE_ERROR_ON(is_open());
321 try
322 {
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100323 _fs.open(npy_filename, std::ios::in | std::ios::binary);
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100324 ARM_COMPUTE_EXIT_ON_MSG_VAR(!_fs.good(), "Failed to load binary data from %s", npy_filename.c_str());
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100325 _fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
326 _file_layout = file_layout;
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100327
328 std::tie(_shape, _fortran_order, _typestring) = parse_npy_header(_fs);
329 }
330 catch(const std::ifstream::failure &e)
331 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100332 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", npy_filename.c_str(), e.what());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100333 }
334 }
335 /** Return true if a NPY file is currently open */
336 bool is_open()
337 {
338 return _fs.is_open();
339 }
340
341 /** Return true if a NPY file is in fortran order */
342 bool is_fortran()
343 {
344 return _fortran_order;
345 }
346
Gian Marco0bc5a252017-12-04 13:55:08 +0000347 /** Initialise the tensor's metadata with the dimensions of the NPY file currently open
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100348 *
349 * @param[out] tensor Tensor to initialise
Gian Marco0bc5a252017-12-04 13:55:08 +0000350 * @param[in] dt Data type to use for the tensor
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100351 */
352 template <typename T>
Gian Marco0bc5a252017-12-04 13:55:08 +0000353 void init_tensor(T &tensor, arm_compute::DataType dt)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100354 {
355 ARM_COMPUTE_ERROR_ON(!is_open());
Gian Marco0bc5a252017-12-04 13:55:08 +0000356 ARM_COMPUTE_ERROR_ON(dt != arm_compute::DataType::F32);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100357
358 // Use the size of the input NPY tensor
359 TensorShape shape;
360 shape.set_num_dimensions(_shape.size());
361 for(size_t i = 0; i < _shape.size(); ++i)
362 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100363 size_t src = i;
364 if(_fortran_order)
365 {
366 src = _shape.size() - 1 - i;
367 }
368 shape.set(i, _shape.at(src));
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100369 }
370
Gian Marco0bc5a252017-12-04 13:55:08 +0000371 arm_compute::TensorInfo tensor_info(shape, 1, dt);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100372 tensor.allocator()->init(tensor_info);
373 }
374
375 /** Fill a tensor with the content of the currently open NPY file.
376 *
377 * @note If the tensor is a CLTensor, the function maps and unmaps the tensor
378 *
379 * @param[in,out] tensor Tensor to fill (Must be allocated, and of matching dimensions with the opened NPY).
380 */
381 template <typename T>
382 void fill_tensor(T &tensor)
383 {
384 ARM_COMPUTE_ERROR_ON(!is_open());
giuros01351bd132019-08-23 14:27:30 +0100385 ARM_COMPUTE_ERROR_ON_DATA_TYPE_NOT_IN(&tensor, arm_compute::DataType::QASYMM8, arm_compute::DataType::S32, arm_compute::DataType::F32, arm_compute::DataType::F16);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100386 try
387 {
388 // Map buffer if creating a CLTensor
389 map(tensor, true);
390
391 // Check if the file is large enough to fill the tensor
392 const size_t current_position = _fs.tellg();
393 _fs.seekg(0, std::ios_base::end);
394 const size_t end_position = _fs.tellg();
395 _fs.seekg(current_position, std::ios_base::beg);
396
397 ARM_COMPUTE_ERROR_ON_MSG((end_position - current_position) < tensor.info()->tensor_shape().total_size() * tensor.info()->element_size(),
398 "Not enough data in file");
399 ARM_COMPUTE_UNUSED(end_position);
400
401 // Check if the typestring matches the given one
402 std::string expect_typestr = get_typestring(tensor.info()->data_type());
403 ARM_COMPUTE_ERROR_ON_MSG(_typestring != expect_typestr, "Typestrings mismatch");
404
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100405 bool are_layouts_different = (_file_layout != tensor.info()->data_layout());
406 // Correct dimensions (Needs to match TensorShape dimension corrections)
407 if(_shape.size() != tensor.info()->tensor_shape().num_dimensions())
408 {
409 for(int i = static_cast<int>(_shape.size()) - 1; i > 0; --i)
410 {
411 if(_shape[i] == 1)
412 {
413 _shape.pop_back();
414 }
415 else
416 {
417 break;
418 }
419 }
420 }
Michalis Spyrou39412952018-08-14 17:06:16 +0100421
422 TensorShape permuted_shape = tensor.info()->tensor_shape();
423 arm_compute::PermutationVector perm;
424 if(are_layouts_different && tensor.info()->tensor_shape().num_dimensions() > 2)
425 {
426 perm = (tensor.info()->data_layout() == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
427 arm_compute::PermutationVector perm_vec = (tensor.info()->data_layout() == arm_compute::DataLayout::NCHW) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
428
429 arm_compute::permute(permuted_shape, perm_vec);
430 }
431
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100432 // Validate tensor shape
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000433 ARM_COMPUTE_ERROR_ON_MSG(_shape.size() != tensor.info()->tensor_shape().num_dimensions(), "Tensor ranks mismatch");
Michalis Spyrou39412952018-08-14 17:06:16 +0100434 for(size_t i = 0; i < _shape.size(); ++i)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100435 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100436 ARM_COMPUTE_ERROR_ON_MSG(permuted_shape[i] != _shape[i], "Tensor dimensions mismatch");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100437 }
438
Gian Marco0bc5a252017-12-04 13:55:08 +0000439 switch(tensor.info()->data_type())
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100440 {
Georgios Pinitasa799ce02018-09-12 20:11:34 +0100441 case arm_compute::DataType::QASYMM8:
442 case arm_compute::DataType::S32:
Gian Marco0bc5a252017-12-04 13:55:08 +0000443 case arm_compute::DataType::F32:
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000444 case arm_compute::DataType::F16:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100445 {
446 // Read data
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100447 if(!are_layouts_different && !_fortran_order && tensor.info()->padding().empty())
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100448 {
449 // If tensor has no padding read directly from stream.
450 _fs.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
451 }
452 else
453 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100454 // If tensor has padding or is in fortran order accessing tensor elements through execution window.
Michalis Spyrou39412952018-08-14 17:06:16 +0100455 Window window;
456 const unsigned int num_dims = _shape.size();
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100457 if(_fortran_order)
458 {
459 for(unsigned int dim = 0; dim < num_dims; dim++)
460 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100461 permuted_shape.set(dim, _shape[num_dims - dim - 1]);
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100462 perm.set(dim, num_dims - dim - 1);
463 }
Michalis Spyrou39412952018-08-14 17:06:16 +0100464 if(are_layouts_different)
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100465 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100466 // Permute only if num_dimensions greater than 2
467 if(num_dims > 2)
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100468 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100469 if(_file_layout == DataLayout::NHWC) // i.e destination is NCHW --> permute(1,2,0)
470 {
471 arm_compute::permute(perm, arm_compute::PermutationVector(1U, 2U, 0U));
472 }
473 else
474 {
475 arm_compute::permute(perm, arm_compute::PermutationVector(2U, 0U, 1U));
476 }
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100477 }
478 }
479 }
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100480 window.use_tensor_dimensions(permuted_shape);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100481
482 execute_window_loop(window, [&](const Coordinates & id)
483 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100484 Coordinates dst(id);
485 arm_compute::permute(dst, perm);
486 _fs.read(reinterpret_cast<char *>(tensor.ptr_to_element(dst)), tensor.info()->element_size());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100487 });
488 }
489
490 break;
491 }
492 default:
Gian Marco0bc5a252017-12-04 13:55:08 +0000493 ARM_COMPUTE_ERROR("Unsupported data type");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100494 }
495
496 // Unmap buffer if creating a CLTensor
497 unmap(tensor);
498 }
499 catch(const std::ifstream::failure &e)
500 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100501 ARM_COMPUTE_ERROR_VAR("Loading NPY file: %s", e.what());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100502 }
503 }
504
505private:
506 std::ifstream _fs;
507 std::vector<unsigned long> _shape;
508 bool _fortran_order;
509 std::string _typestring;
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100510 DataLayout _file_layout;
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100511};
512
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100513/** Template helper function to save a tensor image to a PPM file.
514 *
515 * @note Only U8 and RGB888 formats supported.
516 * @note Only works with 2D tensors.
517 * @note If the input tensor is a CLTensor, the function maps and unmaps the image
518 *
519 * @param[in] tensor The tensor to save as PPM file
520 * @param[in] ppm_filename Filename of the file to create.
521 */
522template <typename T>
523void save_to_ppm(T &tensor, const std::string &ppm_filename)
524{
525 ARM_COMPUTE_ERROR_ON_FORMAT_NOT_IN(&tensor, arm_compute::Format::RGB888, arm_compute::Format::U8);
526 ARM_COMPUTE_ERROR_ON(tensor.info()->num_dimensions() > 2);
527
528 std::ofstream fs;
529
530 try
531 {
532 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
533 fs.open(ppm_filename, std::ios::out | std::ios::binary);
534
535 const unsigned int width = tensor.info()->tensor_shape()[0];
536 const unsigned int height = tensor.info()->tensor_shape()[1];
537
538 fs << "P6\n"
539 << width << " " << height << " 255\n";
540
Anthony Barbier7068f992017-10-26 15:23:08 +0100541 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100542 map(tensor, true);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100543
544 switch(tensor.info()->format())
545 {
546 case arm_compute::Format::U8:
547 {
548 arm_compute::Window window;
549 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, 1));
550 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
551
552 arm_compute::Iterator in(&tensor, window);
553
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100554 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates &)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100555 {
556 const unsigned char value = *in.ptr();
557
558 fs << value << value << value;
559 },
560 in);
561
562 break;
563 }
564 case arm_compute::Format::RGB888:
565 {
566 arm_compute::Window window;
567 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, width));
568 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
569
570 arm_compute::Iterator in(&tensor, window);
571
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100572 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates &)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100573 {
574 fs.write(reinterpret_cast<std::fstream::char_type *>(in.ptr()), width * tensor.info()->element_size());
575 },
576 in);
577
578 break;
579 }
580 default:
581 ARM_COMPUTE_ERROR("Unsupported format");
582 }
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100583
Anthony Barbier7068f992017-10-26 15:23:08 +0100584 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100585 unmap(tensor);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100586 }
587 catch(const std::ofstream::failure &e)
588 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100589 ARM_COMPUTE_ERROR_VAR("Writing %s: (%s)", ppm_filename.c_str(), e.what());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100590 }
591}
steniu01bee466b2017-06-21 16:45:41 +0100592
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100593/** Template helper function to save a tensor image to a NPY file.
594 *
Gian Marcobfa3b522017-12-12 10:08:38 +0000595 * @note Only F32 data type supported.
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100596 * @note If the input tensor is a CLTensor, the function maps and unmaps the image
597 *
598 * @param[in] tensor The tensor to save as NPY file
599 * @param[in] npy_filename Filename of the file to create.
600 * @param[in] fortran_order If true, save matrix in fortran order.
601 */
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000602template <typename T, typename U = float>
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100603void save_to_npy(T &tensor, const std::string &npy_filename, bool fortran_order)
604{
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000605 ARM_COMPUTE_ERROR_ON_DATA_TYPE_NOT_IN(&tensor, arm_compute::DataType::F32, arm_compute::DataType::QASYMM8);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100606
607 std::ofstream fs;
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100608 try
609 {
610 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
611 fs.open(npy_filename, std::ios::out | std::ios::binary);
612
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100613 std::vector<npy::ndarray_len_t> shape(tensor.info()->num_dimensions());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100614
Pablo Tello32521432018-11-15 14:43:10 +0000615 for(unsigned int i = 0, j = tensor.info()->num_dimensions() - 1; i < tensor.info()->num_dimensions(); ++i, --j)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100616 {
Pablo Tello32521432018-11-15 14:43:10 +0000617 shape[i] = tensor.info()->tensor_shape()[!fortran_order ? j : i];
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100618 }
619
620 // Map buffer if creating a CLTensor
621 map(tensor, true);
622
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000623 using typestring_type = typename std::conditional<std::is_floating_point<U>::value, float, qasymm8_t>::type;
624
625 std::vector<typestring_type> tmp; /* Used only to get the typestring */
626 npy::Typestring typestring_o{ tmp };
627 std::string typestring = typestring_o.str();
628
629 std::ofstream stream(npy_filename, std::ofstream::binary);
630 npy::write_header(stream, typestring, fortran_order, shape);
631
632 arm_compute::Window window;
633 window.use_tensor_dimensions(tensor.info()->tensor_shape());
634
635 arm_compute::Iterator in(&tensor, window);
636
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100637 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates &)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100638 {
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000639 stream.write(reinterpret_cast<const char *>(in.ptr()), sizeof(typestring_type));
640 },
641 in);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100642
643 // Unmap buffer if creating a CLTensor
644 unmap(tensor);
645 }
646 catch(const std::ofstream::failure &e)
647 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100648 ARM_COMPUTE_ERROR_VAR("Writing %s: (%s)", npy_filename.c_str(), e.what());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100649 }
650}
651
steniu01bee466b2017-06-21 16:45:41 +0100652/** Load the tensor with pre-trained data from a binary file
653 *
654 * @param[in] tensor The tensor to be filled. Data type supported: F32.
655 * @param[in] filename Filename of the binary file to load from.
656 */
657template <typename T>
658void load_trained_data(T &tensor, const std::string &filename)
659{
660 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
661
662 std::ifstream fs;
663
664 try
665 {
666 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
667 // Open file
668 fs.open(filename, std::ios::in | std::ios::binary);
669
670 if(!fs.good())
671 {
672 throw std::runtime_error("Could not load binary data: " + filename);
673 }
674
Anthony Barbier7068f992017-10-26 15:23:08 +0100675 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100676 map(tensor, true);
677
steniu01bee466b2017-06-21 16:45:41 +0100678 Window window;
679
680 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, 1, 1));
681
682 for(unsigned int d = 1; d < tensor.info()->num_dimensions(); ++d)
683 {
684 window.set(d, Window::Dimension(0, tensor.info()->tensor_shape()[d], 1));
685 }
686
687 arm_compute::Iterator in(&tensor, window);
688
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100689 execute_window_loop(window, [&](const Coordinates &)
steniu01bee466b2017-06-21 16:45:41 +0100690 {
691 fs.read(reinterpret_cast<std::fstream::char_type *>(in.ptr()), tensor.info()->tensor_shape()[0] * tensor.info()->element_size());
692 },
693 in);
694
Anthony Barbier7068f992017-10-26 15:23:08 +0100695 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100696 unmap(tensor);
steniu01bee466b2017-06-21 16:45:41 +0100697 }
698 catch(const std::ofstream::failure &e)
699 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100700 ARM_COMPUTE_ERROR_VAR("Writing %s: (%s)", filename.c_str(), e.what());
steniu01bee466b2017-06-21 16:45:41 +0100701 }
702}
703
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000704template <typename T, typename TensorType>
705void fill_tensor_value(TensorType &tensor, T value)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100706{
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000707 map(tensor, true);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100708
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100709 Window window;
Michalis Spyrou5e69bb42018-03-09 16:36:00 +0000710 window.use_tensor_dimensions(tensor.info()->tensor_shape());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100711
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000712 Iterator it_tensor(&tensor, window);
713 execute_window_loop(window, [&](const Coordinates &)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100714 {
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000715 *reinterpret_cast<T *>(it_tensor.ptr()) = value;
716 },
717 it_tensor);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100718
719 unmap(tensor);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100720}
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100721
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000722template <typename T, typename TensorType>
723void fill_tensor_zero(TensorType &tensor)
724{
725 fill_tensor_value(tensor, T(0));
726}
727
728template <typename T, typename TensorType>
729void fill_tensor_vector(TensorType &tensor, std::vector<T> vec)
730{
731 ARM_COMPUTE_ERROR_ON(tensor.info()->tensor_shape().total_size() != vec.size());
732
733 map(tensor, true);
734
735 Window window;
736 window.use_tensor_dimensions(tensor.info()->tensor_shape());
737
738 int i = 0;
739 Iterator it_tensor(&tensor, window);
740 execute_window_loop(window, [&](const Coordinates &)
741 {
742 *reinterpret_cast<T *>(it_tensor.ptr()) = vec.at(i++);
743 },
744 it_tensor);
745
746 unmap(tensor);
747}
748
749template <typename T, typename TensorType>
750void fill_random_tensor(TensorType &tensor, std::random_device::result_type seed, T lower_bound = std::numeric_limits<T>::lowest(), T upper_bound = std::numeric_limits<T>::max())
751{
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000752 constexpr bool is_fp_16bit = std::is_same<T, half>::value || std::is_same<T, bfloat16>::value;
753 constexpr bool is_integral = std::is_integral<T>::value && !is_fp_16bit;
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000754
Giorgio Arenaa8e2aeb2021-01-06 11:34:57 +0000755 using fp_dist_type = typename std::conditional<is_fp_16bit, arm_compute::utils::uniform_real_distribution_16bit<T>, std::uniform_real_distribution<T>>::type;
Giorgio Arena82c0d7f2020-12-15 17:15:43 +0000756 using dist_type = typename std::conditional<is_integral, std::uniform_int_distribution<T>, fp_dist_type>::type;
757
758 std::mt19937 gen(seed);
759 dist_type dist(lower_bound, upper_bound);
760
761 map(tensor, true);
762
763 Window window;
764 window.use_tensor_dimensions(tensor.info()->tensor_shape());
765
766 Iterator it(&tensor, window);
767 execute_window_loop(window, [&](const Coordinates &)
768 {
769 *reinterpret_cast<T *>(it.ptr()) = dist(gen);
770 },
771 it);
772
773 unmap(tensor);
774}
775
776template <typename T, typename TensorType>
777void fill_random_tensor(TensorType &tensor, T lower_bound = std::numeric_limits<T>::lowest(), T upper_bound = std::numeric_limits<T>::max())
778{
779 std::random_device rd;
780 fill_random_tensor(tensor, rd(), lower_bound, upper_bound);
781}
782
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100783template <typename T>
Gian Marco0bc5a252017-12-04 13:55:08 +0000784void init_sgemm_output(T &dst, T &src0, T &src1, arm_compute::DataType dt)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100785{
Georgios Pinitas108a95e2019-03-27 13:55:59 +0000786 dst.allocator()->init(TensorInfo(TensorShape(src1.info()->dimension(0), src0.info()->dimension(1), src0.info()->dimension(2)), 1, dt));
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100787}
Gian Marco5ca74092018-02-08 16:21:54 +0000788/** This function returns the amount of memory free reading from /proc/meminfo
789 *
790 * @return The free memory in kB
791 */
792uint64_t get_mem_free_from_meminfo();
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100793
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000794/** Compare two tensors
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100795 *
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000796 * @param[in] tensor1 First tensor to be compared.
797 * @param[in] tensor2 Second tensor to be compared.
798 * @param[in] tolerance Tolerance used for the comparison.
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100799 *
800 * @return The number of mismatches
801 */
802template <typename T>
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000803int compare_tensor(ITensor &tensor1, ITensor &tensor2, T tolerance)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100804{
805 ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(&tensor1, &tensor2);
806 ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(&tensor1, &tensor2);
807
808 int num_mismatches = 0;
809 Window window;
810 window.use_tensor_dimensions(tensor1.info()->tensor_shape());
811
812 map(tensor1, true);
813 map(tensor2, true);
Pablo Tello32521432018-11-15 14:43:10 +0000814
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100815 Iterator itensor1(&tensor1, window);
816 Iterator itensor2(&tensor2, window);
817
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100818 execute_window_loop(window, [&](const Coordinates &)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100819 {
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000820 if(std::abs(*reinterpret_cast<T *>(itensor1.ptr()) - *reinterpret_cast<T *>(itensor2.ptr())) > tolerance)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100821 {
822 ++num_mismatches;
823 }
824 },
825 itensor1, itensor2);
826
827 unmap(itensor1);
828 unmap(itensor2);
829
830 return num_mismatches;
831}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100832} // namespace utils
833} // namespace arm_compute
834#endif /* __UTILS_UTILS_H__*/