blob: 4d067ac748615c90846f181e1756fa5a32568618 [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_TENSOR_OPERATIONS_H__
25#define __ARM_COMPUTE_TEST_TENSOR_OPERATIONS_H__
26
27#include "FixedPoint.h"
28#include "Tensor.h"
29#include "Types.h"
30#include "Utils.h"
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +010031#include "support/ToolchainSupport.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010032
33#include "FixedPoint.h"
34#include "Types.h"
35#include "arm_compute/core/FixedPoint.h"
36#include "arm_compute/core/Types.h"
37#include "tests/validation/FixedPoint.h"
Giorgio Arena50f9fd72017-06-19 17:05:30 +010038#include "tests/validation/ValidationUserConfiguration.h"
Anthony Barbier6ff3b192017-09-04 18:44:23 +010039
40#include <algorithm>
41#include <array>
42#include <cmath>
Giorgio Arena50f9fd72017-06-19 17:05:30 +010043#include <random>
Georgios Pinitasac4e8732017-07-05 17:02:25 +010044#include <string>
Georgios Pinitasd4f8c272017-06-30 16:16:19 +010045#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010046
Pablo Tello0c34fe22017-06-26 17:17:42 +010047#if ARM_COMPUTE_ENABLE_FP16
48//Beware! most std templates acting on types don't work with the data type float16_t
49namespace std
50{
51template <>
52class numeric_limits<float16_t>
53{
54public:
55 static float16_t lowest()
56 {
57 return -std::numeric_limits<float>::max(); // -inf
58 };
59 static float16_t max()
60 {
61 return std::numeric_limits<float>::max(); // +inf
62 };
63};
64}
65#endif /* ARM_COMPUTE_ENABLE_FP16 */
66
Anthony Barbier6ff3b192017-09-04 18:44:23 +010067namespace arm_compute
68{
69namespace test
70{
71namespace validation
72{
73namespace tensor_operations
74{
75namespace
76{
Pablo Tello383deec2017-06-23 10:40:05 +010077template <class T>
78struct is_floating_point
79 : std::integral_constant < bool,
80 std::is_same<float, typename std::remove_cv<T>::type>::value ||
Anthony Barbierac69aa12017-07-03 17:39:37 +010081#ifdef ARM_COMPUTE_ENABLE_FP16
Pablo Tello383deec2017-06-23 10:40:05 +010082 std::is_same<float16_t, typename std::remove_cv<T>::type>::value ||
Anthony Barbierac69aa12017-07-03 17:39:37 +010083#endif /* ARM_COMPUTE_ENABLE_FP16 */
Pablo Tello383deec2017-06-23 10:40:05 +010084 std::is_same<double, typename std::remove_cv<T>::type>::value || std::is_same<long double, typename std::remove_cv<T>::type>::value >
85{
86};
87
Anthony Barbier6ff3b192017-09-04 18:44:23 +010088bool is_valid_pixel(int i, int min, int max)
89{
90 return (i >= min && i < max);
91}
92
93// 3D convolution for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +010094template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010095void convolution3d(const T *in, const T *weights, const T *bias, T *out, int xi, int yi, int width_in, int height_in, int depth_in, int width_weights, int height_weights, int8_t fixed_point_position)
96{
97 const int half_width_weights = width_weights / 2;
98 const int half_height_weights = height_weights / 2;
99
100 // Reset accumulator
101 T acc = static_cast<T>(0);
102
103 // Compute a 2D convolution for each IFM and accumulate the result
104 for(int ifm = 0; ifm < depth_in; ++ifm)
105 {
106 // Compute the offset for the input slice
107 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
108
109 // Compute 2D convolution
110 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
111 {
112 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
113 {
114 // Check if the pixel is out-of-bound
115 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
116 {
117 const int idx = xk + half_width_weights;
118 const int idy = yk + half_height_weights;
119
120 const T i_value = in[offset_slice_in + xk + yk * width_in];
121 const T w_value = weights[idx + idy * width_weights + ifm * width_weights * height_weights];
122
123 acc += i_value * w_value;
124 }
125 }
126 }
127 }
128
129 // Accumulate the bias and store the result
130 *out = acc + (*bias);
131}
132
133// 3D convolution for fixed point type
134template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
135void convolution3d(const T *in, const T *weights, const T *bias, T *out, int xi, int yi, int width_in, int height_in, int depth_in, int width_weights, int height_weights,
136 int8_t fixed_point_position)
137{
138 const int half_width_weights = width_weights / 2;
139 const int half_height_weights = height_weights / 2;
140
141 using namespace fixed_point_arithmetic;
142 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
143
144 // Reset accumulator
145 fixed_point<promoted_type> acc(0, fixed_point_position);
146
147 // Compute a 2D convolution for each IFM and accumulate the result
148 for(int ifm = 0; ifm < depth_in; ++ifm)
149 {
150 // Compute the offset for the input slice
151 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
152
153 // Compute 2D convolution
154 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
155 {
156 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
157 {
158 // Check if the pixel is out-of-bound
159 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
160 {
161 const int idx = xk + half_width_weights;
162 const int idy = yk + half_height_weights;
163
164 const fixed_point<promoted_type> i_value(in[offset_slice_in + xk + yk * width_in], fixed_point_position, true);
165 const fixed_point<promoted_type> w_value(weights[idx + idy * width_weights + ifm * width_weights * height_weights], fixed_point_position, true);
166 const fixed_point<promoted_type> iw = i_value * w_value;
167 acc = iw + acc;
168 }
169 }
170 }
171 }
172
173 // Get the bias
174 const fixed_point<promoted_type> b(*bias, fixed_point_position, true);
175
176 // Accumulate the bias and covert back
177 acc = acc + b;
178 fixed_point<T> res(acc);
179 *out = res.raw();
180}
181
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100182template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100183void vector_matrix_multiply(const T *in, const T *weights, const T *bias, T *out, int cols_weights, int rows_weights, uint8_t fixed_point_position)
184{
185 for(int x = 0; x < cols_weights; ++x)
186 {
187 T acc = 0.0f;
188 for(int y = 0; y < rows_weights; ++y)
189 {
190 acc += in[y] * weights[x + y * cols_weights];
191 }
192 out[x] = acc + bias[x];
193 }
194}
195
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100196// Vector matrix multiply for fixed point type
197template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
198void vector_matrix_multiply(const T *in, const T *weights, const T *bias, T *out, int cols_weights, int rows_weights, uint8_t fixed_point_position)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100199{
200 using namespace fixed_point_arithmetic;
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100201 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100202
203 for(int x = 0; x < cols_weights; ++x)
204 {
205 // Reset accumulator
206 fixed_point<promoted_type> acc(0, fixed_point_position);
207
208 for(int y = 0; y < rows_weights; ++y)
209 {
210 const fixed_point<promoted_type> i_value(in[y], fixed_point_position, true);
211 const fixed_point<promoted_type> w_value(weights[x + y * cols_weights], fixed_point_position, true);
212 const fixed_point<promoted_type> iw = i_value * w_value;
213 acc = iw + acc;
214 }
215
216 // Get the bias
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100217 const fixed_point<T> b(bias[x], fixed_point_position, true);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100218
219 // Convert back and accumulate the bias
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100220 fixed_point<T> res(acc);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100221 res = res + b;
222
223 // Store the result
224 out[x] = res.raw();
225 }
226}
227
SiCong Libacaf9a2017-06-19 13:41:45 +0100228// Return a tensor element at a specified coordinate with different border modes
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100229template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
230T tensor_elem_at(const Tensor<T> &in, Coordinates &coord, BorderMode border_mode, T constant_border_value)
231{
232 const int x = coord.x();
233 const int y = coord.y();
234 const int width = static_cast<int>(in.shape().x());
235 const int height = static_cast<int>(in.shape().y());
236
SiCong Libacaf9a2017-06-19 13:41:45 +0100237 // If coordinates beyond range of tensor's width or height
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100238 if(x < 0 || y < 0 || x >= width || y >= height)
239 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100240 if(border_mode == BorderMode::REPLICATE)
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100241 {
242 coord.set(0, std::max(0, std::min(x, width - 1)));
243 coord.set(1, std::max(0, std::min(y, height - 1)));
244 return in[coord2index(in.shape(), coord)];
245 }
246 else
247 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100248 return constant_border_value;
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100249 }
250 }
251 else
252 {
253 return in[coord2index(in.shape(), coord)];
254 }
255}
256
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100257/** Apply 2D spatial filter on a single element of @p in at coordinates @p coord
258 *
259 * - filter sizes have to be odd number
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100260 * - Row major order of filter assumed
261 * - TO_ZERO rounding policy assumed
262 * - SATURATE convert policy assumed
263 *
264 */
265template <typename T1, typename T2, typename T3>
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100266void apply_2d_spatial_filter(Coordinates coord, const Tensor<T1> &in, Tensor<T3> &out, const TensorShape &filter_shape, const T2 *filter_itr, float scale, BorderMode border_mode,
267 T1 constant_border_value = 0)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100268{
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100269 double val = 0;
270 const int x = coord.x();
271 const int y = coord.y();
272 for(int j = y - static_cast<int>(filter_shape[1] / 2); j <= y + static_cast<int>(filter_shape[1] / 2); ++j)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100273 {
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100274 for(int i = x - static_cast<int>(filter_shape[0] / 2); i <= x + static_cast<int>(filter_shape[0] / 2); ++i)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100275 {
276 coord.set(0, i);
277 coord.set(1, j);
SiCong Libacaf9a2017-06-19 13:41:45 +0100278 val += static_cast<double>(*filter_itr) * tensor_elem_at(in, coord, border_mode, constant_border_value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100279 ++filter_itr;
280 }
281 }
282 coord.set(0, x);
283 coord.set(1, y);
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100284 const double rounded_val = support::cpp11::trunc(val * static_cast<double>(scale));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100285 out[coord2index(in.shape(), coord)] = saturate_cast<T3>(rounded_val);
286}
287} // namespace
288
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100289// Sobel 3x3
290template <typename T1, typename T2>
291void sobel_3x3(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
292{
293 const std::array<int8_t, 9> sobel_x{ { -1, 0, 1, -2, 0, 2, -1, 0, 1 } };
294 const std::array<int8_t, 9> sobel_y{ { -1, -2, -1, 0, 0, 0, 1, 2, 1 } };
295
296 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
297 {
298 const Coordinates id = index2coord(in.shape(), element_idx);
299
300 apply_2d_spatial_filter(id, in, out_x, TensorShape(3U, 3U), sobel_x.data(), 1.f, border_mode, constant_border_value);
301 apply_2d_spatial_filter(id, in, out_y, TensorShape(3U, 3U), sobel_y.data(), 1.f, border_mode, constant_border_value);
302 }
303}
304
305// Sobel 5x5
306template <typename T1, typename T2>
307void sobel_5x5(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
308{
309 const std::array<int8_t, 25> sobel_x{ {
310 -1, -2, 0, 2, 1,
311 -4, -8, 0, 8, 4,
312 -6, -12, 0, 12, 6,
313 -4, -8, 0, 8, 4,
314 -1, -2, 0, 2, 1
315 } };
316
317 const std::array<int8_t, 25> sobel_y{ {
318 -1, -4, -6, -4, -1,
319 -2, -8, -12, -8, -2,
320 0, 0, 0, 0, 0,
321 2, 8, 12, 8, 2,
322 1, 4, 6, 4, 1
323 } };
324
325 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
326 {
327 const Coordinates id = index2coord(in.shape(), element_idx);
328
329 apply_2d_spatial_filter(id, in, out_x, TensorShape(5U, 5U), sobel_x.data(), 1.f, border_mode, constant_border_value);
330 apply_2d_spatial_filter(id, in, out_y, TensorShape(5U, 5U), sobel_y.data(), 1.f, border_mode, constant_border_value);
331 }
332}
333
Giorgio Arena2ca209e2017-06-13 15:49:37 +0100334// Min max location
335template <typename T1>
Giorgio Arena935deee2017-06-14 13:40:36 +0100336void min_max_location(const Tensor<T1> &in, int32_t &min, int32_t &max, IArray<Coordinates2D> &min_loc, IArray<Coordinates2D> &max_loc, uint32_t &min_count, uint32_t &max_count)
Giorgio Arena2ca209e2017-06-13 15:49:37 +0100337{
338 // Set min and max to first pixel
339 min = in[0];
340 max = in[0];
341 min_count = 0;
342 max_count = 0;
343
344 const size_t width = in.shape().x();
345
346 // Look for min and max values
347 for(int i = 1; i < in.num_elements(); ++i)
348 {
349 if(static_cast<int32_t>(in[i]) < min)
350 {
351 min = in[i];
352 }
353 if(static_cast<int32_t>(in[i]) > max)
354 {
355 max = in[i];
356 }
357 }
358
359 for(int i = 0; i < in.num_elements(); ++i)
360 {
361 if(static_cast<int32_t>(in[i]) == min)
362 {
363 Coordinates2D min_coord;
364 min_coord.x = static_cast<int32_t>(i % width);
365 min_coord.y = static_cast<int32_t>(i / width);
366
367 min_loc.push_back(min_coord);
368
369 min_count++;
370 }
371 if(static_cast<int32_t>(in[i]) == max)
372 {
373 Coordinates2D max_coord;
374 max_coord.x = static_cast<int32_t>(i % width);
375 max_coord.y = static_cast<int32_t>(i / width);
376
377 max_loc.push_back(max_coord);
378
379 max_count++;
380 }
381 }
382}
383
Giorgio Arenaf7959862017-06-13 15:19:51 +0100384// Mean Standard Deviation
385template <typename T1>
386void mean_and_standard_deviation(const Tensor<T1> &in, float &mean, float &std_dev)
387{
388 int num_elements = in.num_elements();
389
390 // Calculate mean
391 mean = 0.f;
392 for(int i = 0; i < num_elements; ++i)
393 {
394 mean += in[i];
395 }
396 mean /= num_elements;
397
398 // Calculate standard deviation
399 std_dev = 0.f;
400 for(int i = 0; i < num_elements; ++i)
401 {
402 std_dev += (mean - in[i]) * (mean - in[i]);
403 }
404 std_dev = sqrt(std_dev / num_elements);
405}
406
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100407// Integral Image
408void integral_image(const Tensor<uint8_t> &in, Tensor<uint32_t> &out)
409{
410 // Length of dimensions
411 const size_t width = in.shape().x();
412 const size_t height = in.shape().y();
413 const size_t depth = in.shape().z() * in.shape()[3] * in.shape()[4] * in.shape()[5];
414
415 const size_t image_size = width * height;
416
417 for(size_t z = 0; z < depth; ++z)
418 {
419 size_t current_image = z * image_size;
420
421 //First element of each image
422 out[current_image] = in[current_image];
423
424 // First row of each image (add only pixel on the left)
425 for(size_t x = 1; x < width; ++x)
426 {
427 out[current_image + x] = static_cast<uint32_t>(in[current_image + x]) + out[current_image + x - 1];
428 }
429
430 // Subsequent rows
431 for(size_t y = 1; y < height; ++y)
432 {
433 size_t current_row = current_image + (width * y);
434
435 // First element of each row (add only pixel up)
436 out[current_row] = static_cast<uint32_t>(in[current_row]) + out[current_row - width];
437
438 // Following row elements
439 for(size_t x = 1; x < width; ++x)
440 {
441 size_t current_pixel = current_row + x;
442
443 // out = in + up(out) + left(out) - up_left(out)
444 out[current_pixel] = static_cast<uint32_t>(in[current_pixel]) + out[current_pixel - 1]
445 + out[current_pixel - width] - out[current_pixel - width - 1];
446 }
447 }
448 }
449}
450
451// Absolute difference
452template <typename T1, typename T2, typename T3>
453void absolute_difference(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out)
454{
455 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
456
457 for(int i = 0; i < in1.num_elements(); ++i)
458 {
459 intermediate_type val = std::abs(static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]));
460 out[i] = saturate_cast<T3>(val);
461 }
462}
463
464// Accumulate
465template <typename T1, typename T2>
466void accumulate(const Tensor<T1> &in, Tensor<T2> &out)
467{
468 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
469
470 for(int i = 0; i < in.num_elements(); ++i)
471 {
472 intermediate_type val = static_cast<intermediate_type>(out[i]) + static_cast<intermediate_type>(in[i]);
473 out[i] = saturate_cast<T2>(val);
474 }
475}
476
477// Accumulate squared
478template <typename T1, typename T2>
479void accumulate_squared(const Tensor<T1> &in, Tensor<T2> &out, uint32_t shift)
480{
481 if(shift > 15)
482 {
483 ARM_COMPUTE_ERROR("Shift in accumulate_squared must be within the range [0, 15]");
484 }
485 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
486 intermediate_type denom = 1 << shift;
487
488 for(int i = 0; i < in.num_elements(); ++i)
489 {
490 intermediate_type val = static_cast<intermediate_type>(out[i]) + (static_cast<intermediate_type>(in[i]) * static_cast<intermediate_type>(in[i]) / denom);
491 out[i] = saturate_cast<T2>(val);
492 }
493}
494
495// Accumulate weighted
496template <typename T>
497void accumulate_weighted(const Tensor<T> &in, Tensor<T> &out, float alpha)
498{
499 if(alpha < 0.f || alpha > 1.f)
500 {
501 ARM_COMPUTE_ERROR("Weight (alpha) specified in accumulate_weighted must be within the range [0, 1]");
502 }
503 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
504
505 for(int i = 0; i < in.num_elements(); ++i)
506 {
507 double val = (1. - static_cast<double>(alpha)) * static_cast<intermediate_type>(out[i]) + static_cast<double>(alpha) * static_cast<intermediate_type>(in[i]);
508 out[i] = static_cast<T>(val);
509 }
510}
511
512// Arithmetic addition
513template <typename T1, typename T2, typename T3>
514void arithmetic_addition(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
515{
516 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
517
518 for(int i = 0; i < in1.num_elements(); ++i)
519 {
520 intermediate_type val = static_cast<intermediate_type>(in1[i]) + static_cast<intermediate_type>(in2[i]);
521 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
522 }
523}
524
525// Arithmetic Subtraction
526template <typename T1, typename T2, typename T3>
527void arithmetic_subtraction(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
528{
529 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
530
531 for(int i = 0; i < in1.num_elements(); ++i)
532 {
533 intermediate_type val = static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]);
534 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
535 }
536}
537
538// Bitwise and
539template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
540void bitwise_and(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
541{
542 for(int i = 0; i < in1.num_elements(); ++i)
543 {
544 out[i] = in1[i] & in2[i];
545 }
546}
547
548// Bitwise or
549template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
550void bitwise_or(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
551{
552 for(int i = 0; i < in1.num_elements(); ++i)
553 {
554 out[i] = in1[i] | in2[i];
555 }
556}
557
558// Bitwise xor
559template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
560void bitwise_xor(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
561{
562 for(int i = 0; i < in1.num_elements(); ++i)
563 {
564 out[i] = in1[i] ^ in2[i];
565 }
566}
567
568// Bitwise not
569template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
570void bitwise_not(const Tensor<T> &in, Tensor<T> &out)
571{
572 for(int i = 0; i < in.num_elements(); ++i)
573 {
574 out[i] = ~in[i];
575 }
576}
577
SiCong Libacaf9a2017-06-19 13:41:45 +0100578// Box3x3 filter
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100579template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
SiCong Libacaf9a2017-06-19 13:41:45 +0100580void box3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100581{
582 const std::array<T, 9> filter{ { 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
SiCong Libacaf9a2017-06-19 13:41:45 +0100583 float scale = 1.f / static_cast<float>(filter.size());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100584 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
585 {
586 const Coordinates id = index2coord(in.shape(), element_idx);
SiCong Libacaf9a2017-06-19 13:41:45 +0100587 apply_2d_spatial_filter(id, in, out, TensorShape(3U, 3U), filter.data(), scale, border_mode, constant_border_value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100588 }
589}
590
591// Depth conversion
Pablo Tello91654c42017-07-05 11:32:17 +0100592template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&is_floating_point<T2>::value, int >::type = 0 >
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100593void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
594{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100595 using namespace fixed_point_arithmetic;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100596
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100597 const int fixed_point_position = in.fixed_point_position();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100598 for(int i = 0; i < in.num_elements(); ++i)
599 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100600 out[i] = static_cast<float>(fixed_point<T1>(in[i], fixed_point_position, true));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100601 }
602}
603
Pablo Tello91654c42017-07-05 11:32:17 +0100604template < typename T1, typename T2, typename std::enable_if < is_floating_point<T1>::value &&std::is_integral<T2>::value, int >::type = 0 >
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100605void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100606{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100607 using namespace fixed_point_arithmetic;
608
609 const int fixed_point_position = out.fixed_point_position();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100610 for(int i = 0; i < in.num_elements(); ++i)
611 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100612 out[i] = fixed_point<T2>(in[i], fixed_point_position).raw();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100613 }
614}
615
Georgios Pinitase2229412017-07-12 12:30:40 +0100616template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&std::is_integral<T2>::value &&!std::is_same<T1, T2>::value, int >::type = 0 >
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100617void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100618{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100619 // Up-casting
620 if(std::numeric_limits<T1>::digits <= std::numeric_limits<T2>::digits)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100621 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100622 for(int i = 0; i < in.num_elements(); ++i)
623 {
624 out[i] = static_cast<T2>(in[i]) << shift;
625 }
626 }
627 // Down-casting
628 else
629 {
630 for(int i = 0; i < in.num_elements(); ++i)
631 {
632 T1 val = in[i] >> shift;
633 out[i] = ((policy == ConvertPolicy::SATURATE) ? saturate_cast<T2>(val) : static_cast<T2>(val));
634 }
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100635 }
636}
637
Georgios Pinitase2229412017-07-12 12:30:40 +0100638template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&std::is_integral<T2>::value &&std::is_same<T1, T2>::value, int >::type = 0 >
639void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
640{
641 using namespace fixed_point_arithmetic;
642 bool is_in_place = (&in == &out);
643
644 const int fixed_point_position_in = in.fixed_point_position();
645 const int fixed_point_position_out = (is_in_place) ? static_cast<int>(shift) : out.fixed_point_position();
646
647 if(!is_in_place || (fixed_point_position_in != fixed_point_position_out))
648 {
649 for(int i = 0; i < in.num_elements(); ++i)
650 {
651 auto x = fixed_point<T2>(in[i], fixed_point_position_in, true);
652 x.rescale(fixed_point_position_out);
653 out[i] = x.raw();
654 }
655 }
656}
657
Pablo Tello331fc742017-07-06 11:47:06 +0100658template < typename T1, typename T2, typename std::enable_if < is_floating_point<T1>::value &&is_floating_point<T2>::value, int >::type = 0 >
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100659void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100660{
661 for(int i = 0; i < in.num_elements(); ++i)
662 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100663 out[i] = static_cast<T2>(in[i]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100664 }
665}
666
SiCong Li5a536642017-06-19 14:47:05 +0100667// Gaussian3x3 filter
668template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
669void gaussian3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
670{
671 const std::array<T, 9> filter{ { 1, 2, 1, 2, 4, 2, 1, 2, 1 } };
672 const float scale = 1.f / 16.f;
673 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
674 {
675 const Coordinates id = index2coord(in.shape(), element_idx);
676 apply_2d_spatial_filter(id, in, out, TensorShape(3U, 3U), filter.data(), scale, border_mode, constant_border_value);
677 }
678}
679
SiCong Li3eb263e2017-06-19 15:31:43 +0100680// Gaussian5x5 filter
681template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
682void gaussian5x5(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
683{
684 const std::array<T, 25> filter{ {
685 1, 4, 6, 4, 1,
686 4, 16, 24, 16, 4,
687 6, 24, 36, 24, 6,
688 4, 16, 24, 16, 4,
689 1, 4, 6, 4, 1
690 } };
691 const float scale = 1.f / 256.f;
692 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
693 {
694 const Coordinates id = index2coord(in.shape(), element_idx);
695 apply_2d_spatial_filter(id, in, out, TensorShape(5U, 5U), filter.data(), scale, border_mode, constant_border_value);
696 }
697}
698
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100699// Matrix multiplication for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100700template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100701void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
702{
703 const int M = out.shape().y();
704 const int N = out.shape().x();
705 const int K = in1.shape().x();
706
707 for(int r = 0; r < M; ++r)
708 {
709 for(int c = 0; c < N; ++c)
710 {
711 T acc = 0.0f;
712
713 for(int k = 0; k < K; ++k)
714 {
715 const T a0 = in1[r * K + k];
716 const T b0 = in2[k * N + c];
717
718 acc += a0 * b0;
719 }
720
721 // Finalize the result: A * B * alpha + C * beta
722 const T c0 = in3[c + r * N];
723 out[c + r * N] = alpha * acc + beta * c0;
724 }
725 }
726}
727
728// Matrix multiplication for fixed point type
729template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
730void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
731{
732 using namespace fixed_point_arithmetic;
733
734 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
735
736 const int M = out.shape().y();
737 const int N = out.shape().x();
738 const int K = in1.shape().x();
739 const int8_t fixed_point_position = static_cast<int8_t>(in1.fixed_point_position());
740
741 const fixed_point<T> alpha_q(alpha, fixed_point_position);
742 const fixed_point<T> beta_q(beta, fixed_point_position);
743
744 for(int r = 0; r < M; ++r)
745 {
746 for(int c = 0; c < N; ++c)
747 {
748 fixed_point<promoted_type> acc_q(0, fixed_point_position);
749
750 for(int k = 0; k < K; ++k)
751 {
752 const fixed_point<promoted_type> a0_q(in1[r * K + k], fixed_point_position, true);
753 const fixed_point<promoted_type> b0_q(in2[k * N + c], fixed_point_position, true);
754 const fixed_point<promoted_type> axb_q = a0_q * b0_q;
755
756 acc_q = axb_q + acc_q;
757 }
758
759 // Finalize the result: A * B * alpha + C * beta
760 const fixed_point<T> c0_q(in3[c + r * N], fixed_point_position, true);
761
762 fixed_point<T> res_q(acc_q);
763 res_q = alpha_q * res_q;
764 res_q = (c0_q * beta_q) + res_q;
765
766 // Store the result
767 out[c + r * N] = res_q.raw();
768 }
769 }
770}
771
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100772// Non linear filter
773template <typename T>
774void non_linear_filter(const Tensor<T> &in, Tensor<T> &out, NonLinearFilterFunction function, unsigned int mask_size,
775 MatrixPattern pattern, const uint8_t *mask, BorderMode border_mode, uint8_t constant_border_value)
776{
SiCong Li7a035752017-06-28 15:27:02 +0100777 ARM_COMPUTE_ERROR_ON(pattern == MatrixPattern::OTHER && mask == nullptr);
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100778
779 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
780
781 const int sq_mask_size = mask_size * mask_size;
782 const int half_mask_size = mask_size / 2;
783 std::vector<intermediate_type> vals(sq_mask_size);
784 intermediate_type current_value = 0;
785
SiCong Li7a035752017-06-28 15:27:02 +0100786 const ValidRegion valid_region = shape_to_valid_region(in.shape(), border_mode == BorderMode::UNDEFINED, BorderSize(half_mask_size));
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100787
788 for(int element_idx = 0, count = 0, index = 0; element_idx < in.num_elements(); ++element_idx, count = 0, index = 0)
789 {
790 Coordinates id = index2coord(in.shape(), element_idx);
791 if(is_in_valid_region(valid_region, id))
792 {
793 int idx = id.x();
794 int idy = id.y();
795 for(int y = idy - half_mask_size; y <= idy + half_mask_size; ++y)
796 {
797 for(int x = idx - half_mask_size; x <= idx + half_mask_size; ++x, ++index)
798 {
799 id.set(0, x);
800 id.set(1, y);
801 current_value = tensor_elem_at(in, id, border_mode, constant_border_value);
802
803 if(mask[index] == 255)
804 {
805 vals[count] = static_cast<intermediate_type>(current_value);
806 ++count;
807 }
808 }
809 }
810 std::sort(vals.begin(), vals.begin() + count);
811 switch(function)
812 {
813 case NonLinearFilterFunction::MIN:
814 out[element_idx] = saturate_cast<T>(vals[0]);
815 break;
816 case NonLinearFilterFunction::MAX:
817 out[element_idx] = saturate_cast<T>(vals[count - 1]);
818 break;
819 case NonLinearFilterFunction::MEDIAN:
820 out[element_idx] = saturate_cast<T>(vals[count / 2]);
821 break;
822 default:
823 ARM_COMPUTE_ERROR("Unsupported NonLinearFilter function.");
824 }
825 }
826 }
827}
828
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100829// Pixel-wise multiplication
830template <typename T1, typename T2, typename T3>
831void pixel_wise_multiplication(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, float scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
832{
833 if(scale < 0)
834 {
835 ARM_COMPUTE_ERROR("Scale of pixel-wise multiplication must be non-negative");
836 }
837 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
838 for(int i = 0; i < in1.num_elements(); ++i)
839 {
840 double val = static_cast<intermediate_type>(in1[i]) * static_cast<intermediate_type>(in2[i]) * static_cast<double>(scale);
Pablo Tello383deec2017-06-23 10:40:05 +0100841 if(is_floating_point<T3>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100842 {
843 out[i] = val;
844 }
845 else
846 {
847 double rounded_val = 0;
848 switch(rounding_policy)
849 {
850 case(RoundingPolicy::TO_ZERO):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100851 rounded_val = support::cpp11::trunc(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100852 break;
853 case(RoundingPolicy::TO_NEAREST_UP):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100854 rounded_val = round_half_up(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100855 break;
856 case(RoundingPolicy::TO_NEAREST_EVEN):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100857 rounded_val = round_half_even(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100858 break;
859 default:
860 ARM_COMPUTE_ERROR("Unsupported rounding policy");
861 }
862 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(rounded_val) : static_cast<T3>(rounded_val);
863 }
864 }
865}
866
867// Fixed-point Pixel-wise Multiplication
868template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
869void fixed_point_pixel_wise_multiplication(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out, int scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
870{
871 using namespace fixed_point_arithmetic;
872
873 const int fixed_point_position = in1.fixed_point_position();
874
875 ARM_COMPUTE_ERROR_ON_MSG(in1.data_type() != in2.data_type() || in1.data_type() != out.data_type(),
876 "Tensors must all have the same DataType");
877 ARM_COMPUTE_ERROR_ON_MSG(fixed_point_position != in2.fixed_point_position() || fixed_point_position != out.fixed_point_position(),
878 "Fixed-point position must be the same for both inputs and outputs");
879
880 // Validate fixed_point_position
881 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS8) && (fixed_point_position == 0 || fixed_point_position > 7));
882 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS16) && (fixed_point_position == 0 || fixed_point_position > 15));
883
884 fixed_point<T> fp_scale(scale, fixed_point_position);
885 const bool is_sat = convert_policy == ConvertPolicy::SATURATE;
886 const bool do_scaling = scale != 1;
887
888 for(int i = 0; i < in1.num_elements(); ++i)
889 {
890 fixed_point<T> val1(in1[i], fixed_point_position, true);
891 fixed_point<T> val2(in2[i], fixed_point_position, true);
892 fixed_point<T> res = (is_sat) ? val1 * val2 : mul<OverflowPolicy::WRAP>(val1, val2);
893 if(do_scaling)
894 {
895 res = (is_sat) ? res * fp_scale : mul<OverflowPolicy::WRAP>(res, fp_scale);
896 }
897 out[i] = res.raw();
898 }
899}
900
Isabella Gottardib797fa22017-06-23 15:02:11 +0100901//Table Lookup
902template <typename T, typename T1>
903void table_lookup(const Tensor<T> &in, Tensor<T> &out, std::map<T1, T1> &lut)
904{
905 for(int i = 0; i < in.num_elements(); ++i)
906 {
907 out[i] = static_cast<T>(lut[in[i]]);
908 }
909}
910
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100911// Threshold
912template <typename T>
913void threshold(const Tensor<T> &in, Tensor<T> &out, uint8_t threshold, uint8_t false_value, uint8_t true_value, ThresholdType type, uint8_t upper)
914{
915 switch(type)
916 {
917 case ThresholdType::BINARY:
918 for(int i = 0; i < in.num_elements(); ++i)
919 {
920 out[i] = ((in[i] > threshold) ? true_value : false_value);
921 }
922 break;
923 case ThresholdType::RANGE:
924 for(int i = 0; i < in.num_elements(); ++i)
925 {
926 if(in[i] > upper)
927 {
928 out[i] = false_value;
929 }
930 else if(in[i] < threshold)
931 {
932 out[i] = false_value;
933 }
934 else
935 {
936 out[i] = true_value;
937 }
938 }
939 break;
940 default:
941 ARM_COMPUTE_ERROR("Thresholding type not recognised");
942 break;
943 }
944}
945
946// Activation Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100947template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100948void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
949{
950 const T a = static_cast<T>(act_info.a());
951 const T b = static_cast<T>(act_info.b());
952
953 for(int i = 0; i < in.num_elements(); ++i)
954 {
955 T x = in[i];
956 switch(act_info.activation())
957 {
958 case ActivationLayerInfo::ActivationFunction::ABS:
959 out[i] = std::abs(x);
960 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100961 case ActivationLayerInfo::ActivationFunction::LINEAR:
962 out[i] = a * x + b;
963 break;
964 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
965 out[i] = static_cast<T>(1) / (static_cast<T>(1) + std::exp(-x));
966 break;
967 case ActivationLayerInfo::ActivationFunction::RELU:
968 out[i] = std::max<T>(0, x);
969 break;
Georgios Pinitas579c0492017-07-12 16:12:12 +0100970 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
971 out[i] = std::min<T>(a, std::max<T>(0, x));
972 break;
973 case ActivationLayerInfo::ActivationFunction::LEAKY_RELU:
974 out[i] = (x > 0) ? x : a * x;
975 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100976 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
977 out[i] = std::log(static_cast<T>(1) + std::exp(x));
978 break;
979 case ActivationLayerInfo::ActivationFunction::SQRT:
980 out[i] = std::sqrt(x);
981 break;
982 case ActivationLayerInfo::ActivationFunction::SQUARE:
983 out[i] = x * x;
984 break;
985 case ActivationLayerInfo::ActivationFunction::TANH:
986 out[i] = a * std::tanh(b * x);
987 break;
988 default:
989 ARM_COMPUTE_ERROR("Activation function not recognised");
990 break;
991 }
992 }
993}
994
995// Activation Layer for fixed point type
996template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
997void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
998{
999 using namespace fixed_point_arithmetic;
1000 int fixed_point_position = in.fixed_point_position();
1001 ActivationLayerInfo::ActivationFunction act_func = act_info.activation();
1002 const fixed_point<T> a(act_info.a(), fixed_point_position);
1003 const fixed_point<T> b(act_info.b(), fixed_point_position);
1004 const fixed_point<T> const_0(0, fixed_point_position);
1005 const fixed_point<T> const_1(1, fixed_point_position);
1006
1007 for(int i = 0; i < in.num_elements(); ++i)
1008 {
1009 fixed_point<T> x(in[i], fixed_point_position, true);
1010 switch(act_func)
1011 {
1012 case ActivationLayerInfo::ActivationFunction::ABS:
1013 out[i] = abs(x).raw();
1014 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001015 case ActivationLayerInfo::ActivationFunction::LINEAR:
1016 out[i] = add(b, mul(a, x)).raw();
1017 break;
1018 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
1019 out[i] = (const_1 / (const_1 + exp(-x))).raw();
1020 break;
1021 case ActivationLayerInfo::ActivationFunction::RELU:
1022 out[i] = max(const_0, x).raw();
1023 break;
Georgios Pinitas579c0492017-07-12 16:12:12 +01001024 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
1025 out[i] = min(a, max(const_0, x)).raw();
1026 break;
1027 case ActivationLayerInfo::ActivationFunction::LEAKY_RELU:
1028 out[i] = (x > const_0) ? x.raw() : mul(a, x).raw();
1029 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001030 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
1031 out[i] = log(const_1 + exp(x)).raw();
1032 break;
1033 case ActivationLayerInfo::ActivationFunction::SQRT:
1034 out[i] = (const_1 / inv_sqrt(x)).raw();
1035 break;
1036 case ActivationLayerInfo::ActivationFunction::SQUARE:
1037 out[i] = mul(x, x).raw();
1038 break;
1039 case ActivationLayerInfo::ActivationFunction::TANH:
Georgios Pinitasccc65d42017-06-27 17:39:11 +01001040 out[i] = mul(a, tanh(mul(b, x))).raw();
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001041 break;
1042 default:
1043 ARM_COMPUTE_ERROR("Activation function not recognised");
1044 break;
1045 }
1046 }
1047}
1048
1049// Batch Normalization Layer for fixed point type
1050template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1051void batch_normalization_layer(const Tensor<T> &in, Tensor<T> &out, const Tensor<T> &mean, const Tensor<T> &var, const Tensor<T> &beta, const Tensor<T> &gamma, float epsilon, int fixed_point_position)
1052{
1053 const int cols = static_cast<int>(in.shape()[0]);
1054 const int rows = static_cast<int>(in.shape()[1]);
1055 const int depth = static_cast<int>(in.shape()[2]);
1056 int upper_dims = in.shape().total_size() / (cols * rows * depth);
1057
1058 for(int r = 0; r < upper_dims; ++r)
1059 {
1060 for(int i = 0; i < depth; ++i)
1061 {
1062 for(int k = 0; k < rows; ++k)
1063 {
1064 for(int l = 0; l < cols; ++l)
1065 {
1066 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
Michalis Spyrou172e5702017-06-26 14:18:47 +01001067 fixed_point_arithmetic::fixed_point<T> in_qs(in[pos], fixed_point_position, true);
1068 fixed_point_arithmetic::fixed_point<T> var_qs(var[i], fixed_point_position, true);
1069 fixed_point_arithmetic::fixed_point<T> mean_qs(mean[i], fixed_point_position, true);
1070 fixed_point_arithmetic::fixed_point<T> beta_qs(beta[i], fixed_point_position, true);
1071 fixed_point_arithmetic::fixed_point<T> gamma_qs(gamma[i], fixed_point_position, true);
1072 fixed_point_arithmetic::fixed_point<T> epsilon_qs(epsilon, fixed_point_position);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001073
Michalis Spyrou172e5702017-06-26 14:18:47 +01001074 auto denominator = fixed_point_arithmetic::inv_sqrt(var_qs + epsilon_qs);
1075 auto numerator = in_qs - mean_qs;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001076 auto x_bar = numerator * denominator;
Michalis Spyrou172e5702017-06-26 14:18:47 +01001077 x_bar = beta_qs + x_bar * gamma_qs;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001078 out[pos] = x_bar.raw();
1079 }
1080 }
1081 }
1082 }
1083}
1084
1085// Batch Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001086template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001087void batch_normalization_layer(const Tensor<T> &in, Tensor<T> &out, const Tensor<T> &mean, const Tensor<T> &var, const Tensor<T> &beta, const Tensor<T> &gamma, float epsilon, int fixed_point_position)
1088{
1089 const int cols = static_cast<int>(in.shape()[0]);
1090 const int rows = static_cast<int>(in.shape()[1]);
1091 const int depth = static_cast<int>(in.shape()[2]);
1092 int upper_dims = in.shape().total_size() / (cols * rows * depth);
1093
1094 for(int r = 0; r < upper_dims; ++r)
1095 {
1096 for(int i = 0; i < depth; ++i)
1097 {
1098 for(int k = 0; k < rows; ++k)
1099 {
1100 for(int l = 0; l < cols; ++l)
1101 {
1102 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
1103 const float denominator = sqrt(var[i] + epsilon);
1104 const float numerator = in[pos] - mean[i];
1105 const float x_bar = numerator / denominator;
1106 out[pos] = beta[i] + x_bar * gamma[i];
1107 }
1108 }
1109 }
1110 }
1111}
1112
Georgios Pinitasac4e8732017-07-05 17:02:25 +01001113// Depth Concatenate layer
1114template <typename T>
1115void depth_concatenate_layer(const std::vector<const Tensor<T> *> &srcs, Tensor<T> &out)
1116{
1117 unsigned depth_offset = 0;
1118 const int width_out = out.shape().x();
1119 const int height_out = out.shape().y();
1120 const int depth_out = out.shape().z();
1121 const int out_stride_z = width_out * height_out;
1122 const int batches = out.shape().total_size_upper(3);
1123
1124 // Set output tensor to 0
1125 memset(out.data(), 0, out.num_elements() * element_size_from_data_type(out.data_type()));
1126
1127 for(unsigned int i = 0; i < srcs.size(); ++i)
1128 {
1129 ARM_COMPUTE_ERROR_ON(srcs[i] == nullptr);
1130 ARM_COMPUTE_ERROR_ON(srcs[i]->data_type() != out.data_type());
1131 ARM_COMPUTE_ERROR_ON(depth_offset >= out.shape().z());
1132 ARM_COMPUTE_ERROR_ON(batches != static_cast<int>(srcs[i]->shape().total_size_upper(3)));
1133
1134 const Tensor<T> *src = srcs[i];
1135 const int width = src->shape().x();
1136 const int height = src->shape().y();
1137 const int depth = src->shape().z();
1138 const unsigned int x_diff = (width_out - width) / 2;
1139 const unsigned int y_diff = (height_out - height) / 2;
1140
1141 const T *src_ptr = src->data();
1142 for(int b = 0; b < batches; ++b)
1143 {
1144 const unsigned int offset_to_first_element = b * out_stride_z * depth_out + depth_offset * out_stride_z
1145 + y_diff * width_out + x_diff;
1146 for(int d = 0; d < depth; ++d)
1147 {
1148 for(int r = 0; r < height; ++r)
1149 {
1150 std::copy(src_ptr, src_ptr + width, out.data() + offset_to_first_element + d * out_stride_z + r * width_out);
1151 src_ptr += width;
1152 }
1153 }
1154 }
1155
1156 depth_offset += depth;
1157 }
1158}
1159
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001160// Convolution layer
1161template <typename T>
1162void convolution_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out, const PadStrideInfo &conv_info)
1163{
1164 const int width_in = in.shape().x();
1165 const int height_in = in.shape().y();
1166 const int depth_in = in.shape().z();
1167 const int width_out = out.shape().x();
1168 const int height_out = out.shape().y();
1169 const int depth_out = out.shape().z();
1170 const int width_weights = weights.shape().x();
1171 const int height_weights = weights.shape().y();
1172 const int depth_weights = weights.shape().z();
1173 const int pad_xi = std::min(static_cast<int>(conv_info.pad().first), width_weights / 2);
1174 const int pad_yi = std::min(static_cast<int>(conv_info.pad().second), height_weights / 2);
1175 const int start_xi = width_weights / 2 - pad_xi;
1176 const int start_yi = height_weights / 2 - pad_yi;
1177 const int end_xi = width_in - start_xi;
1178 const int end_yi = height_in - start_yi;
1179 const int stride_xi = conv_info.stride().first;
1180 const int stride_yi = conv_info.stride().second;
1181 const int num_batches = in.shape().total_size() / (width_in * height_in * depth_in);
1182
1183 for(int r = 0; r < num_batches; ++r)
1184 {
1185 for(int yi = start_yi; yi < end_yi; yi += stride_yi)
1186 {
1187 for(int xi = start_xi; xi < end_xi; xi += stride_xi)
1188 {
1189 for(int ofm = 0; ofm < depth_out; ++ofm)
1190 {
1191 // Compute input and output offsets
1192 const int offset_in = r * width_in * height_in * depth_in;
1193 const int xo = (xi - start_xi) / stride_xi;
1194 const int yo = (yi - start_yi) / stride_yi;
1195 const int offset_out = xo + yo * width_out + ofm * width_out * height_out + r * width_out * height_out * depth_out;
1196
1197 // Compute 3D convolution
1198 convolution3d(in.data() + offset_in,
1199 weights.data() + ofm * width_weights * height_weights * depth_weights,
1200 bias.data() + ofm,
1201 out.data() + offset_out,
1202 xi, yi,
1203 width_in, height_in, depth_in,
1204 width_weights, height_weights,
1205 static_cast<int8_t>(in.fixed_point_position()));
1206 }
1207 }
1208 }
1209 }
1210}
1211
1212// Fully connected layer
1213template <typename T>
1214void fully_connected_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out)
1215{
1216 ARM_COMPUTE_ERROR_ON(weights.shape().x() != out.shape().x());
1217 ARM_COMPUTE_ERROR_ON(weights.shape().y() != in.shape().x() * in.shape().y() * in.shape().z());
1218 const int cols_weights = weights.shape().x();
1219 const int rows_weights = weights.shape().y();
1220 const int num_batches = in.shape().total_size() / rows_weights;
1221
1222 for(int k = 0; k < num_batches; ++k)
1223 {
1224 vector_matrix_multiply<T>(in.data() + k * rows_weights,
1225 weights.data(),
1226 bias.data(),
1227 out.data() + k * cols_weights,
1228 cols_weights,
1229 rows_weights,
1230 in.fixed_point_position());
1231 }
1232}
1233
1234// Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001235template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001236void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1237{
1238 const uint32_t norm_size = norm_info.norm_size();
1239 NormType type = norm_info.type();
1240 float beta = norm_info.beta();
1241 uint32_t kappa = norm_info.kappa();
1242
1243 const int cols = static_cast<int>(in.shape()[0]);
1244 const int rows = static_cast<int>(in.shape()[1]);
1245 const int depth = static_cast<int>(in.shape()[2]);
1246 int upper_dims = in.shape().total_size() / (cols * rows);
1247
1248 float coeff = norm_info.scale_coeff();
1249 int radius_cols = norm_size / 2;
1250 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1251 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1252
1253 if(type == NormType::CROSS_MAP)
1254 {
1255 // Remove also depth from upper dimensions since it is the axes we want
1256 // to use for normalization
1257 upper_dims /= depth;
1258 for(int r = 0; r < upper_dims; ++r)
1259 {
1260 for(int i = 0; i < rows; ++i)
1261 {
1262 for(int k = 0; k < cols; ++k)
1263 {
1264 for(int l = 0; l < depth; ++l)
1265 {
1266 float accumulated_scale = 0.f;
1267 for(int j = -radius_cols; j <= radius_cols; ++j)
1268 {
1269 const int z = l + j;
1270 if(z >= 0 && z < depth)
1271 {
1272 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1273 accumulated_scale += value * value;
1274 }
1275 }
1276 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = kappa + accumulated_scale * coeff;
1277 }
1278 }
1279 }
1280 }
1281 }
1282 else
1283 {
1284 for(int r = 0; r < upper_dims; ++r)
1285 {
1286 for(int i = 0; i < rows; ++i)
1287 {
1288 for(int k = 0; k < cols; ++k)
1289 {
1290 float accumulated_scale = 0.f;
1291 for(int j = -radius_rows; j <= radius_rows; ++j)
1292 {
1293 const int y = i + j;
1294 for(int l = -radius_cols; l <= radius_cols; ++l)
1295 {
1296 const int x = k + l;
1297 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1298 {
1299 const T value = in[x + y * cols + r * cols * rows];
1300 accumulated_scale += value * value;
1301 }
1302 }
1303 }
1304 out[k + i * cols + r * cols * rows] = kappa + accumulated_scale * coeff;
1305 }
1306 }
1307 }
1308 }
1309
1310 if(beta == 1.f)
1311 {
1312 for(int i = 0; i < out.num_elements(); ++i)
1313 {
1314 out[i] = in[i] / out[i];
1315 }
1316 }
1317 else if(beta == 0.5f)
1318 {
1319 for(int i = 0; i < out.num_elements(); ++i)
1320 {
1321 out[i] = in[i] / std::sqrt(out[i]);
1322 }
1323 }
1324 else
1325 {
1326 for(int i = 0; i < out.num_elements(); ++i)
1327 {
1328 out[i] = in[i] * std::exp(std::log(out[i]) * -beta);
1329 }
1330 }
1331}
1332// Normalization Layer for fixed-point types
1333template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1334void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1335{
1336 using namespace fixed_point_arithmetic;
1337
1338 const int fixed_point_position = in.fixed_point_position();
1339
1340 const uint32_t norm_size = norm_info.norm_size();
1341 NormType type = norm_info.type();
1342 fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1343 fixed_point<T> kappa(norm_info.kappa(), fixed_point_position);
1344
1345 const int cols = static_cast<int>(in.shape()[0]);
1346 const int rows = static_cast<int>(in.shape()[1]);
1347 const int depth = static_cast<int>(in.shape()[2]);
1348 int upper_dims = in.shape().total_size() / (cols * rows);
1349
1350 fixed_point<T> coeff(norm_info.scale_coeff(), fixed_point_position);
1351 int radius_cols = norm_size / 2;
1352 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1353 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1354
1355 if(type == NormType::CROSS_MAP)
1356 {
1357 // Remove also depth from upper dimensions since it is the axes we want
1358 // to use for normalization
1359 upper_dims /= depth;
1360 for(int r = 0; r < upper_dims; ++r)
1361 {
1362 for(int i = 0; i < rows; ++i)
1363 {
1364 for(int k = 0; k < cols; ++k)
1365 {
1366 for(int l = 0; l < depth; ++l)
1367 {
1368 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1369 for(int j = -radius_cols; j <= radius_cols; ++j)
1370 {
1371 const int z = l + j;
1372 if(z >= 0 && z < depth)
1373 {
1374 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1375 const fixed_point<T> fp_value(value, fixed_point_position, true);
1376 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1377 }
1378 }
1379 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1380 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = accumulated_scale.raw();
1381 }
1382 }
1383 }
1384 }
1385 }
1386 else
1387 {
1388 for(int r = 0; r < upper_dims; ++r)
1389 {
1390 for(int i = 0; i < rows; ++i)
1391 {
1392 for(int k = 0; k < cols; ++k)
1393 {
1394 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1395 for(int j = -radius_rows; j <= radius_rows; ++j)
1396 {
1397 const int y = i + j;
1398 for(int l = -radius_cols; l <= radius_cols; ++l)
1399 {
1400 const int x = k + l;
1401 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1402 {
1403 const T value = in[x + y * cols + r * cols * rows];
1404 const fixed_point<T> fp_value(value, fixed_point_position, true);
1405 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1406 }
1407 }
1408 }
1409 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1410 out[k + i * cols + r * cols * rows] = accumulated_scale.raw();
1411 }
1412 }
1413 }
1414 }
1415
1416 if(norm_info.beta() == 1.f)
1417 {
1418 for(int i = 0; i < out.num_elements(); ++i)
1419 {
1420 fixed_point<T> res = div(fixed_point<T>(in[i], fixed_point_position, true), fixed_point<T>(out[i], fixed_point_position, true));
1421 out[i] = res.raw();
1422 }
1423 }
1424 else
1425 {
1426 const fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1427 for(int i = 0; i < out.num_elements(); ++i)
1428 {
1429 fixed_point<T> res = pow(fixed_point<T>(out[i], fixed_point_position, true), beta);
1430 res = div(fixed_point<T>(in[i], fixed_point_position, true), res);
1431 out[i] = res.raw();
1432 }
1433 }
1434}
1435
1436// Pooling layer
1437template <typename T>
1438void pooling_layer(const Tensor<T> &in, Tensor<T> &out, PoolingLayerInfo pool_info, int fixed_point_position)
1439{
1440 const int pool_size = pool_info.pool_size();
1441 PoolingType type = pool_info.pool_type();
1442 int pool_stride_x = 0;
1443 int pool_stride_y = 0;
1444 int pad_x = 0;
1445 int pad_y = 0;
1446 std::tie(pool_stride_x, pool_stride_y) = pool_info.pad_stride_info().stride();
1447 std::tie(pad_x, pad_y) = pool_info.pad_stride_info().pad();
1448
Georgios Pinitasce093142017-06-19 16:11:53 +01001449 const int w_in = static_cast<int>(in.shape()[0]);
1450 const int h_in = static_cast<int>(in.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001451
Georgios Pinitasce093142017-06-19 16:11:53 +01001452 const int w_out = static_cast<int>(out.shape()[0]);
1453 const int h_out = static_cast<int>(out.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001454
Georgios Pinitasce093142017-06-19 16:11:53 +01001455 int upper_dims = in.shape().total_size() / (w_in * h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001456
Georgios Pinitasce093142017-06-19 16:11:53 +01001457 int pooled_w = 0;
1458 int pooled_h = 0;
1459 if(pool_info.pad_stride_info().round() == DimensionRoundingType::CEIL)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001460 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001461 pooled_w = static_cast<int>(ceil(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1462 pooled_h = static_cast<int>(ceil(static_cast<float>(h_in + 2 * pad_y - pool_size) / pool_stride_y)) + 1;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001463 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001464 else
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001465 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001466 pooled_w = static_cast<int>(floor(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1467 pooled_h = static_cast<int>(floor(static_cast<float>(h_in + 2 * pad_y - pool_size) / pool_stride_y)) + 1;
1468 }
1469
1470 if((pooled_w - 1) * pool_stride_x >= w_in + pad_x)
1471 {
1472 --pooled_w;
1473 }
1474 if((pooled_h - 1) * pool_stride_y >= h_in + pad_y)
1475 {
1476 --pooled_h;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001477 }
1478
1479 if(type == PoolingType::MAX)
1480 {
1481 for(int r = 0; r < upper_dims; ++r)
1482 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001483 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001484 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001485 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001486 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001487 int wstart = w * pool_stride_x - pad_x;
1488 int hstart = h * pool_stride_y - pad_y;
1489 int wend = std::min(wstart + pool_size, w_in);
1490 int hend = std::min(hstart + pool_size, h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001491 wstart = std::max(wstart, 0);
Georgios Pinitasce093142017-06-19 16:11:53 +01001492 hstart = std::max(hstart, 0);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001493
1494 T max_val = std::numeric_limits<T>::lowest();
1495 for(int y = hstart; y < hend; ++y)
1496 {
1497 for(int x = wstart; x < wend; ++x)
1498 {
Pablo Tello0c34fe22017-06-26 17:17:42 +01001499 const T val = in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001500 if(val > max_val)
1501 {
1502 max_val = val;
1503 }
1504 }
1505 }
1506
Georgios Pinitasce093142017-06-19 16:11:53 +01001507 out[r * h_out * w_out + h * pooled_w + w] = max_val;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001508 }
1509 }
1510 }
1511 }
1512 else // Average pooling
1513 {
1514 for(int r = 0; r < upper_dims; ++r)
1515 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001516 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001517 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001518 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001519 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001520 T avg_val = 0;
1521 int wstart = w * pool_stride_x - pad_x;
1522 int hstart = h * pool_stride_y - pad_y;
1523 int wend = std::min(wstart + pool_size, w_in + pad_x);
1524 int hend = std::min(hstart + pool_size, h_in + pad_y);
1525 int pool = (hend - hstart) * (wend - wstart);
1526 wstart = std::max(wstart, 0);
1527 hstart = std::max(hstart, 0);
1528 wend = std::min(wend, w_in);
1529 hend = std::min(hend, h_in);
Pablo Tello383deec2017-06-23 10:40:05 +01001530 if(is_floating_point<T>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001531 {
1532 for(int y = hstart; y < hend; ++y)
1533 {
1534 for(int x = wstart; x < wend; ++x)
1535 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001536 avg_val += in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001537 }
1538 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001539 out[r * h_out * w_out + h * pooled_w + w] = avg_val / pool;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001540 }
1541 else
1542 {
1543 static std::array<qint8_t, 10> scale_values_q8 =
1544 { { 0x0, 0x0, 0x40, 0x2A, 0x20, 0x19, 0x15, 0x12, 0x10, 0xE } };
1545
1546 for(int y = hstart; y < hend; ++y)
1547 {
1548 for(int x = wstart; x < wend; ++x)
1549 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001550 avg_val = sqadd_qs8(avg_val, in[r * h_in * w_in + y * w_in + x]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001551 }
1552 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001553 out[r * h_out * w_out + h * pooled_w + w] = sqmul_qs8(avg_val, (scale_values_q8[pool] >> (7 - fixed_point_position)), fixed_point_position);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001554 }
1555 }
1556 }
1557 }
1558 }
1559}
1560
Georgios Pinitas7b7858d2017-06-21 16:44:24 +01001561// Pooling layer
1562template <typename T>
1563void roi_pooling_layer(const Tensor<T> &in, Tensor<T> &out, const std::vector<ROI> &rois, const ROIPoolingLayerInfo &pool_info)
1564{
1565 const int num_rois = rois.size();
1566 const int width_in = in.shape().x();
1567 const int height_in = in.shape().y();
1568 const int fms = in.shape().z();
1569 const int volume_in = width_in * height_in * fms;
1570 const int pool_w = pool_info.pooled_width();
1571 const int pool_h = pool_info.pooled_height();
1572 const int volume_out = pool_w * pool_h * fms;
1573 const float roi_scale = pool_info.spatial_scale();
1574
1575 // Iterate through all rois
1576 for(int roi_idx = 0; roi_idx < num_rois; ++roi_idx)
1577 {
1578 // Get dimensions of current ROI
1579 const ROI &roi = rois[roi_idx];
1580
1581 int batch_id = roi.batch_idx;
1582 int roi_start_x = support::cpp11::round(roi.rect.x * roi_scale);
1583 int roi_start_y = support::cpp11::round(roi.rect.y * roi_scale);
1584 int roi_width = std::max(support::cpp11::round(roi.rect.width * roi_scale), 1.f);
1585 int roi_height = std::max(support::cpp11::round(roi.rect.height * roi_scale), 1.f);
1586
1587 // Determine pooling regions
1588 float pool_region_size_x = static_cast<float>(roi_width) / pool_w;
1589 float pool_region_size_y = static_cast<float>(roi_height) / pool_h;
1590
1591 // Iterate through all channel
1592 for(int fm = 0; fm < fms; ++fm)
1593 {
1594 // Calculate each output pixel
1595 for(int py = 0; py < pool_h; ++py)
1596 {
1597 for(int px = 0; px < pool_w; ++px)
1598 {
1599 int region_start_x = static_cast<int>(std::floor(px * pool_region_size_x));
1600 int region_end_x = static_cast<int>(std::ceil((px + 1) * pool_region_size_x));
1601 int region_start_y = static_cast<int>(std::floor(py * pool_region_size_y));
1602 int region_end_y = static_cast<int>(std::ceil((py + 1) * pool_region_size_y));
1603
1604 region_start_x = std::min(std::max(region_start_x + roi_start_x, 0), width_in);
1605 region_end_x = std::min(std::max(region_end_x + roi_start_x, 0), width_in);
1606 region_start_y = std::min(std::max(region_start_y + roi_start_y, 0), height_in);
1607 region_end_y = std::min(std::max(region_end_y + roi_start_y, 0), height_in);
1608
1609 // Iterate through each pixel in the pooling region
1610 if((region_end_x <= region_start_x) || (region_end_y <= region_start_y))
1611 {
1612 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = 0;
1613 }
1614 else
1615 {
1616 T curr_max = std::numeric_limits<T>::lowest();
1617 for(int j = region_start_y; j < region_end_y; ++j)
1618 {
1619 for(int i = region_start_x; i < region_end_x; ++i)
1620 {
1621 const auto val = in[batch_id * volume_in + fm * width_in * height_in + j * width_in + i];
1622 curr_max = std::max(val, curr_max);
1623 }
1624 }
1625 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = curr_max;
1626 }
1627 }
1628 }
1629 }
1630 }
1631}
1632
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001633// Softmax Layer
Pablo Tello383deec2017-06-23 10:40:05 +01001634template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001635void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1636{
1637 const int cols = static_cast<int>(in.shape()[0]);
1638 const int upper_dims = in.shape().total_size() / cols;
1639 for(int r = 0; r < upper_dims; ++r)
1640 {
1641 // Find max
1642 T max = std::numeric_limits<T>::lowest();
1643 for(int c = 0; c < cols; ++c)
1644 {
1645 const T x = in[r * cols + c];
1646 if(x > max)
1647 {
1648 max = x;
1649 }
1650 }
1651
1652 // Regularize
1653 T sum = 0;
1654 for(int c = 0; c < cols; ++c)
1655 {
1656 const T res = exp(in[r * cols + c] - max);
1657 out[r * cols + c] = res;
1658 sum += res;
1659 }
1660
1661 // Normalize
1662 const T norm_val = 1 / sum;
1663 for(int c = 0; c < cols; ++c)
1664 {
1665 out[r * cols + c] *= norm_val;
1666 }
1667 }
1668}
1669template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1670void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1671{
1672 using namespace fixed_point_arithmetic;
1673 using promoted_T = typename test::traits::promote<T>::type;
1674
1675 const int fixed_point_position = in.fixed_point_position();
1676 const int cols = static_cast<int>(in.shape()[0]);
1677 const int upper_dims = in.shape().total_size() / cols;
1678
1679 for(int r = 0; r < upper_dims; ++r)
1680 {
1681 // Find max
1682 fixed_point<T> max(std::numeric_limits<T>::lowest(), fixed_point_position, true);
1683 for(int c = 0; c < cols; ++c)
1684 {
1685 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1686 if(x > max)
1687 {
1688 max = x;
1689 }
1690 }
1691
1692 // Regularize
1693 fixed_point<promoted_T> sum(0, fixed_point_position);
1694 for(int c = 0; c < cols; ++c)
1695 {
1696 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1697 fixed_point<T> res = exp(x - max);
1698 out[r * cols + c] = res.raw();
1699 sum = add(sum, static_cast<fixed_point<promoted_T>>(res));
1700 }
1701
1702 // Normalize
1703 fixed_point<T> sat_sum(sum);
1704 for(int c = 0; c < cols; ++c)
1705 {
1706 const fixed_point<T> x(out[r * cols + c], fixed_point_position, true);
1707 out[r * cols + c] = div(x, sat_sum).raw();
1708 }
1709 }
1710}
1711
1712// Fixed point operations
1713template <typename T>
1714void fixed_point_operation(const Tensor<T> &in, Tensor<T> &out, FixedPointOp op)
1715{
1716 int p = in.fixed_point_position();
1717 switch(op)
1718 {
1719 case FixedPointOp::EXP:
1720 for(int i = 0; i < in.num_elements(); ++i)
1721 {
1722 out[i] = fixed_point_arithmetic::exp(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1723 }
1724 break;
1725 case FixedPointOp::LOG:
1726 for(int i = 0; i < in.num_elements(); ++i)
1727 {
1728 out[i] = fixed_point_arithmetic::log(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1729 }
1730 break;
1731 case FixedPointOp::INV_SQRT:
1732 for(int i = 0; i < in.num_elements(); ++i)
1733 {
1734 out[i] = fixed_point_arithmetic::inv_sqrt(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1735 }
1736 break;
1737 case FixedPointOp::RECIPROCAL:
1738 for(int i = 0; i < in.num_elements(); ++i)
1739 {
1740 out[i] = fixed_point_arithmetic::div(fixed_point_arithmetic::fixed_point<T>(1, p), fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1741 }
1742 break;
1743 default:
1744 ARM_COMPUTE_ERROR("Fixed point operation not supported");
1745 break;
1746 }
1747}
1748
1749// Tensor print
1750template <typename T>
1751void print(const Tensor<T> &in, std::ostream &out)
1752{
1753 out << "\n";
1754 for(int i = 0; i < in.num_elements(); ++i)
1755 {
1756 out << in[i] << " ";
1757 }
1758 out << "\n";
1759}
1760} // namespace tensor_operations
1761} // namespace validation
1762} // namespace test
1763} // namespace arm_compute
1764
1765#endif /* __ARM_COMPUTE_TEST_TENSOR_OPERATIONS_H__ */