blob: 01e513766918b372d29ffe69ae617d83ab75888e [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
Anthony Barbier6db0ff52018-01-05 10:59:12 +00002 * Copyright (c) 2016, 2018 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"
Giorgio Arenacf3935f2017-10-26 17:14:13 +010033#include "libnpy/npy.hpp"
Anthony Barbier2a07e182017-08-04 18:20:27 +010034#include "support/ToolchainSupport.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010035
36#ifdef ARM_COMPUTE_CL
37#include "arm_compute/core/CL/OpenCL.h"
Isabella Gottardi02aabcc2017-10-12 17:28:51 +010038#include "arm_compute/runtime/CL/CLDistribution1D.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010039#include "arm_compute/runtime/CL/CLTensor.h"
40#endif /* ARM_COMPUTE_CL */
Anthony Barbier7068f992017-10-26 15:23:08 +010041#ifdef ARM_COMPUTE_GC
42#include "arm_compute/runtime/GLES_COMPUTE/GCTensor.h"
43#endif /* ARM_COMPUTE_GC */
Anthony Barbier6ff3b192017-09-04 18:44:23 +010044
45#include <cstdlib>
46#include <cstring>
47#include <fstream>
48#include <iostream>
Giorgio Arenacf3935f2017-10-26 17:14:13 +010049#include <random>
50#include <string>
51#include <tuple>
52#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010053
54namespace arm_compute
55{
56namespace utils
57{
Anthony Barbier6db0ff52018-01-05 10:59:12 +000058/** Abstract Example class.
59 *
60 * All examples have to inherit from this class.
61 */
62class Example
63{
64public:
65 virtual void do_setup(int argc, char **argv) {};
66 virtual void do_run() {};
67 virtual void do_teardown() {};
68
69 /** Default destructor. */
70 virtual ~Example() = default;
71};
72
73/** Run an example and handle the potential exceptions it throws
74 *
75 * @param[in] argc Number of command line arguments
76 * @param[in] argv Command line arguments
77 * @param[in] example Example to run
78 */
79int run_example(int argc, char **argv, Example &example);
80
81template <typename T>
82int run_example(int argc, char **argv)
83{
84 T example;
85 return run_example(argc, argv, example);
86}
Anthony Barbier6ff3b192017-09-04 18:44:23 +010087
88/** Draw a RGB rectangular window for the detected object
89 *
90 * @param[in, out] tensor Input tensor where the rectangle will be drawn on. Format supported: RGB888
91 * @param[in] rect Geometry of the rectangular window
92 * @param[in] r Red colour to use
93 * @param[in] g Green colour to use
94 * @param[in] b Blue colour to use
95 */
96void draw_detection_rectangle(arm_compute::ITensor *tensor, const arm_compute::DetectionWindow &rect, uint8_t r, uint8_t g, uint8_t b);
97
98/** Parse the ppm header from an input file stream. At the end of the execution,
99 * the file position pointer will be located at the first pixel stored in the ppm file
100 *
101 * @param[in] fs Input file stream to parse
102 *
103 * @return The width, height and max value stored in the header of the PPM file
104 */
105std::tuple<unsigned int, unsigned int, int> parse_ppm_header(std::ifstream &fs);
106
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100107/** Parse the npy header from an input file stream. At the end of the execution,
108 * the file position pointer will be located at the first pixel stored in the npy file //TODO
109 *
110 * @param[in] fs Input file stream to parse
111 *
112 * @return The width and height stored in the header of the NPY file
113 */
114std::tuple<std::vector<unsigned long>, bool, std::string> parse_npy_header(std::ifstream &fs);
115
116/** Obtain numpy type string from DataType.
117 *
118 * @param[in] data_type Data type.
119 *
120 * @return numpy type string.
121 */
122inline std::string get_typestring(DataType data_type)
123{
124 // Check endianness
125 const unsigned int i = 1;
126 const char *c = reinterpret_cast<const char *>(&i);
127 std::string endianness;
128 if(*c == 1)
129 {
130 endianness = std::string("<");
131 }
132 else
133 {
134 endianness = std::string(">");
135 }
136 const std::string no_endianness("|");
137
138 switch(data_type)
139 {
140 case DataType::U8:
141 return no_endianness + "u" + support::cpp11::to_string(sizeof(uint8_t));
142 case DataType::S8:
143 return no_endianness + "i" + support::cpp11::to_string(sizeof(int8_t));
144 case DataType::U16:
145 return endianness + "u" + support::cpp11::to_string(sizeof(uint16_t));
146 case DataType::S16:
147 return endianness + "i" + support::cpp11::to_string(sizeof(int16_t));
148 case DataType::U32:
149 return endianness + "u" + support::cpp11::to_string(sizeof(uint32_t));
150 case DataType::S32:
151 return endianness + "i" + support::cpp11::to_string(sizeof(int32_t));
152 case DataType::U64:
153 return endianness + "u" + support::cpp11::to_string(sizeof(uint64_t));
154 case DataType::S64:
155 return endianness + "i" + support::cpp11::to_string(sizeof(int64_t));
156 case DataType::F32:
157 return endianness + "f" + support::cpp11::to_string(sizeof(float));
158 case DataType::F64:
159 return endianness + "f" + support::cpp11::to_string(sizeof(double));
160 case DataType::SIZET:
161 return endianness + "u" + support::cpp11::to_string(sizeof(size_t));
162 default:
163 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
164 }
165}
166
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100167/** Maps a tensor if needed
168 *
169 * @param[in] tensor Tensor to be mapped
170 * @param[in] blocking Specified if map is blocking or not
171 */
172template <typename T>
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100173inline void map(T &tensor, bool blocking)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100174{
175 ARM_COMPUTE_UNUSED(tensor);
176 ARM_COMPUTE_UNUSED(blocking);
177}
178
179/** Unmaps a tensor if needed
180 *
181 * @param tensor Tensor to be unmapped
182 */
183template <typename T>
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100184inline void unmap(T &tensor)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100185{
186 ARM_COMPUTE_UNUSED(tensor);
187}
188
189#ifdef ARM_COMPUTE_CL
190/** Maps a tensor if needed
191 *
192 * @param[in] tensor Tensor to be mapped
193 * @param[in] blocking Specified if map is blocking or not
194 */
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100195inline void map(CLTensor &tensor, bool blocking)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100196{
197 tensor.map(blocking);
198}
199
200/** Unmaps a tensor if needed
201 *
202 * @param tensor Tensor to be unmapped
203 */
Gian Marco Iodiceae27e942017-09-28 18:31:26 +0100204inline void unmap(CLTensor &tensor)
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100205{
206 tensor.unmap();
207}
Isabella Gottardi02aabcc2017-10-12 17:28:51 +0100208
209/** Maps a distribution if needed
210 *
211 * @param[in] distribution Distribution to be mapped
212 * @param[in] blocking Specified if map is blocking or not
213 */
214inline void map(CLDistribution1D &distribution, bool blocking)
215{
216 distribution.map(blocking);
217}
218
219/** Unmaps a distribution if needed
220 *
221 * @param distribution Distribution to be unmapped
222 */
223inline void unmap(CLDistribution1D &distribution)
224{
225 distribution.unmap();
226}
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100227#endif /* ARM_COMPUTE_CL */
228
Anthony Barbier7068f992017-10-26 15:23:08 +0100229#ifdef ARM_COMPUTE_GC
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 */
235inline void map(GCTensor &tensor, bool blocking)
236{
237 tensor.map(blocking);
238}
239
240/** Unmaps a tensor if needed
241 *
242 * @param tensor Tensor to be unmapped
243 */
244inline void unmap(GCTensor &tensor)
245{
246 tensor.unmap();
247}
248#endif /* ARM_COMPUTE_GC */
249
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100250/** Class to load the content of a PPM file into an Image
251 */
252class PPMLoader
253{
254public:
255 PPMLoader()
256 : _fs(), _width(0), _height(0)
257 {
258 }
259 /** Open a PPM file and reads its metadata (Width, height)
260 *
261 * @param[in] ppm_filename File to open
262 */
263 void open(const std::string &ppm_filename)
264 {
265 ARM_COMPUTE_ERROR_ON(is_open());
266 try
267 {
268 _fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
269 _fs.open(ppm_filename, std::ios::in | std::ios::binary);
270
271 unsigned int max_val = 0;
272 std::tie(_width, _height, max_val) = parse_ppm_header(_fs);
273
274 ARM_COMPUTE_ERROR_ON_MSG(max_val >= 256, "2 bytes per colour channel not supported in file %s", ppm_filename.c_str());
275 }
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000276 catch(std::runtime_error &e)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100277 {
278 ARM_COMPUTE_ERROR("Accessing %s: %s", ppm_filename.c_str(), e.what());
279 }
280 }
281 /** Return true if a PPM file is currently open
282 */
283 bool is_open()
284 {
285 return _fs.is_open();
286 }
287
288 /** Initialise an image's metadata with the dimensions of the PPM file currently open
289 *
290 * @param[out] image Image to initialise
291 * @param[in] format Format to use for the image (Must be RGB888 or U8)
292 */
293 template <typename T>
294 void init_image(T &image, arm_compute::Format format)
295 {
296 ARM_COMPUTE_ERROR_ON(!is_open());
297 ARM_COMPUTE_ERROR_ON(format != arm_compute::Format::RGB888 && format != arm_compute::Format::U8);
298
299 // Use the size of the input PPM image
300 arm_compute::TensorInfo image_info(_width, _height, format);
301 image.allocator()->init(image_info);
302 }
303
304 /** Fill an image with the content of the currently open PPM file.
305 *
306 * @note If the image is a CLImage, the function maps and unmaps the image
307 *
308 * @param[in,out] image Image to fill (Must be allocated, and of matching dimensions with the opened PPM).
309 */
310 template <typename T>
311 void fill_image(T &image)
312 {
313 ARM_COMPUTE_ERROR_ON(!is_open());
314 ARM_COMPUTE_ERROR_ON(image.info()->dimension(0) != _width || image.info()->dimension(1) != _height);
315 ARM_COMPUTE_ERROR_ON_FORMAT_NOT_IN(&image, arm_compute::Format::U8, arm_compute::Format::RGB888);
316 try
317 {
Anthony Barbier7068f992017-10-26 15:23:08 +0100318 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100319 map(image, true);
320
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100321 // Check if the file is large enough to fill the image
322 const size_t current_position = _fs.tellg();
323 _fs.seekg(0, std::ios_base::end);
324 const size_t end_position = _fs.tellg();
325 _fs.seekg(current_position, std::ios_base::beg);
326
327 ARM_COMPUTE_ERROR_ON_MSG((end_position - current_position) < image.info()->tensor_shape().total_size() * image.info()->element_size(),
328 "Not enough data in file");
329 ARM_COMPUTE_UNUSED(end_position);
330
331 switch(image.info()->format())
332 {
333 case arm_compute::Format::U8:
334 {
335 // We need to convert the data from RGB to grayscale:
336 // Iterate through every pixel of the image
337 arm_compute::Window window;
338 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, _width, 1));
339 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, _height, 1));
340
341 arm_compute::Iterator out(&image, window);
342
343 unsigned char red = 0;
344 unsigned char green = 0;
345 unsigned char blue = 0;
346
347 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id)
348 {
349 red = _fs.get();
350 green = _fs.get();
351 blue = _fs.get();
352
353 *out.ptr() = 0.2126f * red + 0.7152f * green + 0.0722f * blue;
354 },
355 out);
356
357 break;
358 }
359 case arm_compute::Format::RGB888:
360 {
361 // There is no format conversion needed: we can simply copy the content of the input file to the image one row at the time.
362 // Create a vertical window to iterate through the image's rows:
363 arm_compute::Window window;
364 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, _height, 1));
365
366 arm_compute::Iterator out(&image, window);
367
368 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id)
369 {
370 // Copy one row from the input file to the current row of the image:
371 _fs.read(reinterpret_cast<std::fstream::char_type *>(out.ptr()), _width * image.info()->element_size());
372 },
373 out);
374
375 break;
376 }
377 default:
378 ARM_COMPUTE_ERROR("Unsupported format");
379 }
380
Anthony Barbier7068f992017-10-26 15:23:08 +0100381 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100382 unmap(image);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100383 }
384 catch(const std::ifstream::failure &e)
385 {
386 ARM_COMPUTE_ERROR("Loading PPM file: %s", e.what());
387 }
388 }
389
Gian Marco44ec2e72017-10-19 14:13:38 +0100390 /** Fill a tensor with 3 planes (one for each channel) with the content of the currently open PPM file.
391 *
392 * @note If the image is a CLImage, the function maps and unmaps the image
393 *
394 * @param[in,out] tensor Tensor with 3 planes to fill (Must be allocated, and of matching dimensions with the opened PPM). Data types supported: U8/F32
395 * @param[in] bgr (Optional) Fill the first plane with blue channel (default = false)
396 */
397 template <typename T>
398 void fill_planar_tensor(T &tensor, bool bgr = false)
399 {
400 ARM_COMPUTE_ERROR_ON(!is_open());
401 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::U8, DataType::F32);
402 ARM_COMPUTE_ERROR_ON(tensor.info()->dimension(0) != _width || tensor.info()->dimension(1) != _height || tensor.info()->dimension(2) != 3);
403
404 try
405 {
406 // Map buffer if creating a CLTensor
407 map(tensor, true);
408
409 // Check if the file is large enough to fill the image
410 const size_t current_position = _fs.tellg();
411 _fs.seekg(0, std::ios_base::end);
412 const size_t end_position = _fs.tellg();
413 _fs.seekg(current_position, std::ios_base::beg);
414
415 ARM_COMPUTE_ERROR_ON_MSG((end_position - current_position) < tensor.info()->tensor_shape().total_size(),
416 "Not enough data in file");
417 ARM_COMPUTE_UNUSED(end_position);
418
419 // Iterate through every pixel of the image
420 arm_compute::Window window;
421 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, _width, 1));
422 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, _height, 1));
423 window.set(arm_compute::Window::DimZ, arm_compute::Window::Dimension(0, 1, 1));
424
425 arm_compute::Iterator out(&tensor, window);
426
427 unsigned char red = 0;
428 unsigned char green = 0;
429 unsigned char blue = 0;
430
431 size_t stride_z = tensor.info()->strides_in_bytes()[2];
432
433 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id)
434 {
435 red = _fs.get();
436 green = _fs.get();
437 blue = _fs.get();
438
439 switch(tensor.info()->data_type())
440 {
441 case arm_compute::DataType::U8:
442 {
443 *(out.ptr() + 0 * stride_z) = bgr ? blue : red;
444 *(out.ptr() + 1 * stride_z) = green;
445 *(out.ptr() + 2 * stride_z) = bgr ? red : blue;
446 break;
447 }
448 case arm_compute::DataType::F32:
449 {
450 *reinterpret_cast<float *>(out.ptr() + 0 * stride_z) = static_cast<float>(bgr ? blue : red);
451 *reinterpret_cast<float *>(out.ptr() + 1 * stride_z) = static_cast<float>(green);
452 *reinterpret_cast<float *>(out.ptr() + 2 * stride_z) = static_cast<float>(bgr ? red : blue);
453 break;
454 }
455 default:
456 {
457 ARM_COMPUTE_ERROR("Unsupported data type");
458 }
459 }
460 },
461 out);
462
463 // Unmap buffer if creating a CLTensor
464 unmap(tensor);
465 }
466 catch(const std::ifstream::failure &e)
467 {
468 ARM_COMPUTE_ERROR("Loading PPM file: %s", e.what());
469 }
470 }
471
Isabella Gottardia4c61882017-11-03 12:11:55 +0000472 /** Return the width of the currently open PPM file.
473 */
474 unsigned int width() const
475 {
476 return _width;
477 }
478
479 /** Return the height of the currently open PPM file.
480 */
481 unsigned int height() const
482 {
483 return _height;
484 }
485
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100486private:
487 std::ifstream _fs;
488 unsigned int _width, _height;
489};
490
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100491class NPYLoader
492{
493public:
494 NPYLoader()
495 : _fs(), _shape(), _fortran_order(false), _typestring()
496 {
497 }
498
499 /** Open a NPY file and reads its metadata
500 *
501 * @param[in] npy_filename File to open
502 */
503 void open(const std::string &npy_filename)
504 {
505 ARM_COMPUTE_ERROR_ON(is_open());
506 try
507 {
508 _fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
509 _fs.open(npy_filename, std::ios::in | std::ios::binary);
510
511 std::tie(_shape, _fortran_order, _typestring) = parse_npy_header(_fs);
512 }
513 catch(const std::ifstream::failure &e)
514 {
515 ARM_COMPUTE_ERROR("Accessing %s: %s", npy_filename.c_str(), e.what());
516 }
517 }
518 /** Return true if a NPY file is currently open */
519 bool is_open()
520 {
521 return _fs.is_open();
522 }
523
524 /** Return true if a NPY file is in fortran order */
525 bool is_fortran()
526 {
527 return _fortran_order;
528 }
529
Gian Marco0bc5a252017-12-04 13:55:08 +0000530 /** Initialise the tensor's metadata with the dimensions of the NPY file currently open
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100531 *
532 * @param[out] tensor Tensor to initialise
Gian Marco0bc5a252017-12-04 13:55:08 +0000533 * @param[in] dt Data type to use for the tensor
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100534 */
535 template <typename T>
Gian Marco0bc5a252017-12-04 13:55:08 +0000536 void init_tensor(T &tensor, arm_compute::DataType dt)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100537 {
538 ARM_COMPUTE_ERROR_ON(!is_open());
Gian Marco0bc5a252017-12-04 13:55:08 +0000539 ARM_COMPUTE_ERROR_ON(dt != arm_compute::DataType::F32);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100540
541 // Use the size of the input NPY tensor
542 TensorShape shape;
543 shape.set_num_dimensions(_shape.size());
544 for(size_t i = 0; i < _shape.size(); ++i)
545 {
546 shape.set(i, _shape.at(i));
547 }
548
Gian Marco0bc5a252017-12-04 13:55:08 +0000549 arm_compute::TensorInfo tensor_info(shape, 1, dt);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100550 tensor.allocator()->init(tensor_info);
551 }
552
553 /** Fill a tensor with the content of the currently open NPY file.
554 *
555 * @note If the tensor is a CLTensor, the function maps and unmaps the tensor
556 *
557 * @param[in,out] tensor Tensor to fill (Must be allocated, and of matching dimensions with the opened NPY).
558 */
559 template <typename T>
560 void fill_tensor(T &tensor)
561 {
562 ARM_COMPUTE_ERROR_ON(!is_open());
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000563 ARM_COMPUTE_ERROR_ON_DATA_TYPE_NOT_IN(&tensor, arm_compute::DataType::F32);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100564 try
565 {
566 // Map buffer if creating a CLTensor
567 map(tensor, true);
568
569 // Check if the file is large enough to fill the tensor
570 const size_t current_position = _fs.tellg();
571 _fs.seekg(0, std::ios_base::end);
572 const size_t end_position = _fs.tellg();
573 _fs.seekg(current_position, std::ios_base::beg);
574
575 ARM_COMPUTE_ERROR_ON_MSG((end_position - current_position) < tensor.info()->tensor_shape().total_size() * tensor.info()->element_size(),
576 "Not enough data in file");
577 ARM_COMPUTE_UNUSED(end_position);
578
579 // Check if the typestring matches the given one
580 std::string expect_typestr = get_typestring(tensor.info()->data_type());
581 ARM_COMPUTE_ERROR_ON_MSG(_typestring != expect_typestr, "Typestrings mismatch");
582
583 // Validate tensor shape
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000584 ARM_COMPUTE_ERROR_ON_MSG(_shape.size() != tensor.info()->tensor_shape().num_dimensions(), "Tensor ranks mismatch");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100585 if(_fortran_order)
586 {
587 for(size_t i = 0; i < _shape.size(); ++i)
588 {
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000589 ARM_COMPUTE_ERROR_ON_MSG(tensor.info()->tensor_shape()[i] != _shape[i], "Tensor dimensions mismatch");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100590 }
591 }
592 else
593 {
594 for(size_t i = 0; i < _shape.size(); ++i)
595 {
Anthony Barbier6db0ff52018-01-05 10:59:12 +0000596 ARM_COMPUTE_ERROR_ON_MSG(tensor.info()->tensor_shape()[i] != _shape[_shape.size() - i - 1], "Tensor dimensions mismatch");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100597 }
598 }
599
Gian Marco0bc5a252017-12-04 13:55:08 +0000600 switch(tensor.info()->data_type())
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100601 {
Gian Marco0bc5a252017-12-04 13:55:08 +0000602 case arm_compute::DataType::F32:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100603 {
604 // Read data
605 if(tensor.info()->padding().empty())
606 {
607 // If tensor has no padding read directly from stream.
608 _fs.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
609 }
610 else
611 {
612 // If tensor has padding accessing tensor elements through execution window.
613 Window window;
614 window.use_tensor_dimensions(tensor.info()->tensor_shape());
615
616 execute_window_loop(window, [&](const Coordinates & id)
617 {
618 _fs.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
619 });
620 }
621
622 break;
623 }
624 default:
Gian Marco0bc5a252017-12-04 13:55:08 +0000625 ARM_COMPUTE_ERROR("Unsupported data type");
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100626 }
627
628 // Unmap buffer if creating a CLTensor
629 unmap(tensor);
630 }
631 catch(const std::ifstream::failure &e)
632 {
633 ARM_COMPUTE_ERROR("Loading NPY file: %s", e.what());
634 }
635 }
636
637private:
638 std::ifstream _fs;
639 std::vector<unsigned long> _shape;
640 bool _fortran_order;
641 std::string _typestring;
642};
643
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100644/** Template helper function to save a tensor image to a PPM file.
645 *
646 * @note Only U8 and RGB888 formats supported.
647 * @note Only works with 2D tensors.
648 * @note If the input tensor is a CLTensor, the function maps and unmaps the image
649 *
650 * @param[in] tensor The tensor to save as PPM file
651 * @param[in] ppm_filename Filename of the file to create.
652 */
653template <typename T>
654void save_to_ppm(T &tensor, const std::string &ppm_filename)
655{
656 ARM_COMPUTE_ERROR_ON_FORMAT_NOT_IN(&tensor, arm_compute::Format::RGB888, arm_compute::Format::U8);
657 ARM_COMPUTE_ERROR_ON(tensor.info()->num_dimensions() > 2);
658
659 std::ofstream fs;
660
661 try
662 {
663 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
664 fs.open(ppm_filename, std::ios::out | std::ios::binary);
665
666 const unsigned int width = tensor.info()->tensor_shape()[0];
667 const unsigned int height = tensor.info()->tensor_shape()[1];
668
669 fs << "P6\n"
670 << width << " " << height << " 255\n";
671
Anthony Barbier7068f992017-10-26 15:23:08 +0100672 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100673 map(tensor, true);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100674
675 switch(tensor.info()->format())
676 {
677 case arm_compute::Format::U8:
678 {
679 arm_compute::Window window;
680 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, 1));
681 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
682
683 arm_compute::Iterator in(&tensor, window);
684
685 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id)
686 {
687 const unsigned char value = *in.ptr();
688
689 fs << value << value << value;
690 },
691 in);
692
693 break;
694 }
695 case arm_compute::Format::RGB888:
696 {
697 arm_compute::Window window;
698 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, width));
699 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
700
701 arm_compute::Iterator in(&tensor, window);
702
703 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id)
704 {
705 fs.write(reinterpret_cast<std::fstream::char_type *>(in.ptr()), width * tensor.info()->element_size());
706 },
707 in);
708
709 break;
710 }
711 default:
712 ARM_COMPUTE_ERROR("Unsupported format");
713 }
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100714
Anthony Barbier7068f992017-10-26 15:23:08 +0100715 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100716 unmap(tensor);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100717 }
718 catch(const std::ofstream::failure &e)
719 {
720 ARM_COMPUTE_ERROR("Writing %s: (%s)", ppm_filename.c_str(), e.what());
721 }
722}
steniu01bee466b2017-06-21 16:45:41 +0100723
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100724/** Template helper function to save a tensor image to a NPY file.
725 *
Gian Marcobfa3b522017-12-12 10:08:38 +0000726 * @note Only F32 data type supported.
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100727 * @note Only works with 2D tensors.
728 * @note If the input tensor is a CLTensor, the function maps and unmaps the image
729 *
730 * @param[in] tensor The tensor to save as NPY file
731 * @param[in] npy_filename Filename of the file to create.
732 * @param[in] fortran_order If true, save matrix in fortran order.
733 */
734template <typename T>
735void save_to_npy(T &tensor, const std::string &npy_filename, bool fortran_order)
736{
Gian Marcobfa3b522017-12-12 10:08:38 +0000737 ARM_COMPUTE_ERROR_ON_DATA_TYPE_NOT_IN(&tensor, arm_compute::DataType::F32);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100738 ARM_COMPUTE_ERROR_ON(tensor.info()->num_dimensions() > 2);
739
740 std::ofstream fs;
741
742 try
743 {
744 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
745 fs.open(npy_filename, std::ios::out | std::ios::binary);
746
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000747 const unsigned int width = tensor.info()->tensor_shape()[0];
748 const unsigned int height = tensor.info()->tensor_shape()[1];
749 std::vector<npy::ndarray_len_t> shape(2);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100750
751 if(!fortran_order)
752 {
753 shape[0] = height, shape[1] = width;
754 }
755 else
756 {
757 shape[0] = width, shape[1] = height;
758 }
759
760 // Map buffer if creating a CLTensor
761 map(tensor, true);
762
Gian Marcobfa3b522017-12-12 10:08:38 +0000763 switch(tensor.info()->data_type())
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100764 {
Gian Marcobfa3b522017-12-12 10:08:38 +0000765 case arm_compute::DataType::F32:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100766 {
767 std::vector<float> tmp; /* Used only to get the typestring */
768 npy::Typestring typestring_o{ tmp };
769 std::string typestring = typestring_o.str();
770
771 std::ofstream stream(npy_filename, std::ofstream::binary);
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000772 npy::write_header(stream, typestring, fortran_order, shape);
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100773
774 arm_compute::Window window;
775 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, width, 1));
776 window.set(arm_compute::Window::DimY, arm_compute::Window::Dimension(0, height, 1));
777
778 arm_compute::Iterator in(&tensor, window);
779
780 arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id)
781 {
782 stream.write(reinterpret_cast<const char *>(in.ptr()), sizeof(float));
783 },
784 in);
785
786 break;
787 }
788 default:
789 ARM_COMPUTE_ERROR("Unsupported format");
790 }
791
792 // Unmap buffer if creating a CLTensor
793 unmap(tensor);
794 }
795 catch(const std::ofstream::failure &e)
796 {
797 ARM_COMPUTE_ERROR("Writing %s: (%s)", npy_filename.c_str(), e.what());
798 }
799}
800
steniu01bee466b2017-06-21 16:45:41 +0100801/** Load the tensor with pre-trained data from a binary file
802 *
803 * @param[in] tensor The tensor to be filled. Data type supported: F32.
804 * @param[in] filename Filename of the binary file to load from.
805 */
806template <typename T>
807void load_trained_data(T &tensor, const std::string &filename)
808{
809 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
810
811 std::ifstream fs;
812
813 try
814 {
815 fs.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
816 // Open file
817 fs.open(filename, std::ios::in | std::ios::binary);
818
819 if(!fs.good())
820 {
821 throw std::runtime_error("Could not load binary data: " + filename);
822 }
823
Anthony Barbier7068f992017-10-26 15:23:08 +0100824 // Map buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100825 map(tensor, true);
826
steniu01bee466b2017-06-21 16:45:41 +0100827 Window window;
828
829 window.set(arm_compute::Window::DimX, arm_compute::Window::Dimension(0, 1, 1));
830
831 for(unsigned int d = 1; d < tensor.info()->num_dimensions(); ++d)
832 {
833 window.set(d, Window::Dimension(0, tensor.info()->tensor_shape()[d], 1));
834 }
835
836 arm_compute::Iterator in(&tensor, window);
837
838 execute_window_loop(window, [&](const Coordinates & id)
839 {
840 fs.read(reinterpret_cast<std::fstream::char_type *>(in.ptr()), tensor.info()->tensor_shape()[0] * tensor.info()->element_size());
841 },
842 in);
843
Anthony Barbier7068f992017-10-26 15:23:08 +0100844 // Unmap buffer if creating a CLTensor/GCTensor
Georgios Pinitasdc836b62017-09-20 14:02:37 +0100845 unmap(tensor);
steniu01bee466b2017-06-21 16:45:41 +0100846 }
847 catch(const std::ofstream::failure &e)
848 {
849 ARM_COMPUTE_ERROR("Writing %s: (%s)", filename.c_str(), e.what());
850 }
851}
852
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100853template <typename T>
854void fill_random_tensor(T &tensor, float lower_bound, float upper_bound)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100855{
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100856 std::random_device rd;
857 std::mt19937 gen(rd());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100858
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100859 TensorShape shape(tensor.info()->dimension(0), tensor.info()->dimension(1));
860
861 Window window;
862 window.set(Window::DimX, Window::Dimension(0, shape.x(), 1));
863 window.set(Window::DimY, Window::Dimension(0, shape.y(), 1));
864
865 map(tensor, true);
866
867 Iterator it(&tensor, window);
868
Gian Marcobfa3b522017-12-12 10:08:38 +0000869 switch(tensor.info()->data_type())
Anthony Barbier2a07e182017-08-04 18:20:27 +0100870 {
Gian Marcobfa3b522017-12-12 10:08:38 +0000871 case arm_compute::DataType::F32:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100872 {
873 std::uniform_real_distribution<float> dist(lower_bound, upper_bound);
874
875 execute_window_loop(window, [&](const Coordinates & id)
876 {
877 *reinterpret_cast<float *>(it.ptr()) = dist(gen);
878 },
879 it);
880
881 break;
882 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100883 default:
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100884 {
885 ARM_COMPUTE_ERROR("Unsupported format");
886 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100887 }
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100888
889 unmap(tensor);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100890}
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100891
892template <typename T>
Gian Marco0bc5a252017-12-04 13:55:08 +0000893void init_sgemm_output(T &dst, T &src0, T &src1, arm_compute::DataType dt)
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100894{
Gian Marco0bc5a252017-12-04 13:55:08 +0000895 dst.allocator()->init(TensorInfo(TensorShape(src1.info()->dimension(0), src0.info()->dimension(1)), 1, dt));
Giorgio Arenacf3935f2017-10-26 17:14:13 +0100896}
897
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100898} // namespace utils
899} // namespace arm_compute
900#endif /* __UTILS_UTILS_H__*/