blob: 4745b8bbd726e1aa4c2889210df7c2112eb31330 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
2 * Copyright (c) 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_TEST_UTILS_H__
25#define __ARM_COMPUTE_TEST_UTILS_H__
26
27#include "arm_compute/core/Coordinates.h"
28#include "arm_compute/core/Error.h"
29#include "arm_compute/core/FixedPoint.h"
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010030#include "arm_compute/core/TensorInfo.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010031#include "arm_compute/core/TensorShape.h"
32#include "arm_compute/core/Types.h"
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010033#include "support/ToolchainSupport.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010034
35#include <cmath>
36#include <cstddef>
37#include <limits>
38#include <memory>
SiCong Li3e363692017-07-04 15:02:10 +010039#include <random>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010040#include <sstream>
41#include <string>
42#include <type_traits>
SiCong Li3e363692017-07-04 15:02:10 +010043#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010044
45namespace arm_compute
46{
47namespace test
48{
Anthony Barbier6ff3b192017-09-04 18:44:23 +010049/** Round floating-point value with half value rounding to positive infinity.
50 *
51 * @param[in] value floating-point value to be rounded.
52 *
53 * @return Floating-point value of rounded @p value.
54 */
55template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
56inline T round_half_up(T value)
57{
58 return std::floor(value + 0.5f);
59}
60
61/** Round floating-point value with half value rounding to nearest even.
62 *
63 * @param[in] value floating-point value to be rounded.
64 * @param[in] epsilon precision.
65 *
66 * @return Floating-point value of rounded @p value.
67 */
68template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
69inline T round_half_even(T value, T epsilon = std::numeric_limits<T>::epsilon())
70{
71 T positive_value = std::abs(value);
72 T ipart = 0;
73 std::modf(positive_value, &ipart);
74 // If 'value' is exactly halfway between two integers
75 if(std::abs(positive_value - (ipart + 0.5f)) < epsilon)
76 {
77 // If 'ipart' is even then return 'ipart'
78 if(std::fmod(ipart, 2.f) < epsilon)
79 {
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010080 return support::cpp11::copysign(ipart, value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010081 }
82 // Else return the nearest even integer
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010083 return support::cpp11::copysign(std::ceil(ipart + 0.5f), value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010084 }
85 // Otherwise use the usual round to closest
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010086 return support::cpp11::copysign(support::cpp11::round(positive_value), value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +010087}
Anthony Barbier6ff3b192017-09-04 18:44:23 +010088
89namespace traits
90{
91// *INDENT-OFF*
92// clang-format off
93template <typename T> struct promote { };
94template <> struct promote<uint8_t> { using type = uint16_t; };
95template <> struct promote<int8_t> { using type = int16_t; };
96template <> struct promote<uint16_t> { using type = uint32_t; };
97template <> struct promote<int16_t> { using type = int32_t; };
98template <> struct promote<uint32_t> { using type = uint64_t; };
99template <> struct promote<int32_t> { using type = int64_t; };
100template <> struct promote<float> { using type = float; };
Georgios Pinitas583137c2017-08-31 18:12:42 +0100101template <> struct promote<half> { using type = half; };
Pablo Tello383deec2017-06-23 10:40:05 +0100102
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100103
104template <typename T>
105using promote_t = typename promote<T>::type;
106
107template <typename T>
108using make_signed_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_signed<T>, std::common_type<T>>::type;
109// clang-format on
110// *INDENT-ON*
111}
112
113/** Look up the format corresponding to a channel.
114 *
115 * @param[in] channel Channel type.
116 *
117 * @return Format that contains the given channel.
118 */
119inline Format get_format_for_channel(Channel channel)
120{
121 switch(channel)
122 {
123 case Channel::R:
124 case Channel::G:
125 case Channel::B:
126 return Format::RGB888;
127 default:
128 throw std::runtime_error("Unsupported channel");
129 }
130}
131
132/** Return the format of a channel.
133 *
134 * @param[in] channel Channel type.
135 *
136 * @return Format of the given channel.
137 */
138inline Format get_channel_format(Channel channel)
139{
140 switch(channel)
141 {
142 case Channel::R:
143 case Channel::G:
144 case Channel::B:
145 return Format::U8;
146 default:
147 throw std::runtime_error("Unsupported channel");
148 }
149}
150
151/** Base case of foldl.
152 *
153 * @return value.
154 */
155template <typename F, typename T>
156inline T foldl(F &&, const T &value)
157{
158 return value;
159}
160
161/** Base case of foldl.
162 *
163 * @return func(value1, value2).
164 */
165template <typename F, typename T, typename U>
166inline auto foldl(F &&func, T &&value1, U &&value2) -> decltype(func(value1, value2))
167{
168 return func(value1, value2);
169}
170
171/** Fold left.
172 *
173 * @param[in] func Binary function to be called.
174 * @param[in] initial Initial value.
175 * @param[in] value Argument passed to the function.
176 * @param[in] values Remaining arguments.
177 */
178template <typename F, typename I, typename T, typename... Vs>
179inline I foldl(F &&func, I &&initial, T &&value, Vs &&... values)
180{
181 return foldl(std::forward<F>(func), func(std::forward<I>(initial), std::forward<T>(value)), std::forward<Vs>(values)...);
182}
183
SiCong Libacaf9a2017-06-19 13:41:45 +0100184/** Create a valid region based on tensor shape, border mode and border size
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100185 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100186 * @param[in] shape Shape used as size of the valid region.
187 * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
188 * @param[in] border_size (Optional) Border size used to specify the region to exclude.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100189 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100190 * @return A valid region starting at (0, 0, ...) with size of @p shape if @p border_undefined is false; otherwise
191 * return A valid region starting at (@p border_size.left, @p border_size.top, ...) with reduced size of @p shape.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100192 */
SiCong Libacaf9a2017-06-19 13:41:45 +0100193inline ValidRegion shape_to_valid_region(TensorShape shape, bool border_undefined = false, BorderSize border_size = BorderSize(0))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100194{
195 Coordinates anchor;
Moritz Pflanzera1848362017-08-25 12:30:03 +0100196 anchor.set_num_dimensions(shape.num_dimensions());
197
SiCong Libacaf9a2017-06-19 13:41:45 +0100198 if(border_undefined)
199 {
200 ARM_COMPUTE_ERROR_ON(shape.num_dimensions() < 2);
Moritz Pflanzera1848362017-08-25 12:30:03 +0100201
SiCong Libacaf9a2017-06-19 13:41:45 +0100202 anchor.set(0, border_size.left);
203 anchor.set(1, border_size.top);
Moritz Pflanzera1848362017-08-25 12:30:03 +0100204
205 const int valid_shape_x = std::max(0, static_cast<int>(shape.x()) - static_cast<int>(border_size.left) - static_cast<int>(border_size.right));
206 const int valid_shape_y = std::max(0, static_cast<int>(shape.y()) - static_cast<int>(border_size.top) - static_cast<int>(border_size.bottom));
207
208 shape.set(0, valid_shape_x);
209 shape.set(1, valid_shape_y);
SiCong Libacaf9a2017-06-19 13:41:45 +0100210 }
Moritz Pflanzera1848362017-08-25 12:30:03 +0100211
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100212 return ValidRegion(std::move(anchor), std::move(shape));
213}
214
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100215/** Write the value after casting the pointer according to @p data_type.
216 *
217 * @warning The type of the value must match the specified data type.
218 *
219 * @param[out] ptr Pointer to memory where the @p value will be written.
220 * @param[in] value Value that will be written.
221 * @param[in] data_type Data type that will be written.
222 */
223template <typename T>
224void store_value_with_data_type(void *ptr, T value, DataType data_type)
225{
226 switch(data_type)
227 {
228 case DataType::U8:
229 *reinterpret_cast<uint8_t *>(ptr) = value;
230 break;
231 case DataType::S8:
232 case DataType::QS8:
233 *reinterpret_cast<int8_t *>(ptr) = value;
234 break;
235 case DataType::U16:
236 *reinterpret_cast<uint16_t *>(ptr) = value;
237 break;
238 case DataType::S16:
Michalis Spyrou0a8334c2017-06-14 18:00:05 +0100239 case DataType::QS16:
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100240 *reinterpret_cast<int16_t *>(ptr) = value;
241 break;
242 case DataType::U32:
243 *reinterpret_cast<uint32_t *>(ptr) = value;
244 break;
245 case DataType::S32:
246 *reinterpret_cast<int32_t *>(ptr) = value;
247 break;
248 case DataType::U64:
249 *reinterpret_cast<uint64_t *>(ptr) = value;
250 break;
251 case DataType::S64:
252 *reinterpret_cast<int64_t *>(ptr) = value;
253 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100254 case DataType::F16:
Georgios Pinitas583137c2017-08-31 18:12:42 +0100255 *reinterpret_cast<half *>(ptr) = value;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100256 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100257 case DataType::F32:
258 *reinterpret_cast<float *>(ptr) = value;
259 break;
260 case DataType::F64:
261 *reinterpret_cast<double *>(ptr) = value;
262 break;
263 case DataType::SIZET:
264 *reinterpret_cast<size_t *>(ptr) = value;
265 break;
266 default:
267 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
268 }
269}
270
271/** Saturate a value of type T against the numeric limits of type U.
272 *
273 * @param[in] val Value to be saturated.
274 *
275 * @return saturated value.
276 */
277template <typename U, typename T>
278T saturate_cast(T val)
279{
280 if(val > static_cast<T>(std::numeric_limits<U>::max()))
281 {
282 val = static_cast<T>(std::numeric_limits<U>::max());
283 }
284 if(val < static_cast<T>(std::numeric_limits<U>::lowest()))
285 {
286 val = static_cast<T>(std::numeric_limits<U>::lowest());
287 }
288 return val;
289}
290
291/** Find the signed promoted common type.
292 */
293template <typename... T>
294struct common_promoted_signed_type
295{
296 using common_type = typename std::common_type<T...>::type;
297 using promoted_type = traits::promote_t<common_type>;
298 using intermediate_type = typename traits::make_signed_conditional_t<promoted_type>::type;
299};
300
301/** Convert a linear index into n-dimensional coordinates.
302 *
303 * @param[in] shape Shape of the n-dimensional tensor.
304 * @param[in] index Linear index specifying the i-th element.
305 *
306 * @return n-dimensional coordinates.
307 */
308inline Coordinates index2coord(const TensorShape &shape, int index)
309{
310 int num_elements = shape.total_size();
311
312 ARM_COMPUTE_ERROR_ON_MSG(index < 0 || index >= num_elements, "Index has to be in [0, num_elements]");
313 ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create coordinate from empty shape");
314
315 Coordinates coord{ 0 };
316
317 for(int d = shape.num_dimensions() - 1; d >= 0; --d)
318 {
319 num_elements /= shape[d];
320 coord.set(d, index / num_elements);
321 index %= num_elements;
322 }
323
324 return coord;
325}
326
327/** Linearise the given coordinate.
328 *
329 * Transforms the given coordinate into a linear offset in terms of
330 * elements.
331 *
332 * @param[in] shape Shape of the n-dimensional tensor.
333 * @param[in] coord The to be converted coordinate.
334 *
335 * @return Linear offset to the element.
336 */
337inline int coord2index(const TensorShape &shape, const Coordinates &coord)
338{
339 ARM_COMPUTE_ERROR_ON_MSG(shape.total_size() == 0, "Cannot get index from empty shape");
340 ARM_COMPUTE_ERROR_ON_MSG(coord.num_dimensions() == 0, "Cannot get index of empty coordinate");
341
342 int index = 0;
343 int dim_size = 1;
344
345 for(unsigned int i = 0; i < coord.num_dimensions(); ++i)
346 {
347 index += coord[i] * dim_size;
348 dim_size *= shape[i];
349 }
350
351 return index;
352}
353
354/** Check if a coordinate is within a valid region */
Moritz Pflanzera1848362017-08-25 12:30:03 +0100355inline bool is_in_valid_region(const ValidRegion &valid_region, Coordinates coord)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100356{
Moritz Pflanzer219c6912017-09-23 19:22:51 +0100357 for(size_t d = 0; d < Coordinates::num_max_dimensions; ++d)
Moritz Pflanzera1848362017-08-25 12:30:03 +0100358 {
359 if(coord[d] < valid_region.start(d) || coord[d] >= valid_region.end(d))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100360 {
361 return false;
362 }
363 }
Moritz Pflanzera1848362017-08-25 12:30:03 +0100364
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100365 return true;
366}
Moritz Pflanzer94450f12017-06-30 12:48:43 +0100367
368/** Create and initialize a tensor of the given type.
369 *
370 * @param[in] shape Tensor shape.
371 * @param[in] data_type Data type.
372 * @param[in] num_channels (Optional) Number of channels.
373 * @param[in] fixed_point_position (Optional) Number of fractional bits.
374 *
375 * @return Initialized tensor of given type.
376 */
377template <typename T>
378inline T create_tensor(const TensorShape &shape, DataType data_type, int num_channels = 1, int fixed_point_position = 0)
379{
380 T tensor;
381 tensor.allocator()->init(TensorInfo(shape, num_channels, data_type, fixed_point_position));
382
383 return tensor;
384}
SiCong Li3e363692017-07-04 15:02:10 +0100385
386/** Create a vector of random ROIs.
387 *
388 * @param[in] shape The shape of the input tensor.
389 * @param[in] pool_info The ROI pooling information.
390 * @param[in] num_rois The number of ROIs to be created.
391 * @param[in] seed The random seed to be used.
392 *
393 * @return A vector that contains the requested number of random ROIs
394 */
395inline std::vector<ROI> generate_random_rois(const TensorShape &shape, const ROIPoolingLayerInfo &pool_info, unsigned int num_rois, std::random_device::result_type seed)
396{
397 ARM_COMPUTE_ERROR_ON((pool_info.pooled_width() < 4) || (pool_info.pooled_height() < 4));
398
399 std::vector<ROI> rois;
400 std::mt19937 gen(seed);
401 const int pool_width = pool_info.pooled_width();
402 const int pool_height = pool_info.pooled_height();
403 const float roi_scale = pool_info.spatial_scale();
404
405 // Calculate distribution bounds
406 const auto scaled_width = static_cast<int>((shape.x() / roi_scale) / pool_width);
407 const auto scaled_height = static_cast<int>((shape.y() / roi_scale) / pool_height);
408 const auto min_width = static_cast<int>(pool_width / roi_scale);
409 const auto min_height = static_cast<int>(pool_height / roi_scale);
410
411 // Create distributions
412 std::uniform_int_distribution<int> dist_batch(0, shape[3] - 1);
413 std::uniform_int_distribution<int> dist_x(0, scaled_width);
414 std::uniform_int_distribution<int> dist_y(0, scaled_height);
415 std::uniform_int_distribution<int> dist_w(min_width, std::max(min_width, (pool_width - 2) * scaled_width));
416 std::uniform_int_distribution<int> dist_h(min_height, std::max(min_height, (pool_height - 2) * scaled_height));
417
418 for(unsigned int r = 0; r < num_rois; ++r)
419 {
420 ROI roi;
421 roi.batch_idx = dist_batch(gen);
422 roi.rect.x = dist_x(gen);
423 roi.rect.y = dist_y(gen);
424 roi.rect.width = dist_w(gen);
425 roi.rect.height = dist_h(gen);
426 rois.push_back(roi);
427 }
428
429 return rois;
430}
431
432template <typename T, typename ArrayAccessor_T>
433inline void fill_array(ArrayAccessor_T &&array, const std::vector<T> &v)
434{
435 array.resize(v.size());
436 std::memcpy(array.buffer(), v.data(), v.size() * sizeof(T));
437}
SiCong Li86b53332017-08-23 11:02:43 +0100438
439/** Obtain numpy type string from DataType.
440 *
441 * @param[in] data_type Data type.
442 *
443 * @return numpy type string.
444 */
445inline std::string get_typestring(DataType data_type)
446{
447 // Check endianness
448 const unsigned int i = 1;
449 const char *c = reinterpret_cast<const char *>(&i);
450 std::string endianness;
451 if(*c == 1)
452 {
453 endianness = std::string("<");
454 }
455 else
456 {
457 endianness = std::string(">");
458 }
459 const std::string no_endianness("|");
460
461 switch(data_type)
462 {
463 case DataType::U8:
464 return no_endianness + "u" + support::cpp11::to_string(sizeof(uint8_t));
465 case DataType::S8:
466 return no_endianness + "i" + support::cpp11::to_string(sizeof(int8_t));
467 case DataType::U16:
468 return endianness + "u" + support::cpp11::to_string(sizeof(uint16_t));
469 case DataType::S16:
470 return endianness + "i" + support::cpp11::to_string(sizeof(int16_t));
471 case DataType::U32:
472 return endianness + "u" + support::cpp11::to_string(sizeof(uint32_t));
473 case DataType::S32:
474 return endianness + "i" + support::cpp11::to_string(sizeof(int32_t));
475 case DataType::U64:
476 return endianness + "u" + support::cpp11::to_string(sizeof(uint64_t));
477 case DataType::S64:
478 return endianness + "i" + support::cpp11::to_string(sizeof(int64_t));
479 case DataType::F32:
480 return endianness + "f" + support::cpp11::to_string(sizeof(float));
481 case DataType::F64:
482 return endianness + "f" + support::cpp11::to_string(sizeof(double));
483 case DataType::SIZET:
484 return endianness + "u" + support::cpp11::to_string(sizeof(size_t));
485 default:
486 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
487 }
488}
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100489} // namespace test
490} // namespace arm_compute
Anthony Barbierac69aa12017-07-03 17:39:37 +0100491#endif /* __ARM_COMPUTE_TEST_UTILS_H__ */