blob: 1d59ee5679ba8e1cce2aa7684d0be26b29cd9939 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
Manuel Bottini053e7512018-12-28 15:05:20 +00002 * Copyright (c) 2016-2019 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
27#include "arm_compute/core/Helpers.h"
28#include "arm_compute/core/ITensor.h"
29#include "arm_compute/core/Types.h"
30#include "arm_compute/core/Validate.h"
steniu01bee466b2017-06-21 16:45:41 +010031#include "arm_compute/core/Window.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010032#include "arm_compute/runtime/Tensor.h"
Michalis Spyrou6bff1952019-10-02 17:22:11 +010033#pragma GCC diagnostic push
34#pragma GCC diagnostic ignored "-Wunused-parameter"
Michalis Spyroufae513c2019-10-16 17:41:33 +010035#pragma GCC diagnostic ignored "-Wstrict-overflow"
Giorgio Arenacf3935f2017-10-26 17:14:13 +010036#include "libnpy/npy.hpp"
Michalis Spyrou6bff1952019-10-02 17:22:11 +010037#pragma GCC diagnostic pop
Anthony Barbier2a07e182017-08-04 18:20:27 +010038#include "support/ToolchainSupport.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010039
40#ifdef ARM_COMPUTE_CL
41#include "arm_compute/core/CL/OpenCL.h"
Isabella Gottardi02aabcc2017-10-12 17:28:51 +010042#include "arm_compute/runtime/CL/CLDistribution1D.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010043#include "arm_compute/runtime/CL/CLTensor.h"
44#endif /* ARM_COMPUTE_CL */
Anthony Barbier7068f992017-10-26 15:23:08 +010045#ifdef ARM_COMPUTE_GC
46#include "arm_compute/runtime/GLES_COMPUTE/GCTensor.h"
47#endif /* ARM_COMPUTE_GC */
Anthony Barbier6ff3b192017-09-04 18:44:23 +010048
49#include <cstdlib>
50#include <cstring>
51#include <fstream>
52#include <iostream>
Giorgio Arenacf3935f2017-10-26 17:14:13 +010053#include <random>
54#include <string>
55#include <tuple>
56#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010057
58namespace arm_compute
59{
60namespace utils
61{
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010062/** Supported image types */
63enum class ImageType
64{
65 UNKNOWN,
66 PPM,
67 JPEG
68};
69
Anthony Barbier6db0ff52018-01-05 10:59:12 +000070/** Abstract Example class.
71 *
72 * All examples have to inherit from this class.
73 */
74class Example
75{
76public:
Alex Gildayc357c472018-03-21 13:54:09 +000077 /** Setup the example.
78 *
79 * @param[in] argc Argument count.
80 * @param[in] argv Argument values.
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010081 *
82 * @return True in case of no errors in setup else false
Alex Gildayc357c472018-03-21 13:54:09 +000083 */
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010084 virtual bool do_setup(int argc, char **argv)
85 {
Michalis Spyrou6bff1952019-10-02 17:22:11 +010086 ARM_COMPUTE_UNUSED(argc, argv);
Georgios Pinitas12be7ab2018-07-03 12:06:23 +010087 return true;
88 };
Alex Gildayc357c472018-03-21 13:54:09 +000089 /** Run the example. */
Anthony Barbier6db0ff52018-01-05 10:59:12 +000090 virtual void do_run() {};
Alex Gildayc357c472018-03-21 13:54:09 +000091 /** Teardown the example. */
Anthony Barbier6db0ff52018-01-05 10:59:12 +000092 virtual void do_teardown() {};
93
94 /** Default destructor. */
95 virtual ~Example() = default;
96};
97
98/** Run an example and handle the potential exceptions it throws
99 *
100 * @param[in] argc Number of command line arguments
101 * @param[in] argv Command line arguments
102 * @param[in] example Example to run
103 */
Anthony Barbier9fb0cac2018-04-20 15:46:21 +0100104int run_example(int argc, char **argv, std::unique_ptr<Example> example);
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000105
106template <typename T>
107int run_example(int argc, char **argv)
108{
Anthony Barbier9fb0cac2018-04-20 15:46:21 +0100109 return run_example(argc, argv, support::cpp14::make_unique<T>());
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000110}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100111
112/** Draw a RGB rectangular window for the detected object
113 *
114 * @param[in, out] tensor Input tensor where the rectangle will be drawn on. Format supported: RGB888
115 * @param[in] rect Geometry of the rectangular window
116 * @param[in] r Red colour to use
117 * @param[in] g Green colour to use
118 * @param[in] b Blue colour to use
119 */
120void draw_detection_rectangle(arm_compute::ITensor *tensor, const arm_compute::DetectionWindow &rect, uint8_t r, uint8_t g, uint8_t b);
121
Georgios Pinitas12be7ab2018-07-03 12:06:23 +0100122/** Gets image type given a file
123 *
124 * @param[in] filename File to identify its image type
125 *
126 * @return Image type
127 */
128ImageType get_image_type_from_file(const std::string &filename);
129
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100130/** Parse the ppm header from an input file stream. At the end of the execution,
131 * the file position pointer will be located at the first pixel stored in the ppm file
132 *
133 * @param[in] fs Input file stream to parse
134 *
135 * @return The width, height and max value stored in the header of the PPM file
136 */
137std::tuple<unsigned int, unsigned int, int> parse_ppm_header(std::ifstream &fs);
138
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100139/** Parse the npy header from an input file stream. At the end of the execution,
140 * the file position pointer will be located at the first pixel stored in the npy file //TODO
141 *
142 * @param[in] fs Input file stream to parse
143 *
144 * @return The width and height stored in the header of the NPY file
145 */
146std::tuple<std::vector<unsigned long>, bool, std::string> parse_npy_header(std::ifstream &fs);
147
148/** Obtain numpy type string from DataType.
149 *
150 * @param[in] data_type Data type.
151 *
152 * @return numpy type string.
153 */
154inline std::string get_typestring(DataType data_type)
155{
156 // Check endianness
157 const unsigned int i = 1;
158 const char *c = reinterpret_cast<const char *>(&i);
159 std::string endianness;
160 if(*c == 1)
161 {
162 endianness = std::string("<");
163 }
164 else
165 {
166 endianness = std::string(">");
167 }
168 const std::string no_endianness("|");
169
170 switch(data_type)
171 {
172 case DataType::U8:
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000173 case DataType::QASYMM8:
Michalis Spyrouc8530212019-08-22 11:44:04 +0100174 case DataType::QASYMM8_PER_CHANNEL:
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
Anthony Barbier7068f992017-10-26 15:23:08 +0100269#ifdef ARM_COMPUTE_GC
270/** Maps a tensor if needed
271 *
272 * @param[in] tensor Tensor to be mapped
273 * @param[in] blocking Specified if map is blocking or not
274 */
275inline void map(GCTensor &tensor, bool blocking)
276{
277 tensor.map(blocking);
278}
279
280/** Unmaps a tensor if needed
281 *
282 * @param tensor Tensor to be unmapped
283 */
284inline void unmap(GCTensor &tensor)
285{
286 tensor.unmap();
287}
288#endif /* ARM_COMPUTE_GC */
289
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000290/** Specialized class to generate random non-zero FP16 values.
291 * uniform_real_distribution<half> generates values that get rounded off to zero, causing
292 * differences between ACL and reference implementation
293*/
294class uniform_real_distribution_fp16
295{
296 half min{ 0.0f }, max{ 0.0f };
297 std::uniform_real_distribution<float> neg{ min, -0.3f };
298 std::uniform_real_distribution<float> pos{ 0.3f, max };
299 std::uniform_int_distribution<uint8_t> sign_picker{ 0, 1 };
300
301public:
302 using result_type = half;
303 /** Constructor
304 *
305 * @param[in] a Minimum value of the distribution
306 * @param[in] b Maximum value of the distribution
307 */
308 explicit uniform_real_distribution_fp16(half a = half(0.0), half b = half(1.0))
309 : min(a), max(b)
310 {
311 }
312
313 /** () operator to generate next value
314 *
315 * @param[in] gen an uniform random bit generator object
316 */
317 half operator()(std::mt19937 &gen)
318 {
319 if(sign_picker(gen))
320 {
321 return (half)neg(gen);
322 }
323 return (half)pos(gen);
324 }
325};
326
Alex Gildayc357c472018-03-21 13:54:09 +0000327/** Numpy data loader */
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100328class NPYLoader
329{
330public:
Alex Gildayc357c472018-03-21 13:54:09 +0000331 /** Default constructor */
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100332 NPYLoader()
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100333 : _fs(), _shape(), _fortran_order(false), _typestring(), _file_layout(DataLayout::NCHW)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100334 {
335 }
336
337 /** Open a NPY file and reads its metadata
338 *
339 * @param[in] npy_filename File to open
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100340 * @param[in] file_layout (Optional) Layout in which the weights are stored in the file.
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100341 */
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100342 void open(const std::string &npy_filename, DataLayout file_layout = DataLayout::NCHW)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100343 {
344 ARM_COMPUTE_ERROR_ON(is_open());
345 try
346 {
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100347 _fs.open(npy_filename, std::ios::in | std::ios::binary);
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100348 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 +0100349 _fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
350 _file_layout = file_layout;
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100351
352 std::tie(_shape, _fortran_order, _typestring) = parse_npy_header(_fs);
353 }
354 catch(const std::ifstream::failure &e)
355 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100356 ARM_COMPUTE_ERROR_VAR("Accessing %s: %s", npy_filename.c_str(), e.what());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100357 }
358 }
359 /** Return true if a NPY file is currently open */
360 bool is_open()
361 {
362 return _fs.is_open();
363 }
364
365 /** Return true if a NPY file is in fortran order */
366 bool is_fortran()
367 {
368 return _fortran_order;
369 }
370
Gian Marco0bc5a252017-12-04 13:55:08 +0000371 /** Initialise the tensor's metadata with the dimensions of the NPY file currently open
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100372 *
373 * @param[out] tensor Tensor to initialise
Gian Marco0bc5a252017-12-04 13:55:08 +0000374 * @param[in] dt Data type to use for the tensor
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100375 */
376 template <typename T>
Gian Marco0bc5a252017-12-04 13:55:08 +0000377 void init_tensor(T &tensor, arm_compute::DataType dt)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100378 {
379 ARM_COMPUTE_ERROR_ON(!is_open());
Gian Marco0bc5a252017-12-04 13:55:08 +0000380 ARM_COMPUTE_ERROR_ON(dt != arm_compute::DataType::F32);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100381
382 // Use the size of the input NPY tensor
383 TensorShape shape;
384 shape.set_num_dimensions(_shape.size());
385 for(size_t i = 0; i < _shape.size(); ++i)
386 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100387 size_t src = i;
388 if(_fortran_order)
389 {
390 src = _shape.size() - 1 - i;
391 }
392 shape.set(i, _shape.at(src));
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100393 }
394
Gian Marco0bc5a252017-12-04 13:55:08 +0000395 arm_compute::TensorInfo tensor_info(shape, 1, dt);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100396 tensor.allocator()->init(tensor_info);
397 }
398
399 /** Fill a tensor with the content of the currently open NPY file.
400 *
401 * @note If the tensor is a CLTensor, the function maps and unmaps the tensor
402 *
403 * @param[in,out] tensor Tensor to fill (Must be allocated, and of matching dimensions with the opened NPY).
404 */
405 template <typename T>
406 void fill_tensor(T &tensor)
407 {
408 ARM_COMPUTE_ERROR_ON(!is_open());
giuros01351bd132019-08-23 14:27:30 +0100409 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 +0100410 try
411 {
412 // Map buffer if creating a CLTensor
413 map(tensor, true);
414
415 // Check if the file is large enough to fill the tensor
416 const size_t current_position = _fs.tellg();
417 _fs.seekg(0, std::ios_base::end);
418 const size_t end_position = _fs.tellg();
419 _fs.seekg(current_position, std::ios_base::beg);
420
421 ARM_COMPUTE_ERROR_ON_MSG((end_position - current_position) < tensor.info()->tensor_shape().total_size() * tensor.info()->element_size(),
422 "Not enough data in file");
423 ARM_COMPUTE_UNUSED(end_position);
424
425 // Check if the typestring matches the given one
426 std::string expect_typestr = get_typestring(tensor.info()->data_type());
427 ARM_COMPUTE_ERROR_ON_MSG(_typestring != expect_typestr, "Typestrings mismatch");
428
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100429 bool are_layouts_different = (_file_layout != tensor.info()->data_layout());
430 // Correct dimensions (Needs to match TensorShape dimension corrections)
431 if(_shape.size() != tensor.info()->tensor_shape().num_dimensions())
432 {
433 for(int i = static_cast<int>(_shape.size()) - 1; i > 0; --i)
434 {
435 if(_shape[i] == 1)
436 {
437 _shape.pop_back();
438 }
439 else
440 {
441 break;
442 }
443 }
444 }
Michalis Spyrou39412952018-08-14 17:06:16 +0100445
446 TensorShape permuted_shape = tensor.info()->tensor_shape();
447 arm_compute::PermutationVector perm;
448 if(are_layouts_different && tensor.info()->tensor_shape().num_dimensions() > 2)
449 {
450 perm = (tensor.info()->data_layout() == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
451 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);
452
453 arm_compute::permute(permuted_shape, perm_vec);
454 }
455
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100456 // Validate tensor shape
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000457 ARM_COMPUTE_ERROR_ON_MSG(_shape.size() != tensor.info()->tensor_shape().num_dimensions(), "Tensor ranks mismatch");
Michalis Spyrou39412952018-08-14 17:06:16 +0100458 for(size_t i = 0; i < _shape.size(); ++i)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100459 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100460 ARM_COMPUTE_ERROR_ON_MSG(permuted_shape[i] != _shape[i], "Tensor dimensions mismatch");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100461 }
462
Gian Marco0bc5a252017-12-04 13:55:08 +0000463 switch(tensor.info()->data_type())
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100464 {
Georgios Pinitasa799ce02018-09-12 20:11:34 +0100465 case arm_compute::DataType::QASYMM8:
466 case arm_compute::DataType::S32:
Gian Marco0bc5a252017-12-04 13:55:08 +0000467 case arm_compute::DataType::F32:
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000468 case arm_compute::DataType::F16:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100469 {
470 // Read data
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100471 if(!are_layouts_different && !_fortran_order && tensor.info()->padding().empty())
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100472 {
473 // If tensor has no padding read directly from stream.
474 _fs.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
475 }
476 else
477 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100478 // If tensor has padding or is in fortran order accessing tensor elements through execution window.
Michalis Spyrou39412952018-08-14 17:06:16 +0100479 Window window;
480 const unsigned int num_dims = _shape.size();
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100481 if(_fortran_order)
482 {
483 for(unsigned int dim = 0; dim < num_dims; dim++)
484 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100485 permuted_shape.set(dim, _shape[num_dims - dim - 1]);
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100486 perm.set(dim, num_dims - dim - 1);
487 }
Michalis Spyrou39412952018-08-14 17:06:16 +0100488 if(are_layouts_different)
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100489 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100490 // Permute only if num_dimensions greater than 2
491 if(num_dims > 2)
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100492 {
Michalis Spyrou39412952018-08-14 17:06:16 +0100493 if(_file_layout == DataLayout::NHWC) // i.e destination is NCHW --> permute(1,2,0)
494 {
495 arm_compute::permute(perm, arm_compute::PermutationVector(1U, 2U, 0U));
496 }
497 else
498 {
499 arm_compute::permute(perm, arm_compute::PermutationVector(2U, 0U, 1U));
500 }
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100501 }
502 }
503 }
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100504 window.use_tensor_dimensions(permuted_shape);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100505
506 execute_window_loop(window, [&](const Coordinates & id)
507 {
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100508 Coordinates dst(id);
509 arm_compute::permute(dst, perm);
510 _fs.read(reinterpret_cast<char *>(tensor.ptr_to_element(dst)), tensor.info()->element_size());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100511 });
512 }
513
514 break;
515 }
516 default:
Gian Marco0bc5a252017-12-04 13:55:08 +0000517 ARM_COMPUTE_ERROR("Unsupported data type");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100518 }
519
520 // Unmap buffer if creating a CLTensor
521 unmap(tensor);
522 }
523 catch(const std::ifstream::failure &e)
524 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100525 ARM_COMPUTE_ERROR_VAR("Loading NPY file: %s", e.what());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100526 }
527 }
528
529private:
530 std::ifstream _fs;
531 std::vector<unsigned long> _shape;
532 bool _fortran_order;
533 std::string _typestring;
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100534 DataLayout _file_layout;
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100535};
536
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100537/** Template helper function to save a tensor image to a PPM file.
538 *
539 * @note Only U8 and RGB888 formats supported.
540 * @note Only works with 2D tensors.
541 * @note If the input tensor is a CLTensor, the function maps and unmaps the image
542 *
543 * @param[in] tensor The tensor to save as PPM file
544 * @param[in] ppm_filename Filename of the file to create.
545 */
546template <typename T>
547void save_to_ppm(T &tensor, const std::string &ppm_filename)
548{
549 ARM_COMPUTE_ERROR_ON_FORMAT_NOT_IN(&tensor, arm_compute::Format::RGB888, arm_compute::Format::U8);
550 ARM_COMPUTE_ERROR_ON(tensor.info()->num_dimensions() > 2);
551
552 std::ofstream fs;
553
554 try
555 {
556 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
557 fs.open(ppm_filename, std::ios::out | std::ios::binary);
558
559 const unsigned int width = tensor.info()->tensor_shape()[0];
560 const unsigned int height = tensor.info()->tensor_shape()[1];
561
562 fs << "P6\n"
563 << width << " " << height << " 255\n";
564
Anthony Barbier7068f992017-10-26 15:23:08 +0100565 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100566 map(tensor, true);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100567
568 switch(tensor.info()->format())
569 {
570 case arm_compute::Format::U8:
571 {
572 arm_compute::Window window;
573 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, 1));
574 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
575
576 arm_compute::Iterator in(&tensor, window);
577
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100578 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates &)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100579 {
580 const unsigned char value = *in.ptr();
581
582 fs << value << value << value;
583 },
584 in);
585
586 break;
587 }
588 case arm_compute::Format::RGB888:
589 {
590 arm_compute::Window window;
591 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, width));
592 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
593
594 arm_compute::Iterator in(&tensor, window);
595
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100596 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates &)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100597 {
598 fs.write(reinterpret_cast<std::fstream::char_type *>(in.ptr()), width * tensor.info()->element_size());
599 },
600 in);
601
602 break;
603 }
604 default:
605 ARM_COMPUTE_ERROR("Unsupported format");
606 }
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100607
Anthony Barbier7068f992017-10-26 15:23:08 +0100608 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100609 unmap(tensor);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100610 }
611 catch(const std::ofstream::failure &e)
612 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100613 ARM_COMPUTE_ERROR_VAR("Writing %s: (%s)", ppm_filename.c_str(), e.what());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100614 }
615}
steniu01bee466b2017-06-21 16:45:41 +0100616
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100617/** Template helper function to save a tensor image to a NPY file.
618 *
Gian Marcobfa3b522017-12-12 10:08:38 +0000619 * @note Only F32 data type supported.
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100620 * @note If the input tensor is a CLTensor, the function maps and unmaps the image
621 *
622 * @param[in] tensor The tensor to save as NPY file
623 * @param[in] npy_filename Filename of the file to create.
624 * @param[in] fortran_order If true, save matrix in fortran order.
625 */
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000626template <typename T, typename U = float>
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100627void save_to_npy(T &tensor, const std::string &npy_filename, bool fortran_order)
628{
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000629 ARM_COMPUTE_ERROR_ON_DATA_TYPE_NOT_IN(&tensor, arm_compute::DataType::F32, arm_compute::DataType::QASYMM8);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100630
631 std::ofstream fs;
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100632 try
633 {
634 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
635 fs.open(npy_filename, std::ios::out | std::ios::binary);
636
Anthony Barbier4ead11a2018-08-06 09:25:36 +0100637 std::vector<npy::ndarray_len_t> shape(tensor.info()->num_dimensions());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100638
Pablo Tello32521432018-11-15 14:43:10 +0000639 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 +0100640 {
Pablo Tello32521432018-11-15 14:43:10 +0000641 shape[i] = tensor.info()->tensor_shape()[!fortran_order ? j : i];
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100642 }
643
644 // Map buffer if creating a CLTensor
645 map(tensor, true);
646
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000647 using typestring_type = typename std::conditional<std::is_floating_point<U>::value, float, qasymm8_t>::type;
648
649 std::vector<typestring_type> tmp; /* Used only to get the typestring */
650 npy::Typestring typestring_o{ tmp };
651 std::string typestring = typestring_o.str();
652
653 std::ofstream stream(npy_filename, std::ofstream::binary);
654 npy::write_header(stream, typestring, fortran_order, shape);
655
656 arm_compute::Window window;
657 window.use_tensor_dimensions(tensor.info()->tensor_shape());
658
659 arm_compute::Iterator in(&tensor, window);
660
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100661 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates &)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100662 {
Isabella Gottardia7acb3c2019-01-08 13:48:44 +0000663 stream.write(reinterpret_cast<const char *>(in.ptr()), sizeof(typestring_type));
664 },
665 in);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100666
667 // Unmap buffer if creating a CLTensor
668 unmap(tensor);
669 }
670 catch(const std::ofstream::failure &e)
671 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100672 ARM_COMPUTE_ERROR_VAR("Writing %s: (%s)", npy_filename.c_str(), e.what());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100673 }
674}
675
steniu01bee466b2017-06-21 16:45:41 +0100676/** Load the tensor with pre-trained data from a binary file
677 *
678 * @param[in] tensor The tensor to be filled. Data type supported: F32.
679 * @param[in] filename Filename of the binary file to load from.
680 */
681template <typename T>
682void load_trained_data(T &tensor, const std::string &filename)
683{
684 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
685
686 std::ifstream fs;
687
688 try
689 {
690 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
691 // Open file
692 fs.open(filename, std::ios::in | std::ios::binary);
693
694 if(!fs.good())
695 {
696 throw std::runtime_error("Could not load binary data: " + filename);
697 }
698
Anthony Barbier7068f992017-10-26 15:23:08 +0100699 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100700 map(tensor, true);
701
steniu01bee466b2017-06-21 16:45:41 +0100702 Window window;
703
704 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, 1, 1));
705
706 for(unsigned int d = 1; d < tensor.info()->num_dimensions(); ++d)
707 {
708 window.set(d, Window::Dimension(0, tensor.info()->tensor_shape()[d], 1));
709 }
710
711 arm_compute::Iterator in(&tensor, window);
712
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100713 execute_window_loop(window, [&](const Coordinates &)
steniu01bee466b2017-06-21 16:45:41 +0100714 {
715 fs.read(reinterpret_cast<std::fstream::char_type *>(in.ptr()), tensor.info()->tensor_shape()[0] * tensor.info()->element_size());
716 },
717 in);
718
Anthony Barbier7068f992017-10-26 15:23:08 +0100719 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100720 unmap(tensor);
steniu01bee466b2017-06-21 16:45:41 +0100721 }
722 catch(const std::ofstream::failure &e)
723 {
Michalis Spyrou7c60c992019-10-10 14:33:47 +0100724 ARM_COMPUTE_ERROR_VAR("Writing %s: (%s)", filename.c_str(), e.what());
steniu01bee466b2017-06-21 16:45:41 +0100725 }
726}
727
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100728template <typename T>
729void fill_random_tensor(T &tensor, float lower_bound, float upper_bound)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100730{
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100731 std::random_device rd;
732 std::mt19937 gen(rd());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100733
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100734 Window window;
Michalis Spyrou5e69bb42018-03-09 16:36:00 +0000735 window.use_tensor_dimensions(tensor.info()->tensor_shape());
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100736
737 map(tensor, true);
738
739 Iterator it(&tensor, window);
740
Gian Marcobfa3b522017-12-12 10:08:38 +0000741 switch(tensor.info()->data_type())
Anthony Barbier2a07e182017-08-04 18:20:27 +0100742 {
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000743 case arm_compute::DataType::F16:
744 {
745 std::uniform_real_distribution<float> dist(lower_bound, upper_bound);
746
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100747 execute_window_loop(window, [&](const Coordinates &)
Vidhya Sudhan Loganathana25d16c2018-11-16 11:33:12 +0000748 {
749 *reinterpret_cast<half *>(it.ptr()) = (half)dist(gen);
750 },
751 it);
752
753 break;
754 }
Gian Marcobfa3b522017-12-12 10:08:38 +0000755 case arm_compute::DataType::F32:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100756 {
757 std::uniform_real_distribution<float> dist(lower_bound, upper_bound);
758
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100759 execute_window_loop(window, [&](const Coordinates &)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100760 {
761 *reinterpret_cast<float *>(it.ptr()) = dist(gen);
762 },
763 it);
764
765 break;
766 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100767 default:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100768 {
769 ARM_COMPUTE_ERROR("Unsupported format");
770 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100771 }
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100772
773 unmap(tensor);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100774}
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100775
776template <typename T>
Gian Marco0bc5a252017-12-04 13:55:08 +0000777void init_sgemm_output(T &dst, T &src0, T &src1, arm_compute::DataType dt)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100778{
Georgios Pinitas108a95e2019-03-27 13:55:59 +0000779 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 +0100780}
Gian Marco5ca74092018-02-08 16:21:54 +0000781/** This function returns the amount of memory free reading from /proc/meminfo
782 *
783 * @return The free memory in kB
784 */
785uint64_t get_mem_free_from_meminfo();
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100786
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000787/** Compare two tensors
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100788 *
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000789 * @param[in] tensor1 First tensor to be compared.
790 * @param[in] tensor2 Second tensor to be compared.
791 * @param[in] tolerance Tolerance used for the comparison.
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100792 *
793 * @return The number of mismatches
794 */
795template <typename T>
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000796int compare_tensor(ITensor &tensor1, ITensor &tensor2, T tolerance)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100797{
798 ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(&tensor1, &tensor2);
799 ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(&tensor1, &tensor2);
800
801 int num_mismatches = 0;
802 Window window;
803 window.use_tensor_dimensions(tensor1.info()->tensor_shape());
804
805 map(tensor1, true);
806 map(tensor2, true);
Pablo Tello32521432018-11-15 14:43:10 +0000807
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100808 Iterator itensor1(&tensor1, window);
809 Iterator itensor2(&tensor2, window);
810
Michalis Spyrou6bff1952019-10-02 17:22:11 +0100811 execute_window_loop(window, [&](const Coordinates &)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100812 {
Isabella Gottardi0ae5de92019-03-14 10:32:11 +0000813 if(std::abs(*reinterpret_cast<T *>(itensor1.ptr()) - *reinterpret_cast<T *>(itensor2.ptr())) > tolerance)
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100814 {
815 ++num_mismatches;
816 }
817 },
818 itensor1, itensor2);
819
820 unmap(itensor1);
821 unmap(itensor2);
822
823 return num_mismatches;
824}
Pablo Tellodb9116f2019-07-11 16:50:37 +0100825
826/** This function saves opencl kernels library to a file
827 *
828 * @param[in] filename Name of the file to be used to save the library
829 */
830void save_program_cache_to_file(const std::string &filename = "cache.bin");
831
832/** This function loads prebuilt opencl kernels from a file
833 *
834 * @param[in] filename Name of the file to be used to load the kernels
835 */
836void restore_program_cache_from_file(const std::string &filename = "cache.bin");
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100837} // namespace utils
838} // namespace arm_compute
839#endif /* __UTILS_UTILS_H__*/