blob: c5b50167bf6eaecd4b3d2f471dc6ac3877adc3c2 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
Matthew Benthamf1aeab92023-05-30 13:35:34 +00002 * Copyright (c) 2016-2023 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 */
Michalis Spyrouf4643372019-11-29 16:17:13 +000024#ifndef ARM_COMPUTE_UTILS_H
25#define ARM_COMPUTE_UTILS_H
Anthony Barbier6ff3b192017-09-04 18:44:23 +010026
27#include "arm_compute/core/Error.h"
Giuseppe Rossinid7647d42018-07-17 18:13:13 +010028#include "arm_compute/core/PixelValue.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010029#include "arm_compute/core/Types.h"
30
Matthew Bentham314d3e22023-06-23 10:53:52 +000031#include <cmath>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010032#include <numeric>
33#include <sstream>
34#include <string>
35#include <type_traits>
Giorgio Arena1e2af2a2020-10-15 17:39:41 +010036#include <unordered_map>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010037#include <utility>
Matthew Bentham314d3e22023-06-23 10:53:52 +000038
39/* Convenience / backwards compatibility includes */
40#include "arm_compute/core/utils/ActivationFunctionUtils.h"
41#include "arm_compute/core/utils/DataLayoutUtils.h"
42#include "arm_compute/core/utils/DataTypeUtils.h"
43#include "arm_compute/core/utils/FormatUtils.h"
44#include "arm_compute/core/utils/InterpolationPolicyUtils.h"
45#include "arm_compute/core/utils/StringUtils.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010046
47namespace arm_compute
48{
Giorgio Arena1e2af2a2020-10-15 17:39:41 +010049class ITensor;
Giorgio Arena4112eed2020-10-23 14:24:26 +010050class ITensorInfo;
Matthew Benthamf1aeab92023-05-30 13:35:34 +000051class ActivationLayerInfo;
Giorgio Arena1e2af2a2020-10-15 17:39:41 +010052
Anthony Barbier6ff3b192017-09-04 18:44:23 +010053/** Load an entire file in memory
54 *
55 * @param[in] filename Name of the file to read.
56 * @param[in] binary Is it a binary file ?
57 *
58 * @return The content of the file.
59 */
60std::string read_file(const std::string &filename, bool binary);
61
Pablo Tello35767bc2018-12-05 17:36:30 +000062/** Permutes the given dimensions according the permutation vector
63 *
64 * @param[in,out] dimensions Dimensions to be permuted.
65 * @param[in] perm Vector describing the permutation.
66 *
67 */
68template <typename T>
69inline void permute_strides(Dimensions<T> &dimensions, const PermutationVector &perm)
70{
71 const auto old_dim = utility::make_array<Dimensions<T>::num_max_dimensions>(dimensions.begin(), dimensions.end());
72 for(unsigned int i = 0; i < perm.num_dimensions(); ++i)
73 {
74 T dimension_val = old_dim[i];
75 dimensions.set(perm[i], dimension_val);
76 }
77}
78
Georgios Pinitas4074c992018-01-30 18:13:46 +000079/** Calculate padding requirements in case of SAME padding
80 *
81 * @param[in] input_shape Input shape
82 * @param[in] weights_shape Weights shape
83 * @param[in] conv_info Convolution information (containing strides)
Isabella Gottardi6a914402019-01-30 15:45:42 +000084 * @param[in] data_layout (Optional) Data layout of the input and weights tensor
Pablo Tello01bbacb2019-04-30 10:32:42 +010085 * @param[in] dilation (Optional) Dilation factor used in the convolution.
Giorgio Arena17203582019-08-02 16:00:41 +010086 * @param[in] rounding_type (Optional) Dimension rounding type when down-scaling.
Georgios Pinitas4074c992018-01-30 18:13:46 +000087 *
88 * @return PadStrideInfo for SAME padding
89 */
Giorgio Arena17203582019-08-02 16:00:41 +010090PadStrideInfo calculate_same_pad(TensorShape input_shape, TensorShape weights_shape, PadStrideInfo conv_info, DataLayout data_layout = DataLayout::NCHW, const Size2D &dilation = Size2D(1u, 1u),
91 const DimensionRoundingType &rounding_type = DimensionRoundingType::FLOOR);
Georgios Pinitas4074c992018-01-30 18:13:46 +000092
Pablo Tellof5f34bb2017-08-22 13:34:13 +010093/** Returns expected width and height of the deconvolution's output tensor.
94 *
Matthew Jacksonb9070a42019-08-22 16:13:27 +010095 * @param[in] in_width Width of input tensor (Number of columns)
96 * @param[in] in_height Height of input tensor (Number of rows)
97 * @param[in] kernel_width Kernel width.
98 * @param[in] kernel_height Kernel height.
99 * @param[in] pad_stride_info Pad and stride information.
Pablo Tellof5f34bb2017-08-22 13:34:13 +0100100 *
101 * @return A pair with the new width in the first position and the new height in the second.
102 */
Pablo Tello01bbacb2019-04-30 10:32:42 +0100103std::pair<unsigned int, unsigned int> deconvolution_output_dimensions(unsigned int in_width, unsigned int in_height,
104 unsigned int kernel_width, unsigned int kernel_height,
Matthew Jacksonb9070a42019-08-22 16:13:27 +0100105 const PadStrideInfo &pad_stride_info);
Pablo Tellof5f34bb2017-08-22 13:34:13 +0100106
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100107/** Returns expected width and height of output scaled tensor depending on dimensions rounding mode.
108 *
Gian Marco Iodice4e288692017-06-27 11:41:59 +0100109 * @param[in] width Width of input tensor (Number of columns)
110 * @param[in] height Height of input tensor (Number of rows)
111 * @param[in] kernel_width Kernel width.
112 * @param[in] kernel_height Kernel height.
113 * @param[in] pad_stride_info Pad and stride information.
Alex Gilday7da29b62018-03-23 14:16:00 +0000114 * @param[in] dilation (Optional) Dilation, in elements, across x and y. Defaults to (1, 1).
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100115 *
116 * @return A pair with the new width in the first position and the new height in the second.
117 */
Georgios Pinitas80838f12019-12-12 18:23:13 +0000118std::pair<unsigned int, unsigned int> scaled_dimensions(int width, int height,
119 int kernel_width, int kernel_height,
Pablo Tello01bbacb2019-04-30 10:32:42 +0100120 const PadStrideInfo &pad_stride_info,
121 const Size2D &dilation = Size2D(1U, 1U));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100122
Freddie Liardetafcbb8f2021-05-04 12:41:16 +0100123/** Returns calculated width and height of output scaled tensor depending on dimensions rounding mode.
124 *
125 * @param[in] width Width of input tensor (Number of columns)
126 * @param[in] height Height of input tensor (Number of rows)
127 * @param[in] kernel_width Kernel width.
128 * @param[in] kernel_height Kernel height.
129 * @param[in] pad_stride_info Pad and stride information.
130 *
131 * @return A pair with the new width in the first position and the new height in the second, returned values can be < 1
132 */
133std::pair<int, int> scaled_dimensions_signed(int width, int height,
134 int kernel_width, int kernel_height,
135 const PadStrideInfo &pad_stride_info);
136
ramelg0137515692022-02-26 22:06:20 +0000137/** Returns calculated width, height and depth of output scaled tensor depending on dimensions rounding mode.
138 *
139 * @param[in] width Width of input tensor
140 * @param[in] height Height of input tensor
141 * @param[in] depth Depth of input tensor
142 * @param[in] kernel_width Kernel width.
143 * @param[in] kernel_height Kernel height.
144 * @param[in] kernel_depth Kernel depth.
145 * @param[in] pool3d_info Pad and stride and round information for 3d pooling
146 *
147 * @return A tuple with the new width in the first position, the new height in the second, and the new depth in the third.
148 * Returned values can be < 1
149 */
150std::tuple<int, int, int> scaled_3d_dimensions_signed(int width, int height, int depth,
151 int kernel_width, int kernel_height, int kernel_depth,
152 const Pooling3dLayerInfo &pool3d_info);
153
Sang-Hoon Park2697fd82019-10-15 16:49:24 +0100154/** Check if the given reduction operation should be handled in a serial way.
155 *
156 * @param[in] op Reduction operation to perform
157 * @param[in] dt Data type
158 * @param[in] axis Axis along which to reduce
159 *
160 * @return True if the given reduction operation should be handled in a serial way.
161 */
162bool needs_serialized_reduction(ReductionOperation op, DataType dt, unsigned int axis);
163
Sang-Hoon Park0779fec2019-11-13 17:08:12 +0000164/** Returns output quantization information for softmax layer
165 *
166 * @param[in] input_type The data type of the input tensor
167 * @param[in] is_log True for log softmax
168 *
169 * @return Quantization information for the output tensor
170 */
171QuantizationInfo get_softmax_output_quantization_info(DataType input_type, bool is_log);
172
Sang-Hoon Park4715cf92020-01-08 16:02:47 +0000173/** Returns a pair of minimum and maximum values for a quantized activation
174 *
175 * @param[in] act_info The information for activation
176 * @param[in] data_type The used data type
177 * @param[in] oq_info The output quantization information
178 *
179 * @return The pair with minimum and maximum values
180 */
Pablo Marquez Tello205ba242023-07-12 14:29:58 +0100181std::pair<int32_t, int32_t> get_quantized_activation_min_max(const ActivationLayerInfo &act_info, DataType data_type, UniformQuantizationInfo oq_info);
Sang-Hoon Park4715cf92020-01-08 16:02:47 +0000182
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100183/** Convert a channel identity into a string.
184 *
185 * @param[in] channel @ref Channel to be translated to string.
186 *
187 * @return The string describing the channel.
188 */
189const std::string &string_from_channel(Channel channel);
Matthew Bentham314d3e22023-06-23 10:53:52 +0000190
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100191/** Translates a given border mode policy to a string.
192 *
193 * @param[in] border_mode @ref BorderMode to be translated to string.
194 *
195 * @return The string describing the border mode.
196 */
197const std::string &string_from_border_mode(BorderMode border_mode);
198/** Translates a given normalization type to a string.
199 *
200 * @param[in] type @ref NormType to be translated to string.
201 *
202 * @return The string describing the normalization type.
203 */
204const std::string &string_from_norm_type(NormType type);
Georgios Pinitascdf51452017-08-31 14:21:36 +0100205/** Translates a given pooling type to a string.
206 *
207 * @param[in] type @ref PoolingType to be translated to string.
208 *
209 * @return The string describing the pooling type.
210 */
211const std::string &string_from_pooling_type(PoolingType type);
SiCongLic4270cf2021-12-22 11:22:40 +0000212/** Check if the pool region is entirely outside the input tensor
213 *
214 * @param[in] info @ref PoolingLayerInfo to be checked.
215 *
216 * @return True if the pool region is entirely outside the input tensor, False otherwise.
217 */
218bool is_pool_region_entirely_outside_input(const PoolingLayerInfo &info);
ramelg0137515692022-02-26 22:06:20 +0000219/** Check if the 3d pool region is entirely outside the input tensor
220 *
221 * @param[in] info @ref Pooling3dLayerInfo to be checked.
222 *
223 * @return True if the pool region is entirely outside the input tensor, False otherwise.
224 */
225bool is_pool_3d_region_entirely_outside_input(const Pooling3dLayerInfo &info);
226/** Check if the 3D padding is symmetric i.e. padding in each opposite sides are euqal (left=right, top=bottom and front=back)
227 *
228 * @param[in] info @ref Padding3D input 3D padding object to check if it is symmetric
229 *
230 * @return True if padding is symmetric
231 */
Pablo Marquez Tello205ba242023-07-12 14:29:58 +0100232inline bool is_symmetric(const Padding3D &info)
ramelg0137515692022-02-26 22:06:20 +0000233{
234 return ((info.left == info.right) && (info.top == info.bottom) && (info.front == info.back));
235}
Gian Marco Iodice4b908652018-10-18 10:21:02 +0100236/** Translates a given GEMMLowp output stage to a string.
237 *
238 * @param[in] output_stage @ref GEMMLowpOutputStageInfo to be translated to string.
239 *
240 * @return The string describing the GEMMLowp output stage
241 */
242const std::string &string_from_gemmlowp_output_stage(GEMMLowpOutputStageType output_stage);
Giuseppe Rossinid7647d42018-07-17 18:13:13 +0100243/** Convert a PixelValue to a string, represented through the specific data type
244 *
245 * @param[in] value The PixelValue to convert
246 * @param[in] data_type The type to be used to convert the @p value
247 *
248 * @return String representation of the PixelValue through the given data type.
249 */
250std::string string_from_pixel_value(const PixelValue &value, const DataType data_type);
Matthew Bentham314d3e22023-06-23 10:53:52 +0000251
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100252/** Stores padding information before configuring a kernel
253 *
Giorgio Arena4112eed2020-10-23 14:24:26 +0100254 * @param[in] infos list of tensor infos to store the padding info for
255 *
256 * @return An unordered map where each tensor info pointer is paired with its original padding info
257 */
258std::unordered_map<const ITensorInfo *, PaddingSize> get_padding_info(std::initializer_list<const ITensorInfo *> infos);
259/** Stores padding information before configuring a kernel
260 *
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100261 * @param[in] tensors list of tensors to store the padding info for
262 *
Giorgio Arena4112eed2020-10-23 14:24:26 +0100263 * @return An unordered map where each tensor info pointer is paired with its original padding info
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100264 */
Giorgio Arena4112eed2020-10-23 14:24:26 +0100265std::unordered_map<const ITensorInfo *, PaddingSize> get_padding_info(std::initializer_list<const ITensor *> tensors);
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100266/** Check if the previously stored padding info has changed after configuring a kernel
267 *
Giorgio Arena4112eed2020-10-23 14:24:26 +0100268 * @param[in] padding_map an unordered map where each tensor info pointer is paired with its original padding info
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100269 *
Giorgio Arena4112eed2020-10-23 14:24:26 +0100270 * @return true if any of the tensor infos has changed its paddings
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100271 */
Giorgio Arena4112eed2020-10-23 14:24:26 +0100272bool has_padding_changed(const std::unordered_map<const ITensorInfo *, PaddingSize> &padding_map);
Giorgio Arena1e2af2a2020-10-15 17:39:41 +0100273
Michalis Spyrouf63885b2019-01-16 14:18:09 +0000274/** Returns the number of elements required to go from start to end with the wanted step
275 *
276 * @param[in] start start value
277 * @param[in] end end value
278 * @param[in] step step value between each number in the wanted sequence
279 *
280 * @return number of elements to go from start value to end value using the wanted step
281 */
282inline size_t num_of_elements_in_range(const float start, const float end, const float step)
283{
284 ARM_COMPUTE_ERROR_ON_MSG(step == 0, "Range Step cannot be 0");
285 return size_t(std::ceil((end - start) / step));
286}
287
giuros01edc21e42018-11-16 14:45:31 +0000288#ifdef ARM_COMPUTE_ASSERTS_ENABLED
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100289/** Print consecutive elements to an output stream.
290 *
291 * @param[out] s Output stream to print the elements to.
292 * @param[in] ptr Pointer to print the elements from.
293 * @param[in] n Number of elements to print.
294 * @param[in] stream_width (Optional) Width of the stream. If set to 0 the element's width is used. Defaults to 0.
295 * @param[in] element_delim (Optional) Delimeter among the consecutive elements. Defaults to space delimeter
296 */
297template <typename T>
298void print_consecutive_elements_impl(std::ostream &s, const T *ptr, unsigned int n, int stream_width = 0, const std::string &element_delim = " ")
299{
300 using print_type = typename std::conditional<std::is_floating_point<T>::value, T, int>::type;
Michalis Spyrou53860dd2019-07-01 14:20:56 +0100301 std::ios stream_status(nullptr);
302 stream_status.copyfmt(s);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100303
304 for(unsigned int i = 0; i < n; ++i)
305 {
306 // Set stream width as it is not a "sticky" stream manipulator
307 if(stream_width != 0)
308 {
309 s.width(stream_width);
310 }
Anthony Barbier7068f992017-10-26 15:23:08 +0100311
312 if(std::is_same<typename std::decay<T>::type, half>::value)
313 {
314 // We use T instead of print_type here is because the std::is_floating_point<half> returns false and then the print_type becomes int.
315 s << std::right << static_cast<T>(ptr[i]) << element_delim;
316 }
Georgios Pinitase8291ac2020-02-26 09:58:13 +0000317 else if(std::is_same<typename std::decay<T>::type, bfloat16>::value)
318 {
Georgios Pinitasc7b183a2020-03-06 18:12:09 +0000319 // We use T instead of print_type here is because the std::is_floating_point<bfloat16> returns false and then the print_type becomes int.
Georgios Pinitase8291ac2020-02-26 09:58:13 +0000320 s << std::right << float(ptr[i]) << element_delim;
321 }
Anthony Barbier7068f992017-10-26 15:23:08 +0100322 else
323 {
324 s << std::right << static_cast<print_type>(ptr[i]) << element_delim;
325 }
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100326 }
Michalis Spyrou53860dd2019-07-01 14:20:56 +0100327
328 // Restore output stream flags
329 s.copyfmt(stream_status);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100330}
331
332/** Identify the maximum width of n consecutive elements.
333 *
334 * @param[in] s The output stream which will be used to print the elements. Used to extract the stream format.
335 * @param[in] ptr Pointer to the elements.
336 * @param[in] n Number of elements.
337 *
338 * @return The maximum width of the elements.
339 */
340template <typename T>
341int max_consecutive_elements_display_width_impl(std::ostream &s, const T *ptr, unsigned int n)
342{
343 using print_type = typename std::conditional<std::is_floating_point<T>::value, T, int>::type;
344
345 int max_width = -1;
346 for(unsigned int i = 0; i < n; ++i)
347 {
348 std::stringstream ss;
349 ss.copyfmt(s);
Anthony Barbier7068f992017-10-26 15:23:08 +0100350
351 if(std::is_same<typename std::decay<T>::type, half>::value)
352 {
353 // We use T instead of print_type here is because the std::is_floating_point<half> returns false and then the print_type becomes int.
354 ss << static_cast<T>(ptr[i]);
355 }
Georgios Pinitase8291ac2020-02-26 09:58:13 +0000356 else if(std::is_same<typename std::decay<T>::type, bfloat16>::value)
357 {
358 // We use T instead of print_type here is because the std::is_floating_point<bfloat> returns false and then the print_type becomes int.
359 ss << float(ptr[i]);
360 }
Anthony Barbier7068f992017-10-26 15:23:08 +0100361 else
362 {
363 ss << static_cast<print_type>(ptr[i]);
364 }
365
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100366 max_width = std::max<int>(max_width, ss.str().size());
367 }
368 return max_width;
369}
370
371/** Print consecutive elements to an output stream.
372 *
373 * @param[out] s Output stream to print the elements to.
374 * @param[in] dt Data type of the elements
375 * @param[in] ptr Pointer to print the elements from.
376 * @param[in] n Number of elements to print.
377 * @param[in] stream_width (Optional) Width of the stream. If set to 0 the element's width is used. Defaults to 0.
378 * @param[in] element_delim (Optional) Delimeter among the consecutive elements. Defaults to space delimeter
379 */
380void print_consecutive_elements(std::ostream &s, DataType dt, const uint8_t *ptr, unsigned int n, int stream_width, const std::string &element_delim = " ");
381
382/** Identify the maximum width of n consecutive elements.
383 *
384 * @param[in] s Output stream to print the elements to.
385 * @param[in] dt Data type of the elements
386 * @param[in] ptr Pointer to print the elements from.
387 * @param[in] n Number of elements to print.
388 *
389 * @return The maximum width of the elements.
390 */
391int max_consecutive_elements_display_width(std::ostream &s, DataType dt, const uint8_t *ptr, unsigned int n);
giuros01edc21e42018-11-16 14:45:31 +0000392#endif /* ARM_COMPUTE_ASSERTS_ENABLED */
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100393}
Michalis Spyrouf4643372019-11-29 16:17:13 +0000394#endif /*ARM_COMPUTE_UTILS_H */