blob: 4ecd464cdbfcc70f1bf9e88d78dba71310252b47 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
2 * Copyright (c) 2016, 2017 ARM Limited.
3 *
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 __ARM_COMPUTE_UTILS_H__
25#define __ARM_COMPUTE_UTILS_H__
26
27#include "arm_compute/core/Error.h"
28#include "arm_compute/core/Types.h"
29
30#include <algorithm>
31#include <cstdint>
32#include <cstdlib>
33#include <numeric>
34#include <sstream>
35#include <string>
36#include <type_traits>
37#include <utility>
38
39namespace arm_compute
40{
41/** Computes the smallest number larger or equal to value that is a multiple of divisor. */
42template <typename S, typename T>
43inline auto ceil_to_multiple(S value, T divisor) -> decltype(((value + divisor - 1) / divisor) * divisor)
44{
45 ARM_COMPUTE_ERROR_ON(value < 0 || divisor <= 0);
46 return ((value + divisor - 1) / divisor) * divisor;
47}
48
49/** Computes the largest number smaller or equal to value that is a multiple of divisor. */
50template <typename S, typename T>
51inline auto floor_to_multiple(S value, T divisor) -> decltype((value / divisor) * divisor)
52{
53 ARM_COMPUTE_ERROR_ON(value < 0 || divisor <= 0);
54 return (value / divisor) * divisor;
55}
56
57/** Calculate the rounded up quotient of val / m. */
58template <typename S, typename T>
59constexpr auto DIV_CEIL(S val, T m) -> decltype((val + m - 1) / m)
60{
61 return (val + m - 1) / m;
62}
63
64/** Returns the arm_compute library build information
65 *
66 * Contains the version number and the build options used to build the library
67 *
68 * @return The arm_compute library build information
69 */
70std::string build_information();
71
72/** Load an entire file in memory
73 *
74 * @param[in] filename Name of the file to read.
75 * @param[in] binary Is it a binary file ?
76 *
77 * @return The content of the file.
78 */
79std::string read_file(const std::string &filename, bool binary);
80
Anthony Barbier6ff3b192017-09-04 18:44:23 +010081/** The size in bytes of the data type
82 *
83 * @param[in] data_type Input data type
84 *
85 * @return The size in bytes of the data type
86 */
87inline size_t data_size_from_type(DataType data_type)
88{
89 switch(data_type)
90 {
91 case DataType::U8:
92 case DataType::S8:
93 case DataType::QS8:
94 return 1;
95 case DataType::U16:
96 case DataType::S16:
97 case DataType::F16:
98 case DataType::QS16:
99 return 2;
100 case DataType::F32:
101 case DataType::U32:
102 case DataType::S32:
103 return 4;
104 case DataType::F64:
105 case DataType::U64:
106 case DataType::S64:
107 return 8;
108 case DataType::SIZET:
109 return sizeof(size_t);
110 default:
111 ARM_COMPUTE_ERROR("Invalid data type");
112 return 0;
113 }
114}
115
116/** The size in bytes of the pixel format
117 *
118 * @param[in] format Input format
119 *
120 * @return The size in bytes of the pixel format
121 */
122inline size_t pixel_size_from_format(Format format)
123{
124 switch(format)
125 {
126 case Format::U8:
127 return 1;
128 case Format::U16:
129 case Format::S16:
130 case Format::F16:
131 case Format::UV88:
132 case Format::YUYV422:
133 case Format::UYVY422:
134 return 2;
135 case Format::RGB888:
136 return 3;
137 case Format::RGBA8888:
138 return 4;
139 case Format::U32:
140 case Format::S32:
141 case Format::F32:
142 return 4;
143 //Doesn't make sense for planar formats:
144 case Format::NV12:
145 case Format::NV21:
146 case Format::IYUV:
147 case Format::YUV444:
148 default:
149 ARM_COMPUTE_ERROR("Undefined pixel size for given format");
150 return 0;
151 }
152}
153
154/** The size in bytes of the data type
155 *
156 * @param[in] dt Input data type
157 *
158 * @return The size in bytes of the data type
159 */
160inline size_t element_size_from_data_type(DataType dt)
161{
162 switch(dt)
163 {
164 case DataType::S8:
165 case DataType::U8:
166 case DataType::QS8:
167 return 1;
168 case DataType::U16:
169 case DataType::S16:
170 case DataType::QS16:
171 case DataType::F16:
172 return 2;
173 case DataType::U32:
174 case DataType::S32:
175 case DataType::F32:
176 return 4;
177 default:
178 ARM_COMPUTE_ERROR("Undefined element size for given data type");
179 return 0;
180 }
181}
182
183/** Return the data type used by a given single-planar pixel format
184 *
185 * @param[in] format Input format
186 *
187 * @return The size in bytes of the pixel format
188 */
189inline DataType data_type_from_format(Format format)
190{
191 switch(format)
192 {
193 case Format::U8:
194 case Format::UV88:
195 case Format::RGB888:
196 case Format::RGBA8888:
197 case Format::YUYV422:
198 case Format::UYVY422:
199 return DataType::U8;
200 case Format::U16:
201 return DataType::U16;
202 case Format::S16:
203 return DataType::S16;
204 case Format::U32:
205 return DataType::U32;
206 case Format::S32:
207 return DataType::S32;
208 case Format::F16:
209 return DataType::F16;
210 case Format::F32:
211 return DataType::F32;
212 //Doesn't make sense for planar formats:
213 case Format::NV12:
214 case Format::NV21:
215 case Format::IYUV:
216 case Format::YUV444:
217 default:
218 ARM_COMPUTE_ERROR("Not supported data_type for given format");
219 return DataType::UNKNOWN;
220 }
221}
222
223/** Return the plane index of a given channel given an input format.
224 *
225 * @param[in] format Input format
226 * @param[in] channel Input channel
227 *
228 * @return The plane index of the specific channel of the specific format
229 */
230inline int plane_idx_from_channel(Format format, Channel channel)
231{
232 switch(format)
233 {
234 case Format::NV12:
235 case Format::NV21:
236 {
237 switch(channel)
238 {
239 case Channel::Y:
240 return 0;
241 case Channel::U:
242 case Channel::V:
243 return 1;
244 default:
245 ARM_COMPUTE_ERROR("Not supported channel");
246 return 0;
247 }
248 }
249 case Format::IYUV:
250 case Format::YUV444:
251 {
252 switch(channel)
253 {
254 case Channel::Y:
255 return 0;
256 case Channel::U:
257 return 1;
258 case Channel::V:
259 return 2;
260 default:
261 ARM_COMPUTE_ERROR("Not supported channel");
262 return 0;
263 }
264 }
265 default:
266 ARM_COMPUTE_ERROR("Not supported format");
267 return 0;
268 }
269}
270
271/** Return the number of planes for a given format
272 *
273 * @param[in] format Input format
274 *
275 * @return The number of planes for a given image format.
276 */
277inline size_t num_planes_from_format(Format format)
278{
279 switch(format)
280 {
281 case Format::U8:
282 case Format::S16:
283 case Format::U16:
284 case Format::S32:
285 case Format::U32:
286 case Format::F16:
287 case Format::F32:
288 case Format::RGB888:
289 case Format::RGBA8888:
290 case Format::YUYV422:
291 case Format::UYVY422:
292 return 1;
293 case Format::NV12:
294 case Format::NV21:
295 return 2;
296 case Format::IYUV:
297 case Format::YUV444:
298 return 3;
299 default:
300 ARM_COMPUTE_ERROR("Not supported format");
301 return 0;
302 }
303}
304
305/** Return the number of channels for a given single-planar pixel format
306 *
307 * @param[in] format Input format
308 *
309 * @return The number of channels for a given image format.
310 */
311inline size_t num_channels_from_format(Format format)
312{
313 switch(format)
314 {
315 case Format::U8:
316 case Format::U16:
317 case Format::S16:
318 case Format::U32:
319 case Format::S32:
320 case Format::F16:
321 case Format::F32:
322 return 1;
323 // Because the U and V channels are subsampled
324 // these formats appear like having only 2 channels:
325 case Format::YUYV422:
326 case Format::UYVY422:
327 return 2;
328 case Format::UV88:
329 return 2;
330 case Format::RGB888:
331 return 3;
332 case Format::RGBA8888:
333 return 4;
334 //Doesn't make sense for planar formats:
335 case Format::NV12:
336 case Format::NV21:
337 case Format::IYUV:
338 case Format::YUV444:
339 default:
340 return 0;
341 }
342}
343
344/** Separate a 2D convolution into two 1D convolutions
345*
346* @param[in] conv 2D convolution
347* @param[out] conv_col 1D vertical convolution
348* @param[out] conv_row 1D horizontal convolution
349* @param[in] size Size of the 2D convolution
350*
351* @return true if the separation was successful
352*/
353inline bool separate_matrix(const int16_t *conv, int16_t *conv_col, int16_t *conv_row, uint8_t size)
354{
355 int32_t min_col = -1;
356 int16_t min_col_val = -1;
357
358 for(int32_t i = 0; i < size; ++i)
359 {
360 if(conv[i] != 0 && (min_col < 0 || abs(min_col_val) > abs(conv[i])))
361 {
362 min_col = i;
363 min_col_val = conv[i];
364 }
365 }
366
367 if(min_col < 0)
368 {
369 return false;
370 }
371
372 for(uint32_t j = 0; j < size; ++j)
373 {
374 conv_col[j] = conv[min_col + j * size];
375 }
376
377 for(uint32_t i = 0; i < size; i++)
378 {
379 if(static_cast<int>(i) == min_col)
380 {
381 conv_row[i] = 1;
382 }
383 else
384 {
385 int16_t coeff = conv[i] / conv[min_col];
386
387 for(uint32_t j = 1; j < size; ++j)
388 {
389 if(conv[i + j * size] != (conv_col[j] * coeff))
390 {
391 return false;
392 }
393 }
394
395 conv_row[i] = coeff;
396 }
397 }
398
399 return true;
400}
401
402/** Calculate the scale of the given square matrix
403 *
404 * The scale is the absolute value of the sum of all the coefficients in the matrix.
405 *
406 * @note If the coefficients add up to 0 then the scale is set to 1.
407 *
408 * @param[in] matrix Matrix coefficients
409 * @param[in] matrix_size Number of elements per side of the square matrix. (Number of coefficients = matrix_size * matrix_size).
410 *
411 * @return The absolute value of the sum of the coefficients if they don't add up to 0, otherwise 1.
412 */
413inline uint32_t calculate_matrix_scale(const int16_t *matrix, unsigned int matrix_size)
414{
415 const size_t size = matrix_size * matrix_size;
416
417 return std::max(1, std::abs(std::accumulate(matrix, matrix + size, 0)));
418}
419
420/** Calculate accurary required by the horizontal and vertical convolution computations
421 *
422 * @param[in] conv_col Pointer to the vertical vector of the separated convolution filter
423 * @param[in] conv_row Pointer to the horizontal vector of the convolution filter
424 * @param[in] size Number of elements per vector of the separated matrix
425 *
426 * @return The return type is a pair. The first element of the pair is the biggest data type needed for the first stage. The second
427 * element of the pair is the biggest data type needed for the second stage.
428 */
429inline std::pair<DataType, DataType> data_type_for_convolution(const int16_t *conv_col, const int16_t *conv_row, size_t size)
430{
431 DataType first_stage = DataType::UNKNOWN;
432 DataType second_stage = DataType::UNKNOWN;
433
434 auto gez = [](const int16_t &v)
435 {
436 return v >= 0;
437 };
438
439 auto accu_neg = [](const int &first, const int &second)
440 {
441 return first + (second < 0 ? second : 0);
442 };
443
444 auto accu_pos = [](const int &first, const int &second)
445 {
446 return first + (second > 0 ? second : 0);
447 };
448
449 const bool only_positive_coefficients = std::all_of(conv_row, conv_row + size, gez) && std::all_of(conv_col, conv_col + size, gez);
450
451 if(only_positive_coefficients)
452 {
453 const int max_row_value = std::accumulate(conv_row, conv_row + size, 0) * UINT8_MAX;
454 const int max_value = std::accumulate(conv_col, conv_col + size, 0) * max_row_value;
455
456 first_stage = (max_row_value <= UINT16_MAX) ? DataType::U16 : DataType::S32;
457
458 second_stage = (max_value <= UINT16_MAX) ? DataType::U16 : DataType::S32;
459 }
460 else
461 {
462 const int min_row_value = std::accumulate(conv_row, conv_row + size, 0, accu_neg) * UINT8_MAX;
463 const int max_row_value = std::accumulate(conv_row, conv_row + size, 0, accu_pos) * UINT8_MAX;
464 const int neg_coeffs_sum = std::accumulate(conv_col, conv_col + size, 0, accu_neg);
465 const int pos_coeffs_sum = std::accumulate(conv_col, conv_col + size, 0, accu_pos);
466 const int min_value = neg_coeffs_sum * max_row_value + pos_coeffs_sum * min_row_value;
467 const int max_value = neg_coeffs_sum * min_row_value + pos_coeffs_sum * max_row_value;
468
469 first_stage = ((INT16_MIN <= min_row_value) && (max_row_value <= INT16_MAX)) ? DataType::S16 : DataType::S32;
470
471 second_stage = ((INT16_MIN <= min_value) && (max_value <= INT16_MAX)) ? DataType::S16 : DataType::S32;
472 }
473
474 return std::make_pair(first_stage, second_stage);
475}
476
477/** Calculate the accuracy required by the squared convolution calculation.
478 *
479 *
480 * @param[in] conv Pointer to the squared convolution matrix
481 * @param[in] size The total size of the convolution matrix
482 *
483 * @return The return is the biggest data type needed to do the convolution
484 */
485inline DataType data_type_for_convolution_matrix(const int16_t *conv, size_t size)
486{
487 auto gez = [](const int16_t v)
488 {
489 return v >= 0;
490 };
491
492 const bool only_positive_coefficients = std::all_of(conv, conv + size, gez);
493
494 if(only_positive_coefficients)
495 {
496 const int max_conv_value = std::accumulate(conv, conv + size, 0) * UINT8_MAX;
497 if(max_conv_value <= UINT16_MAX)
498 {
499 return DataType::U16;
500 }
501 else
502 {
503 return DataType::S32;
504 }
505 }
506 else
507 {
508 const int min_value = std::accumulate(conv, conv + size, 0, [](int a, int b)
509 {
510 return b < 0 ? a + b : a;
511 })
512 * UINT8_MAX;
513
514 const int max_value = std::accumulate(conv, conv + size, 0, [](int a, int b)
515 {
516 return b > 0 ? a + b : a;
517 })
518 * UINT8_MAX;
519
520 if((INT16_MIN <= min_value) && (INT16_MAX >= max_value))
521 {
522 return DataType::S16;
523 }
524 else
525 {
526 return DataType::S32;
527 }
528 }
529}
530
531/** Returns expected width and height of output scaled tensor depending on dimensions rounding mode.
532 *
Gian Marco Iodice4e288692017-06-27 11:41:59 +0100533 * @param[in] width Width of input tensor (Number of columns)
534 * @param[in] height Height of input tensor (Number of rows)
535 * @param[in] kernel_width Kernel width.
536 * @param[in] kernel_height Kernel height.
537 * @param[in] pad_stride_info Pad and stride information.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100538 *
539 * @return A pair with the new width in the first position and the new height in the second.
540 */
Gian Marco Iodice4e288692017-06-27 11:41:59 +0100541const std::pair<unsigned int, unsigned int> scaled_dimensions(unsigned int width, unsigned int height,
542 unsigned int kernel_width, unsigned int kernel_height,
543 const PadStrideInfo &pad_stride_info);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100544
545/** Convert a tensor format into a string.
546 *
547 * @param[in] format @ref Format to be translated to string.
548 *
549 * @return The string describing the format.
550 */
551const std::string &string_from_format(Format format);
552
553/** Convert a channel identity into a string.
554 *
555 * @param[in] channel @ref Channel to be translated to string.
556 *
557 * @return The string describing the channel.
558 */
559const std::string &string_from_channel(Channel channel);
560
561/** Convert a data type identity into a string.
562 *
563 * @param[in] dt @ref DataType to be translated to string.
564 *
565 * @return The string describing the data type.
566 */
567const std::string &string_from_data_type(DataType dt);
568/** Convert a matrix pattern into a string.
569 *
570 * @param[in] pattern @ref MatrixPattern to be translated to string.
571 *
572 * @return The string describing the matrix pattern.
573 */
574const std::string &string_from_matrix_pattern(MatrixPattern pattern);
575/** Translates a given activation function to a string.
576 *
577 * @param[in] act @ref ActivationLayerInfo::ActivationFunction to be translated to string.
578 *
579 * @return The string describing the activation function.
580 */
581const std::string &string_from_activation_func(ActivationLayerInfo::ActivationFunction act);
582/** Translates a given non linear function to a string.
583 *
584 * @param[in] function @ref NonLinearFilterFunction to be translated to string.
585 *
586 * @return The string describing the non linear function.
587 */
588const std::string &string_from_non_linear_filter_function(NonLinearFilterFunction function);
589/** Translates a given interpolation policy to a string.
590 *
591 * @param[in] policy @ref InterpolationPolicy to be translated to string.
592 *
593 * @return The string describing the interpolation policy.
594 */
595const std::string &string_from_interpolation_policy(InterpolationPolicy policy);
596/** Translates a given border mode policy to a string.
597 *
598 * @param[in] border_mode @ref BorderMode to be translated to string.
599 *
600 * @return The string describing the border mode.
601 */
602const std::string &string_from_border_mode(BorderMode border_mode);
603/** Translates a given normalization type to a string.
604 *
605 * @param[in] type @ref NormType to be translated to string.
606 *
607 * @return The string describing the normalization type.
608 */
609const std::string &string_from_norm_type(NormType type);
610/** Lower a given string.
611 *
612 * @param[in] val Given string to lower.
613 *
614 * @return The lowered string
615 */
616std::string lower_string(const std::string &val);
617
618/** Check if a given data type is of floating point type
619 *
620 * @param[in] dt Input data type.
621 *
622 * @return True if data type is of floating point type, else false.
623 */
624inline bool is_data_type_float(DataType dt)
625{
626 switch(dt)
627 {
628 case DataType::F16:
629 case DataType::F32:
630 return true;
631 default:
632 return false;
633 }
634}
635
636/** Check if a given data type is of fixed point type
637 *
638 * @param[in] dt Input data type.
639 *
640 * @return True if data type is of fixed point type, else false.
641 */
642inline bool is_data_type_fixed_point(DataType dt)
643{
644 switch(dt)
645 {
646 case DataType::QS8:
647 case DataType::QS16:
648 return true;
649 default:
650 return false;
651 }
652}
653
654/** Print consecutive elements to an output stream.
655 *
656 * @param[out] s Output stream to print the elements to.
657 * @param[in] ptr Pointer to print the elements from.
658 * @param[in] n Number of elements to print.
659 * @param[in] stream_width (Optional) Width of the stream. If set to 0 the element's width is used. Defaults to 0.
660 * @param[in] element_delim (Optional) Delimeter among the consecutive elements. Defaults to space delimeter
661 */
662template <typename T>
663void print_consecutive_elements_impl(std::ostream &s, const T *ptr, unsigned int n, int stream_width = 0, const std::string &element_delim = " ")
664{
665 using print_type = typename std::conditional<std::is_floating_point<T>::value, T, int>::type;
666
667 for(unsigned int i = 0; i < n; ++i)
668 {
669 // Set stream width as it is not a "sticky" stream manipulator
670 if(stream_width != 0)
671 {
672 s.width(stream_width);
673 }
674 s << std::right << static_cast<print_type>(ptr[i]) << element_delim;
675 }
676}
677
678/** Identify the maximum width of n consecutive elements.
679 *
680 * @param[in] s The output stream which will be used to print the elements. Used to extract the stream format.
681 * @param[in] ptr Pointer to the elements.
682 * @param[in] n Number of elements.
683 *
684 * @return The maximum width of the elements.
685 */
686template <typename T>
687int max_consecutive_elements_display_width_impl(std::ostream &s, const T *ptr, unsigned int n)
688{
689 using print_type = typename std::conditional<std::is_floating_point<T>::value, T, int>::type;
690
691 int max_width = -1;
692 for(unsigned int i = 0; i < n; ++i)
693 {
694 std::stringstream ss;
695 ss.copyfmt(s);
696 ss << static_cast<print_type>(ptr[i]);
697 max_width = std::max<int>(max_width, ss.str().size());
698 }
699 return max_width;
700}
701
702/** Print consecutive elements to an output stream.
703 *
704 * @param[out] s Output stream to print the elements to.
705 * @param[in] dt Data type of the elements
706 * @param[in] ptr Pointer to print the elements from.
707 * @param[in] n Number of elements to print.
708 * @param[in] stream_width (Optional) Width of the stream. If set to 0 the element's width is used. Defaults to 0.
709 * @param[in] element_delim (Optional) Delimeter among the consecutive elements. Defaults to space delimeter
710 */
711void print_consecutive_elements(std::ostream &s, DataType dt, const uint8_t *ptr, unsigned int n, int stream_width, const std::string &element_delim = " ");
712
713/** Identify the maximum width of n consecutive elements.
714 *
715 * @param[in] s Output stream to print the elements to.
716 * @param[in] dt Data type of the elements
717 * @param[in] ptr Pointer to print the elements from.
718 * @param[in] n Number of elements to print.
719 *
720 * @return The maximum width of the elements.
721 */
722int max_consecutive_elements_display_width(std::ostream &s, DataType dt, const uint8_t *ptr, unsigned int n);
723}
724#endif /*__ARM_COMPUTE_UTILS_H__ */