blob: e90635f0d46e0756b2f78479116ec8ec045da8a0 [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 Pinitasd4f8c272017-06-30 16:16:19 +010044#include <vector>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010045
46namespace arm_compute
47{
48namespace test
49{
50namespace validation
51{
52namespace tensor_operations
53{
54namespace
55{
Pablo Tello383deec2017-06-23 10:40:05 +010056template <class T>
57struct is_floating_point
58 : std::integral_constant < bool,
59 std::is_same<float, typename std::remove_cv<T>::type>::value ||
Anthony Barbierac69aa12017-07-03 17:39:37 +010060#ifdef ARM_COMPUTE_ENABLE_FP16
Pablo Tello383deec2017-06-23 10:40:05 +010061 std::is_same<float16_t, typename std::remove_cv<T>::type>::value ||
Anthony Barbierac69aa12017-07-03 17:39:37 +010062#endif /* ARM_COMPUTE_ENABLE_FP16 */
Pablo Tello383deec2017-06-23 10:40:05 +010063 std::is_same<double, typename std::remove_cv<T>::type>::value || std::is_same<long double, typename std::remove_cv<T>::type>::value >
64{
65};
66
Anthony Barbier6ff3b192017-09-04 18:44:23 +010067bool is_valid_pixel(int i, int min, int max)
68{
69 return (i >= min && i < max);
70}
71
72// 3D convolution for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +010073template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010074void 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)
75{
76 const int half_width_weights = width_weights / 2;
77 const int half_height_weights = height_weights / 2;
78
79 // Reset accumulator
80 T acc = static_cast<T>(0);
81
82 // Compute a 2D convolution for each IFM and accumulate the result
83 for(int ifm = 0; ifm < depth_in; ++ifm)
84 {
85 // Compute the offset for the input slice
86 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
87
88 // Compute 2D convolution
89 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
90 {
91 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
92 {
93 // Check if the pixel is out-of-bound
94 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
95 {
96 const int idx = xk + half_width_weights;
97 const int idy = yk + half_height_weights;
98
99 const T i_value = in[offset_slice_in + xk + yk * width_in];
100 const T w_value = weights[idx + idy * width_weights + ifm * width_weights * height_weights];
101
102 acc += i_value * w_value;
103 }
104 }
105 }
106 }
107
108 // Accumulate the bias and store the result
109 *out = acc + (*bias);
110}
111
112// 3D convolution for fixed point type
113template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
114void 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,
115 int8_t fixed_point_position)
116{
117 const int half_width_weights = width_weights / 2;
118 const int half_height_weights = height_weights / 2;
119
120 using namespace fixed_point_arithmetic;
121 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
122
123 // Reset accumulator
124 fixed_point<promoted_type> acc(0, fixed_point_position);
125
126 // Compute a 2D convolution for each IFM and accumulate the result
127 for(int ifm = 0; ifm < depth_in; ++ifm)
128 {
129 // Compute the offset for the input slice
130 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
131
132 // Compute 2D convolution
133 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
134 {
135 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
136 {
137 // Check if the pixel is out-of-bound
138 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
139 {
140 const int idx = xk + half_width_weights;
141 const int idy = yk + half_height_weights;
142
143 const fixed_point<promoted_type> i_value(in[offset_slice_in + xk + yk * width_in], fixed_point_position, true);
144 const fixed_point<promoted_type> w_value(weights[idx + idy * width_weights + ifm * width_weights * height_weights], fixed_point_position, true);
145 const fixed_point<promoted_type> iw = i_value * w_value;
146 acc = iw + acc;
147 }
148 }
149 }
150 }
151
152 // Get the bias
153 const fixed_point<promoted_type> b(*bias, fixed_point_position, true);
154
155 // Accumulate the bias and covert back
156 acc = acc + b;
157 fixed_point<T> res(acc);
158 *out = res.raw();
159}
160
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100161template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100162void 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)
163{
164 for(int x = 0; x < cols_weights; ++x)
165 {
166 T acc = 0.0f;
167 for(int y = 0; y < rows_weights; ++y)
168 {
169 acc += in[y] * weights[x + y * cols_weights];
170 }
171 out[x] = acc + bias[x];
172 }
173}
174
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100175// Vector matrix multiply for fixed point type
176template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
177void 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 +0100178{
179 using namespace fixed_point_arithmetic;
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100180 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100181
182 for(int x = 0; x < cols_weights; ++x)
183 {
184 // Reset accumulator
185 fixed_point<promoted_type> acc(0, fixed_point_position);
186
187 for(int y = 0; y < rows_weights; ++y)
188 {
189 const fixed_point<promoted_type> i_value(in[y], fixed_point_position, true);
190 const fixed_point<promoted_type> w_value(weights[x + y * cols_weights], fixed_point_position, true);
191 const fixed_point<promoted_type> iw = i_value * w_value;
192 acc = iw + acc;
193 }
194
195 // Get the bias
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100196 const fixed_point<T> b(bias[x], fixed_point_position, true);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100197
198 // Convert back and accumulate the bias
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100199 fixed_point<T> res(acc);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100200 res = res + b;
201
202 // Store the result
203 out[x] = res.raw();
204 }
205}
206
SiCong Libacaf9a2017-06-19 13:41:45 +0100207// Return a tensor element at a specified coordinate with different border modes
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100208template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
209T tensor_elem_at(const Tensor<T> &in, Coordinates &coord, BorderMode border_mode, T constant_border_value)
210{
211 const int x = coord.x();
212 const int y = coord.y();
213 const int width = static_cast<int>(in.shape().x());
214 const int height = static_cast<int>(in.shape().y());
215
SiCong Libacaf9a2017-06-19 13:41:45 +0100216 // If coordinates beyond range of tensor's width or height
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100217 if(x < 0 || y < 0 || x >= width || y >= height)
218 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100219 if(border_mode == BorderMode::REPLICATE)
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100220 {
221 coord.set(0, std::max(0, std::min(x, width - 1)));
222 coord.set(1, std::max(0, std::min(y, height - 1)));
223 return in[coord2index(in.shape(), coord)];
224 }
225 else
226 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100227 return constant_border_value;
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100228 }
229 }
230 else
231 {
232 return in[coord2index(in.shape(), coord)];
233 }
234}
235
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100236/** Apply 2D spatial filter on a single element of @p in at coordinates @p coord
237 *
238 * - filter sizes have to be odd number
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100239 * - Row major order of filter assumed
240 * - TO_ZERO rounding policy assumed
241 * - SATURATE convert policy assumed
242 *
243 */
244template <typename T1, typename T2, typename T3>
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100245void 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,
246 T1 constant_border_value = 0)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100247{
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100248 double val = 0;
249 const int x = coord.x();
250 const int y = coord.y();
251 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 +0100252 {
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100253 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 +0100254 {
255 coord.set(0, i);
256 coord.set(1, j);
SiCong Libacaf9a2017-06-19 13:41:45 +0100257 val += static_cast<double>(*filter_itr) * tensor_elem_at(in, coord, border_mode, constant_border_value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100258 ++filter_itr;
259 }
260 }
261 coord.set(0, x);
262 coord.set(1, y);
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100263 const double rounded_val = support::cpp11::trunc(val * static_cast<double>(scale));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100264 out[coord2index(in.shape(), coord)] = saturate_cast<T3>(rounded_val);
265}
266} // namespace
267
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100268// Sobel 3x3
269template <typename T1, typename T2>
270void sobel_3x3(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
271{
272 const std::array<int8_t, 9> sobel_x{ { -1, 0, 1, -2, 0, 2, -1, 0, 1 } };
273 const std::array<int8_t, 9> sobel_y{ { -1, -2, -1, 0, 0, 0, 1, 2, 1 } };
274
275 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
276 {
277 const Coordinates id = index2coord(in.shape(), element_idx);
278
279 apply_2d_spatial_filter(id, in, out_x, TensorShape(3U, 3U), sobel_x.data(), 1.f, border_mode, constant_border_value);
280 apply_2d_spatial_filter(id, in, out_y, TensorShape(3U, 3U), sobel_y.data(), 1.f, border_mode, constant_border_value);
281 }
282}
283
284// Sobel 5x5
285template <typename T1, typename T2>
286void sobel_5x5(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
287{
288 const std::array<int8_t, 25> sobel_x{ {
289 -1, -2, 0, 2, 1,
290 -4, -8, 0, 8, 4,
291 -6, -12, 0, 12, 6,
292 -4, -8, 0, 8, 4,
293 -1, -2, 0, 2, 1
294 } };
295
296 const std::array<int8_t, 25> sobel_y{ {
297 -1, -4, -6, -4, -1,
298 -2, -8, -12, -8, -2,
299 0, 0, 0, 0, 0,
300 2, 8, 12, 8, 2,
301 1, 4, 6, 4, 1
302 } };
303
304 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
305 {
306 const Coordinates id = index2coord(in.shape(), element_idx);
307
308 apply_2d_spatial_filter(id, in, out_x, TensorShape(5U, 5U), sobel_x.data(), 1.f, border_mode, constant_border_value);
309 apply_2d_spatial_filter(id, in, out_y, TensorShape(5U, 5U), sobel_y.data(), 1.f, border_mode, constant_border_value);
310 }
311}
312
Giorgio Arenaf7959862017-06-13 15:19:51 +0100313// Mean Standard Deviation
314template <typename T1>
315void mean_and_standard_deviation(const Tensor<T1> &in, float &mean, float &std_dev)
316{
317 int num_elements = in.num_elements();
318
319 // Calculate mean
320 mean = 0.f;
321 for(int i = 0; i < num_elements; ++i)
322 {
323 mean += in[i];
324 }
325 mean /= num_elements;
326
327 // Calculate standard deviation
328 std_dev = 0.f;
329 for(int i = 0; i < num_elements; ++i)
330 {
331 std_dev += (mean - in[i]) * (mean - in[i]);
332 }
333 std_dev = sqrt(std_dev / num_elements);
334}
335
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100336// Integral Image
337void integral_image(const Tensor<uint8_t> &in, Tensor<uint32_t> &out)
338{
339 // Length of dimensions
340 const size_t width = in.shape().x();
341 const size_t height = in.shape().y();
342 const size_t depth = in.shape().z() * in.shape()[3] * in.shape()[4] * in.shape()[5];
343
344 const size_t image_size = width * height;
345
346 for(size_t z = 0; z < depth; ++z)
347 {
348 size_t current_image = z * image_size;
349
350 //First element of each image
351 out[current_image] = in[current_image];
352
353 // First row of each image (add only pixel on the left)
354 for(size_t x = 1; x < width; ++x)
355 {
356 out[current_image + x] = static_cast<uint32_t>(in[current_image + x]) + out[current_image + x - 1];
357 }
358
359 // Subsequent rows
360 for(size_t y = 1; y < height; ++y)
361 {
362 size_t current_row = current_image + (width * y);
363
364 // First element of each row (add only pixel up)
365 out[current_row] = static_cast<uint32_t>(in[current_row]) + out[current_row - width];
366
367 // Following row elements
368 for(size_t x = 1; x < width; ++x)
369 {
370 size_t current_pixel = current_row + x;
371
372 // out = in + up(out) + left(out) - up_left(out)
373 out[current_pixel] = static_cast<uint32_t>(in[current_pixel]) + out[current_pixel - 1]
374 + out[current_pixel - width] - out[current_pixel - width - 1];
375 }
376 }
377 }
378}
379
380// Absolute difference
381template <typename T1, typename T2, typename T3>
382void absolute_difference(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out)
383{
384 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
385
386 for(int i = 0; i < in1.num_elements(); ++i)
387 {
388 intermediate_type val = std::abs(static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]));
389 out[i] = saturate_cast<T3>(val);
390 }
391}
392
393// Accumulate
394template <typename T1, typename T2>
395void accumulate(const Tensor<T1> &in, Tensor<T2> &out)
396{
397 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
398
399 for(int i = 0; i < in.num_elements(); ++i)
400 {
401 intermediate_type val = static_cast<intermediate_type>(out[i]) + static_cast<intermediate_type>(in[i]);
402 out[i] = saturate_cast<T2>(val);
403 }
404}
405
406// Accumulate squared
407template <typename T1, typename T2>
408void accumulate_squared(const Tensor<T1> &in, Tensor<T2> &out, uint32_t shift)
409{
410 if(shift > 15)
411 {
412 ARM_COMPUTE_ERROR("Shift in accumulate_squared must be within the range [0, 15]");
413 }
414 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
415 intermediate_type denom = 1 << shift;
416
417 for(int i = 0; i < in.num_elements(); ++i)
418 {
419 intermediate_type val = static_cast<intermediate_type>(out[i]) + (static_cast<intermediate_type>(in[i]) * static_cast<intermediate_type>(in[i]) / denom);
420 out[i] = saturate_cast<T2>(val);
421 }
422}
423
424// Accumulate weighted
425template <typename T>
426void accumulate_weighted(const Tensor<T> &in, Tensor<T> &out, float alpha)
427{
428 if(alpha < 0.f || alpha > 1.f)
429 {
430 ARM_COMPUTE_ERROR("Weight (alpha) specified in accumulate_weighted must be within the range [0, 1]");
431 }
432 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
433
434 for(int i = 0; i < in.num_elements(); ++i)
435 {
436 double val = (1. - static_cast<double>(alpha)) * static_cast<intermediate_type>(out[i]) + static_cast<double>(alpha) * static_cast<intermediate_type>(in[i]);
437 out[i] = static_cast<T>(val);
438 }
439}
440
441// Arithmetic addition
442template <typename T1, typename T2, typename T3>
443void arithmetic_addition(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
444{
445 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
446
447 for(int i = 0; i < in1.num_elements(); ++i)
448 {
449 intermediate_type val = static_cast<intermediate_type>(in1[i]) + static_cast<intermediate_type>(in2[i]);
450 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
451 }
452}
453
454// Arithmetic Subtraction
455template <typename T1, typename T2, typename T3>
456void arithmetic_subtraction(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
457{
458 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
459
460 for(int i = 0; i < in1.num_elements(); ++i)
461 {
462 intermediate_type val = static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]);
463 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
464 }
465}
466
467// Bitwise and
468template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
469void bitwise_and(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
470{
471 for(int i = 0; i < in1.num_elements(); ++i)
472 {
473 out[i] = in1[i] & in2[i];
474 }
475}
476
477// Bitwise or
478template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
479void bitwise_or(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
480{
481 for(int i = 0; i < in1.num_elements(); ++i)
482 {
483 out[i] = in1[i] | in2[i];
484 }
485}
486
487// Bitwise xor
488template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
489void bitwise_xor(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
490{
491 for(int i = 0; i < in1.num_elements(); ++i)
492 {
493 out[i] = in1[i] ^ in2[i];
494 }
495}
496
497// Bitwise not
498template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
499void bitwise_not(const Tensor<T> &in, Tensor<T> &out)
500{
501 for(int i = 0; i < in.num_elements(); ++i)
502 {
503 out[i] = ~in[i];
504 }
505}
506
SiCong Libacaf9a2017-06-19 13:41:45 +0100507// Box3x3 filter
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100508template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
SiCong Libacaf9a2017-06-19 13:41:45 +0100509void box3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100510{
511 const std::array<T, 9> filter{ { 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
SiCong Libacaf9a2017-06-19 13:41:45 +0100512 float scale = 1.f / static_cast<float>(filter.size());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100513 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
514 {
515 const Coordinates id = index2coord(in.shape(), element_idx);
SiCong Libacaf9a2017-06-19 13:41:45 +0100516 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 +0100517 }
518}
519
520// Depth conversion
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100521template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&std::is_floating_point<T2>::value, int >::type = 0 >
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100522void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
523{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100524 using namespace fixed_point_arithmetic;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100525
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100526 const int fixed_point_position = in.fixed_point_position();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100527 for(int i = 0; i < in.num_elements(); ++i)
528 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100529 out[i] = static_cast<float>(fixed_point<T1>(in[i], fixed_point_position, true));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100530 }
531}
532
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100533template < typename T1, typename T2, typename std::enable_if < std::is_floating_point<T1>::value &&std::is_integral<T2>::value, int >::type = 0 >
534void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100535{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100536 using namespace fixed_point_arithmetic;
537
538 const int fixed_point_position = out.fixed_point_position();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100539 for(int i = 0; i < in.num_elements(); ++i)
540 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100541 out[i] = fixed_point<T2>(in[i], fixed_point_position).raw();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100542 }
543}
544
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100545template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&std::is_integral<T2>::value, int >::type = 0 >
546void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100547{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100548 // Up-casting
549 if(std::numeric_limits<T1>::digits <= std::numeric_limits<T2>::digits)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100550 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100551 for(int i = 0; i < in.num_elements(); ++i)
552 {
553 out[i] = static_cast<T2>(in[i]) << shift;
554 }
555 }
556 // Down-casting
557 else
558 {
559 for(int i = 0; i < in.num_elements(); ++i)
560 {
561 T1 val = in[i] >> shift;
562 out[i] = ((policy == ConvertPolicy::SATURATE) ? saturate_cast<T2>(val) : static_cast<T2>(val));
563 }
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100564 }
565}
566
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100567template < typename T1, typename T2, typename std::enable_if < std::is_floating_point<T1>::value &&std::is_floating_point<T2>::value, int >::type = 0 >
568void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100569{
570 for(int i = 0; i < in.num_elements(); ++i)
571 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100572 out[i] = static_cast<T2>(in[i]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100573 }
574}
575
SiCong Li5a536642017-06-19 14:47:05 +0100576// Gaussian3x3 filter
577template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
578void gaussian3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
579{
580 const std::array<T, 9> filter{ { 1, 2, 1, 2, 4, 2, 1, 2, 1 } };
581 const float scale = 1.f / 16.f;
582 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
583 {
584 const Coordinates id = index2coord(in.shape(), element_idx);
585 apply_2d_spatial_filter(id, in, out, TensorShape(3U, 3U), filter.data(), scale, border_mode, constant_border_value);
586 }
587}
588
SiCong Li3eb263e2017-06-19 15:31:43 +0100589// Gaussian5x5 filter
590template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
591void gaussian5x5(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
592{
593 const std::array<T, 25> filter{ {
594 1, 4, 6, 4, 1,
595 4, 16, 24, 16, 4,
596 6, 24, 36, 24, 6,
597 4, 16, 24, 16, 4,
598 1, 4, 6, 4, 1
599 } };
600 const float scale = 1.f / 256.f;
601 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
602 {
603 const Coordinates id = index2coord(in.shape(), element_idx);
604 apply_2d_spatial_filter(id, in, out, TensorShape(5U, 5U), filter.data(), scale, border_mode, constant_border_value);
605 }
606}
607
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100608// Matrix multiplication for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100609template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100610void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
611{
612 const int M = out.shape().y();
613 const int N = out.shape().x();
614 const int K = in1.shape().x();
615
616 for(int r = 0; r < M; ++r)
617 {
618 for(int c = 0; c < N; ++c)
619 {
620 T acc = 0.0f;
621
622 for(int k = 0; k < K; ++k)
623 {
624 const T a0 = in1[r * K + k];
625 const T b0 = in2[k * N + c];
626
627 acc += a0 * b0;
628 }
629
630 // Finalize the result: A * B * alpha + C * beta
631 const T c0 = in3[c + r * N];
632 out[c + r * N] = alpha * acc + beta * c0;
633 }
634 }
635}
636
637// Matrix multiplication for fixed point type
638template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
639void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
640{
641 using namespace fixed_point_arithmetic;
642
643 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
644
645 const int M = out.shape().y();
646 const int N = out.shape().x();
647 const int K = in1.shape().x();
648 const int8_t fixed_point_position = static_cast<int8_t>(in1.fixed_point_position());
649
650 const fixed_point<T> alpha_q(alpha, fixed_point_position);
651 const fixed_point<T> beta_q(beta, fixed_point_position);
652
653 for(int r = 0; r < M; ++r)
654 {
655 for(int c = 0; c < N; ++c)
656 {
657 fixed_point<promoted_type> acc_q(0, fixed_point_position);
658
659 for(int k = 0; k < K; ++k)
660 {
661 const fixed_point<promoted_type> a0_q(in1[r * K + k], fixed_point_position, true);
662 const fixed_point<promoted_type> b0_q(in2[k * N + c], fixed_point_position, true);
663 const fixed_point<promoted_type> axb_q = a0_q * b0_q;
664
665 acc_q = axb_q + acc_q;
666 }
667
668 // Finalize the result: A * B * alpha + C * beta
669 const fixed_point<T> c0_q(in3[c + r * N], fixed_point_position, true);
670
671 fixed_point<T> res_q(acc_q);
672 res_q = alpha_q * res_q;
673 res_q = (c0_q * beta_q) + res_q;
674
675 // Store the result
676 out[c + r * N] = res_q.raw();
677 }
678 }
679}
680
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100681// Non linear filter
682template <typename T>
683void non_linear_filter(const Tensor<T> &in, Tensor<T> &out, NonLinearFilterFunction function, unsigned int mask_size,
684 MatrixPattern pattern, const uint8_t *mask, BorderMode border_mode, uint8_t constant_border_value)
685{
SiCong Li7a035752017-06-28 15:27:02 +0100686 ARM_COMPUTE_ERROR_ON(pattern == MatrixPattern::OTHER && mask == nullptr);
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100687
688 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
689
690 const int sq_mask_size = mask_size * mask_size;
691 const int half_mask_size = mask_size / 2;
692 std::vector<intermediate_type> vals(sq_mask_size);
693 intermediate_type current_value = 0;
694
SiCong Li7a035752017-06-28 15:27:02 +0100695 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 +0100696
697 for(int element_idx = 0, count = 0, index = 0; element_idx < in.num_elements(); ++element_idx, count = 0, index = 0)
698 {
699 Coordinates id = index2coord(in.shape(), element_idx);
700 if(is_in_valid_region(valid_region, id))
701 {
702 int idx = id.x();
703 int idy = id.y();
704 for(int y = idy - half_mask_size; y <= idy + half_mask_size; ++y)
705 {
706 for(int x = idx - half_mask_size; x <= idx + half_mask_size; ++x, ++index)
707 {
708 id.set(0, x);
709 id.set(1, y);
710 current_value = tensor_elem_at(in, id, border_mode, constant_border_value);
711
712 if(mask[index] == 255)
713 {
714 vals[count] = static_cast<intermediate_type>(current_value);
715 ++count;
716 }
717 }
718 }
719 std::sort(vals.begin(), vals.begin() + count);
720 switch(function)
721 {
722 case NonLinearFilterFunction::MIN:
723 out[element_idx] = saturate_cast<T>(vals[0]);
724 break;
725 case NonLinearFilterFunction::MAX:
726 out[element_idx] = saturate_cast<T>(vals[count - 1]);
727 break;
728 case NonLinearFilterFunction::MEDIAN:
729 out[element_idx] = saturate_cast<T>(vals[count / 2]);
730 break;
731 default:
732 ARM_COMPUTE_ERROR("Unsupported NonLinearFilter function.");
733 }
734 }
735 }
736}
737
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100738// Pixel-wise multiplication
739template <typename T1, typename T2, typename T3>
740void pixel_wise_multiplication(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, float scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
741{
742 if(scale < 0)
743 {
744 ARM_COMPUTE_ERROR("Scale of pixel-wise multiplication must be non-negative");
745 }
746 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
747 for(int i = 0; i < in1.num_elements(); ++i)
748 {
749 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 +0100750 if(is_floating_point<T3>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100751 {
752 out[i] = val;
753 }
754 else
755 {
756 double rounded_val = 0;
757 switch(rounding_policy)
758 {
759 case(RoundingPolicy::TO_ZERO):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100760 rounded_val = support::cpp11::trunc(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100761 break;
762 case(RoundingPolicy::TO_NEAREST_UP):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100763 rounded_val = round_half_up(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100764 break;
765 case(RoundingPolicy::TO_NEAREST_EVEN):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100766 rounded_val = round_half_even(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100767 break;
768 default:
769 ARM_COMPUTE_ERROR("Unsupported rounding policy");
770 }
771 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(rounded_val) : static_cast<T3>(rounded_val);
772 }
773 }
774}
775
776// Fixed-point Pixel-wise Multiplication
777template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
778void fixed_point_pixel_wise_multiplication(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out, int scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
779{
780 using namespace fixed_point_arithmetic;
781
782 const int fixed_point_position = in1.fixed_point_position();
783
784 ARM_COMPUTE_ERROR_ON_MSG(in1.data_type() != in2.data_type() || in1.data_type() != out.data_type(),
785 "Tensors must all have the same DataType");
786 ARM_COMPUTE_ERROR_ON_MSG(fixed_point_position != in2.fixed_point_position() || fixed_point_position != out.fixed_point_position(),
787 "Fixed-point position must be the same for both inputs and outputs");
788
789 // Validate fixed_point_position
790 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS8) && (fixed_point_position == 0 || fixed_point_position > 7));
791 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS16) && (fixed_point_position == 0 || fixed_point_position > 15));
792
793 fixed_point<T> fp_scale(scale, fixed_point_position);
794 const bool is_sat = convert_policy == ConvertPolicy::SATURATE;
795 const bool do_scaling = scale != 1;
796
797 for(int i = 0; i < in1.num_elements(); ++i)
798 {
799 fixed_point<T> val1(in1[i], fixed_point_position, true);
800 fixed_point<T> val2(in2[i], fixed_point_position, true);
801 fixed_point<T> res = (is_sat) ? val1 * val2 : mul<OverflowPolicy::WRAP>(val1, val2);
802 if(do_scaling)
803 {
804 res = (is_sat) ? res * fp_scale : mul<OverflowPolicy::WRAP>(res, fp_scale);
805 }
806 out[i] = res.raw();
807 }
808}
809
810// Threshold
811template <typename T>
812void threshold(const Tensor<T> &in, Tensor<T> &out, uint8_t threshold, uint8_t false_value, uint8_t true_value, ThresholdType type, uint8_t upper)
813{
814 switch(type)
815 {
816 case ThresholdType::BINARY:
817 for(int i = 0; i < in.num_elements(); ++i)
818 {
819 out[i] = ((in[i] > threshold) ? true_value : false_value);
820 }
821 break;
822 case ThresholdType::RANGE:
823 for(int i = 0; i < in.num_elements(); ++i)
824 {
825 if(in[i] > upper)
826 {
827 out[i] = false_value;
828 }
829 else if(in[i] < threshold)
830 {
831 out[i] = false_value;
832 }
833 else
834 {
835 out[i] = true_value;
836 }
837 }
838 break;
839 default:
840 ARM_COMPUTE_ERROR("Thresholding type not recognised");
841 break;
842 }
843}
844
845// Activation Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100846template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100847void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
848{
849 const T a = static_cast<T>(act_info.a());
850 const T b = static_cast<T>(act_info.b());
851
852 for(int i = 0; i < in.num_elements(); ++i)
853 {
854 T x = in[i];
855 switch(act_info.activation())
856 {
857 case ActivationLayerInfo::ActivationFunction::ABS:
858 out[i] = std::abs(x);
859 break;
860 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
861 out[i] = std::min<T>(a, std::max<T>(0, x));
862 break;
863 case ActivationLayerInfo::ActivationFunction::LINEAR:
864 out[i] = a * x + b;
865 break;
866 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
867 out[i] = static_cast<T>(1) / (static_cast<T>(1) + std::exp(-x));
868 break;
869 case ActivationLayerInfo::ActivationFunction::RELU:
870 out[i] = std::max<T>(0, x);
871 break;
872 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
873 out[i] = std::log(static_cast<T>(1) + std::exp(x));
874 break;
875 case ActivationLayerInfo::ActivationFunction::SQRT:
876 out[i] = std::sqrt(x);
877 break;
878 case ActivationLayerInfo::ActivationFunction::SQUARE:
879 out[i] = x * x;
880 break;
881 case ActivationLayerInfo::ActivationFunction::TANH:
882 out[i] = a * std::tanh(b * x);
883 break;
884 default:
885 ARM_COMPUTE_ERROR("Activation function not recognised");
886 break;
887 }
888 }
889}
890
891// Activation Layer for fixed point type
892template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
893void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
894{
895 using namespace fixed_point_arithmetic;
896 int fixed_point_position = in.fixed_point_position();
897 ActivationLayerInfo::ActivationFunction act_func = act_info.activation();
898 const fixed_point<T> a(act_info.a(), fixed_point_position);
899 const fixed_point<T> b(act_info.b(), fixed_point_position);
900 const fixed_point<T> const_0(0, fixed_point_position);
901 const fixed_point<T> const_1(1, fixed_point_position);
902
903 for(int i = 0; i < in.num_elements(); ++i)
904 {
905 fixed_point<T> x(in[i], fixed_point_position, true);
906 switch(act_func)
907 {
908 case ActivationLayerInfo::ActivationFunction::ABS:
909 out[i] = abs(x).raw();
910 break;
911 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
912 out[i] = min(a, max(const_0, x)).raw();
913 break;
914 case ActivationLayerInfo::ActivationFunction::LINEAR:
915 out[i] = add(b, mul(a, x)).raw();
916 break;
917 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
918 out[i] = (const_1 / (const_1 + exp(-x))).raw();
919 break;
920 case ActivationLayerInfo::ActivationFunction::RELU:
921 out[i] = max(const_0, x).raw();
922 break;
923 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
924 out[i] = log(const_1 + exp(x)).raw();
925 break;
926 case ActivationLayerInfo::ActivationFunction::SQRT:
927 out[i] = (const_1 / inv_sqrt(x)).raw();
928 break;
929 case ActivationLayerInfo::ActivationFunction::SQUARE:
930 out[i] = mul(x, x).raw();
931 break;
932 case ActivationLayerInfo::ActivationFunction::TANH:
933 out[i] = tanh(x).raw();
934 break;
935 default:
936 ARM_COMPUTE_ERROR("Activation function not recognised");
937 break;
938 }
939 }
940}
941
942// Batch Normalization Layer for fixed point type
943template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
944void 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)
945{
946 const int cols = static_cast<int>(in.shape()[0]);
947 const int rows = static_cast<int>(in.shape()[1]);
948 const int depth = static_cast<int>(in.shape()[2]);
949 int upper_dims = in.shape().total_size() / (cols * rows * depth);
950
951 for(int r = 0; r < upper_dims; ++r)
952 {
953 for(int i = 0; i < depth; ++i)
954 {
955 for(int k = 0; k < rows; ++k)
956 {
957 for(int l = 0; l < cols; ++l)
958 {
959 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
960 fixed_point_arithmetic::fixed_point<T> in_qs8(in[pos], fixed_point_position, true);
961 fixed_point_arithmetic::fixed_point<T> var_qs8(var[i], fixed_point_position, true);
962 fixed_point_arithmetic::fixed_point<T> mean_qs8(mean[i], fixed_point_position, true);
963 fixed_point_arithmetic::fixed_point<T> beta_qs8(beta[i], fixed_point_position, true);
964 fixed_point_arithmetic::fixed_point<T> gamma_qs8(gamma[i], fixed_point_position, true);
965 fixed_point_arithmetic::fixed_point<T> epsilon_qs8(epsilon, fixed_point_position);
966
967 auto denominator = fixed_point_arithmetic::inv_sqrt(var_qs8 + epsilon_qs8);
968 auto numerator = in_qs8 - mean_qs8;
969 auto x_bar = numerator * denominator;
970 x_bar = beta_qs8 + x_bar * gamma_qs8;
971 out[pos] = x_bar.raw();
972 }
973 }
974 }
975 }
976}
977
978// Batch Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100979template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100980void 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)
981{
982 const int cols = static_cast<int>(in.shape()[0]);
983 const int rows = static_cast<int>(in.shape()[1]);
984 const int depth = static_cast<int>(in.shape()[2]);
985 int upper_dims = in.shape().total_size() / (cols * rows * depth);
986
987 for(int r = 0; r < upper_dims; ++r)
988 {
989 for(int i = 0; i < depth; ++i)
990 {
991 for(int k = 0; k < rows; ++k)
992 {
993 for(int l = 0; l < cols; ++l)
994 {
995 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
996 const float denominator = sqrt(var[i] + epsilon);
997 const float numerator = in[pos] - mean[i];
998 const float x_bar = numerator / denominator;
999 out[pos] = beta[i] + x_bar * gamma[i];
1000 }
1001 }
1002 }
1003 }
1004}
1005
1006// Convolution layer
1007template <typename T>
1008void convolution_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out, const PadStrideInfo &conv_info)
1009{
1010 const int width_in = in.shape().x();
1011 const int height_in = in.shape().y();
1012 const int depth_in = in.shape().z();
1013 const int width_out = out.shape().x();
1014 const int height_out = out.shape().y();
1015 const int depth_out = out.shape().z();
1016 const int width_weights = weights.shape().x();
1017 const int height_weights = weights.shape().y();
1018 const int depth_weights = weights.shape().z();
1019 const int pad_xi = std::min(static_cast<int>(conv_info.pad().first), width_weights / 2);
1020 const int pad_yi = std::min(static_cast<int>(conv_info.pad().second), height_weights / 2);
1021 const int start_xi = width_weights / 2 - pad_xi;
1022 const int start_yi = height_weights / 2 - pad_yi;
1023 const int end_xi = width_in - start_xi;
1024 const int end_yi = height_in - start_yi;
1025 const int stride_xi = conv_info.stride().first;
1026 const int stride_yi = conv_info.stride().second;
1027 const int num_batches = in.shape().total_size() / (width_in * height_in * depth_in);
1028
1029 for(int r = 0; r < num_batches; ++r)
1030 {
1031 for(int yi = start_yi; yi < end_yi; yi += stride_yi)
1032 {
1033 for(int xi = start_xi; xi < end_xi; xi += stride_xi)
1034 {
1035 for(int ofm = 0; ofm < depth_out; ++ofm)
1036 {
1037 // Compute input and output offsets
1038 const int offset_in = r * width_in * height_in * depth_in;
1039 const int xo = (xi - start_xi) / stride_xi;
1040 const int yo = (yi - start_yi) / stride_yi;
1041 const int offset_out = xo + yo * width_out + ofm * width_out * height_out + r * width_out * height_out * depth_out;
1042
1043 // Compute 3D convolution
1044 convolution3d(in.data() + offset_in,
1045 weights.data() + ofm * width_weights * height_weights * depth_weights,
1046 bias.data() + ofm,
1047 out.data() + offset_out,
1048 xi, yi,
1049 width_in, height_in, depth_in,
1050 width_weights, height_weights,
1051 static_cast<int8_t>(in.fixed_point_position()));
1052 }
1053 }
1054 }
1055 }
1056}
1057
1058// Fully connected layer
1059template <typename T>
1060void fully_connected_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out)
1061{
1062 ARM_COMPUTE_ERROR_ON(weights.shape().x() != out.shape().x());
1063 ARM_COMPUTE_ERROR_ON(weights.shape().y() != in.shape().x() * in.shape().y() * in.shape().z());
1064 const int cols_weights = weights.shape().x();
1065 const int rows_weights = weights.shape().y();
1066 const int num_batches = in.shape().total_size() / rows_weights;
1067
1068 for(int k = 0; k < num_batches; ++k)
1069 {
1070 vector_matrix_multiply<T>(in.data() + k * rows_weights,
1071 weights.data(),
1072 bias.data(),
1073 out.data() + k * cols_weights,
1074 cols_weights,
1075 rows_weights,
1076 in.fixed_point_position());
1077 }
1078}
1079
1080// Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001081template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001082void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1083{
1084 const uint32_t norm_size = norm_info.norm_size();
1085 NormType type = norm_info.type();
1086 float beta = norm_info.beta();
1087 uint32_t kappa = norm_info.kappa();
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);
1093
1094 float coeff = norm_info.scale_coeff();
1095 int radius_cols = norm_size / 2;
1096 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1097 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1098
1099 if(type == NormType::CROSS_MAP)
1100 {
1101 // Remove also depth from upper dimensions since it is the axes we want
1102 // to use for normalization
1103 upper_dims /= depth;
1104 for(int r = 0; r < upper_dims; ++r)
1105 {
1106 for(int i = 0; i < rows; ++i)
1107 {
1108 for(int k = 0; k < cols; ++k)
1109 {
1110 for(int l = 0; l < depth; ++l)
1111 {
1112 float accumulated_scale = 0.f;
1113 for(int j = -radius_cols; j <= radius_cols; ++j)
1114 {
1115 const int z = l + j;
1116 if(z >= 0 && z < depth)
1117 {
1118 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1119 accumulated_scale += value * value;
1120 }
1121 }
1122 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = kappa + accumulated_scale * coeff;
1123 }
1124 }
1125 }
1126 }
1127 }
1128 else
1129 {
1130 for(int r = 0; r < upper_dims; ++r)
1131 {
1132 for(int i = 0; i < rows; ++i)
1133 {
1134 for(int k = 0; k < cols; ++k)
1135 {
1136 float accumulated_scale = 0.f;
1137 for(int j = -radius_rows; j <= radius_rows; ++j)
1138 {
1139 const int y = i + j;
1140 for(int l = -radius_cols; l <= radius_cols; ++l)
1141 {
1142 const int x = k + l;
1143 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1144 {
1145 const T value = in[x + y * cols + r * cols * rows];
1146 accumulated_scale += value * value;
1147 }
1148 }
1149 }
1150 out[k + i * cols + r * cols * rows] = kappa + accumulated_scale * coeff;
1151 }
1152 }
1153 }
1154 }
1155
1156 if(beta == 1.f)
1157 {
1158 for(int i = 0; i < out.num_elements(); ++i)
1159 {
1160 out[i] = in[i] / out[i];
1161 }
1162 }
1163 else if(beta == 0.5f)
1164 {
1165 for(int i = 0; i < out.num_elements(); ++i)
1166 {
1167 out[i] = in[i] / std::sqrt(out[i]);
1168 }
1169 }
1170 else
1171 {
1172 for(int i = 0; i < out.num_elements(); ++i)
1173 {
1174 out[i] = in[i] * std::exp(std::log(out[i]) * -beta);
1175 }
1176 }
1177}
1178// Normalization Layer for fixed-point types
1179template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1180void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1181{
1182 using namespace fixed_point_arithmetic;
1183
1184 const int fixed_point_position = in.fixed_point_position();
1185
1186 const uint32_t norm_size = norm_info.norm_size();
1187 NormType type = norm_info.type();
1188 fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1189 fixed_point<T> kappa(norm_info.kappa(), fixed_point_position);
1190
1191 const int cols = static_cast<int>(in.shape()[0]);
1192 const int rows = static_cast<int>(in.shape()[1]);
1193 const int depth = static_cast<int>(in.shape()[2]);
1194 int upper_dims = in.shape().total_size() / (cols * rows);
1195
1196 fixed_point<T> coeff(norm_info.scale_coeff(), fixed_point_position);
1197 int radius_cols = norm_size / 2;
1198 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1199 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1200
1201 if(type == NormType::CROSS_MAP)
1202 {
1203 // Remove also depth from upper dimensions since it is the axes we want
1204 // to use for normalization
1205 upper_dims /= depth;
1206 for(int r = 0; r < upper_dims; ++r)
1207 {
1208 for(int i = 0; i < rows; ++i)
1209 {
1210 for(int k = 0; k < cols; ++k)
1211 {
1212 for(int l = 0; l < depth; ++l)
1213 {
1214 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1215 for(int j = -radius_cols; j <= radius_cols; ++j)
1216 {
1217 const int z = l + j;
1218 if(z >= 0 && z < depth)
1219 {
1220 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1221 const fixed_point<T> fp_value(value, fixed_point_position, true);
1222 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1223 }
1224 }
1225 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1226 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = accumulated_scale.raw();
1227 }
1228 }
1229 }
1230 }
1231 }
1232 else
1233 {
1234 for(int r = 0; r < upper_dims; ++r)
1235 {
1236 for(int i = 0; i < rows; ++i)
1237 {
1238 for(int k = 0; k < cols; ++k)
1239 {
1240 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1241 for(int j = -radius_rows; j <= radius_rows; ++j)
1242 {
1243 const int y = i + j;
1244 for(int l = -radius_cols; l <= radius_cols; ++l)
1245 {
1246 const int x = k + l;
1247 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1248 {
1249 const T value = in[x + y * cols + r * cols * rows];
1250 const fixed_point<T> fp_value(value, fixed_point_position, true);
1251 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1252 }
1253 }
1254 }
1255 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1256 out[k + i * cols + r * cols * rows] = accumulated_scale.raw();
1257 }
1258 }
1259 }
1260 }
1261
1262 if(norm_info.beta() == 1.f)
1263 {
1264 for(int i = 0; i < out.num_elements(); ++i)
1265 {
1266 fixed_point<T> res = div(fixed_point<T>(in[i], fixed_point_position, true), fixed_point<T>(out[i], fixed_point_position, true));
1267 out[i] = res.raw();
1268 }
1269 }
1270 else
1271 {
1272 const fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1273 for(int i = 0; i < out.num_elements(); ++i)
1274 {
1275 fixed_point<T> res = pow(fixed_point<T>(out[i], fixed_point_position, true), beta);
1276 res = div(fixed_point<T>(in[i], fixed_point_position, true), res);
1277 out[i] = res.raw();
1278 }
1279 }
1280}
1281
1282// Pooling layer
1283template <typename T>
1284void pooling_layer(const Tensor<T> &in, Tensor<T> &out, PoolingLayerInfo pool_info, int fixed_point_position)
1285{
1286 const int pool_size = pool_info.pool_size();
1287 PoolingType type = pool_info.pool_type();
1288 int pool_stride_x = 0;
1289 int pool_stride_y = 0;
1290 int pad_x = 0;
1291 int pad_y = 0;
1292 std::tie(pool_stride_x, pool_stride_y) = pool_info.pad_stride_info().stride();
1293 std::tie(pad_x, pad_y) = pool_info.pad_stride_info().pad();
1294
Georgios Pinitasce093142017-06-19 16:11:53 +01001295 const int w_in = static_cast<int>(in.shape()[0]);
1296 const int h_in = static_cast<int>(in.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001297
Georgios Pinitasce093142017-06-19 16:11:53 +01001298 const int w_out = static_cast<int>(out.shape()[0]);
1299 const int h_out = static_cast<int>(out.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001300
Georgios Pinitasce093142017-06-19 16:11:53 +01001301 int upper_dims = in.shape().total_size() / (w_in * h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001302
Georgios Pinitasce093142017-06-19 16:11:53 +01001303 int pooled_w = 0;
1304 int pooled_h = 0;
1305 if(pool_info.pad_stride_info().round() == DimensionRoundingType::CEIL)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001306 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001307 pooled_w = static_cast<int>(ceil(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1308 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 +01001309 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001310 else
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001311 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001312 pooled_w = static_cast<int>(floor(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1313 pooled_h = static_cast<int>(floor(static_cast<float>(h_in + 2 * pad_y - pool_size) / pool_stride_y)) + 1;
1314 }
1315
1316 if((pooled_w - 1) * pool_stride_x >= w_in + pad_x)
1317 {
1318 --pooled_w;
1319 }
1320 if((pooled_h - 1) * pool_stride_y >= h_in + pad_y)
1321 {
1322 --pooled_h;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001323 }
1324
1325 if(type == PoolingType::MAX)
1326 {
1327 for(int r = 0; r < upper_dims; ++r)
1328 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001329 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001330 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001331 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001332 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001333 int wstart = w * pool_stride_x - pad_x;
1334 int hstart = h * pool_stride_y - pad_y;
1335 int wend = std::min(wstart + pool_size, w_in);
1336 int hend = std::min(hstart + pool_size, h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001337 wstart = std::max(wstart, 0);
Georgios Pinitasce093142017-06-19 16:11:53 +01001338 hstart = std::max(hstart, 0);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001339
1340 T max_val = std::numeric_limits<T>::lowest();
1341 for(int y = hstart; y < hend; ++y)
1342 {
1343 for(int x = wstart; x < wend; ++x)
1344 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001345 T val = in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001346 if(val > max_val)
1347 {
1348 max_val = val;
1349 }
1350 }
1351 }
1352
Georgios Pinitasce093142017-06-19 16:11:53 +01001353 out[r * h_out * w_out + h * pooled_w + w] = max_val;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001354 }
1355 }
1356 }
1357 }
1358 else // Average pooling
1359 {
1360 for(int r = 0; r < upper_dims; ++r)
1361 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001362 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001363 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001364 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001365 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001366 T avg_val = 0;
1367 int wstart = w * pool_stride_x - pad_x;
1368 int hstart = h * pool_stride_y - pad_y;
1369 int wend = std::min(wstart + pool_size, w_in + pad_x);
1370 int hend = std::min(hstart + pool_size, h_in + pad_y);
1371 int pool = (hend - hstart) * (wend - wstart);
1372 wstart = std::max(wstart, 0);
1373 hstart = std::max(hstart, 0);
1374 wend = std::min(wend, w_in);
1375 hend = std::min(hend, h_in);
Pablo Tello383deec2017-06-23 10:40:05 +01001376 if(is_floating_point<T>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001377 {
1378 for(int y = hstart; y < hend; ++y)
1379 {
1380 for(int x = wstart; x < wend; ++x)
1381 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001382 avg_val += in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001383 }
1384 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001385 out[r * h_out * w_out + h * pooled_w + w] = avg_val / pool;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001386 }
1387 else
1388 {
1389 static std::array<qint8_t, 10> scale_values_q8 =
1390 { { 0x0, 0x0, 0x40, 0x2A, 0x20, 0x19, 0x15, 0x12, 0x10, 0xE } };
1391
1392 for(int y = hstart; y < hend; ++y)
1393 {
1394 for(int x = wstart; x < wend; ++x)
1395 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001396 avg_val = sqadd_qs8(avg_val, in[r * h_in * w_in + y * w_in + x]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001397 }
1398 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001399 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 +01001400 }
1401 }
1402 }
1403 }
1404 }
1405}
1406
Georgios Pinitas7b7858d2017-06-21 16:44:24 +01001407// Pooling layer
1408template <typename T>
1409void roi_pooling_layer(const Tensor<T> &in, Tensor<T> &out, const std::vector<ROI> &rois, const ROIPoolingLayerInfo &pool_info)
1410{
1411 const int num_rois = rois.size();
1412 const int width_in = in.shape().x();
1413 const int height_in = in.shape().y();
1414 const int fms = in.shape().z();
1415 const int volume_in = width_in * height_in * fms;
1416 const int pool_w = pool_info.pooled_width();
1417 const int pool_h = pool_info.pooled_height();
1418 const int volume_out = pool_w * pool_h * fms;
1419 const float roi_scale = pool_info.spatial_scale();
1420
1421 // Iterate through all rois
1422 for(int roi_idx = 0; roi_idx < num_rois; ++roi_idx)
1423 {
1424 // Get dimensions of current ROI
1425 const ROI &roi = rois[roi_idx];
1426
1427 int batch_id = roi.batch_idx;
1428 int roi_start_x = support::cpp11::round(roi.rect.x * roi_scale);
1429 int roi_start_y = support::cpp11::round(roi.rect.y * roi_scale);
1430 int roi_width = std::max(support::cpp11::round(roi.rect.width * roi_scale), 1.f);
1431 int roi_height = std::max(support::cpp11::round(roi.rect.height * roi_scale), 1.f);
1432
1433 // Determine pooling regions
1434 float pool_region_size_x = static_cast<float>(roi_width) / pool_w;
1435 float pool_region_size_y = static_cast<float>(roi_height) / pool_h;
1436
1437 // Iterate through all channel
1438 for(int fm = 0; fm < fms; ++fm)
1439 {
1440 // Calculate each output pixel
1441 for(int py = 0; py < pool_h; ++py)
1442 {
1443 for(int px = 0; px < pool_w; ++px)
1444 {
1445 int region_start_x = static_cast<int>(std::floor(px * pool_region_size_x));
1446 int region_end_x = static_cast<int>(std::ceil((px + 1) * pool_region_size_x));
1447 int region_start_y = static_cast<int>(std::floor(py * pool_region_size_y));
1448 int region_end_y = static_cast<int>(std::ceil((py + 1) * pool_region_size_y));
1449
1450 region_start_x = std::min(std::max(region_start_x + roi_start_x, 0), width_in);
1451 region_end_x = std::min(std::max(region_end_x + roi_start_x, 0), width_in);
1452 region_start_y = std::min(std::max(region_start_y + roi_start_y, 0), height_in);
1453 region_end_y = std::min(std::max(region_end_y + roi_start_y, 0), height_in);
1454
1455 // Iterate through each pixel in the pooling region
1456 if((region_end_x <= region_start_x) || (region_end_y <= region_start_y))
1457 {
1458 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = 0;
1459 }
1460 else
1461 {
1462 T curr_max = std::numeric_limits<T>::lowest();
1463 for(int j = region_start_y; j < region_end_y; ++j)
1464 {
1465 for(int i = region_start_x; i < region_end_x; ++i)
1466 {
1467 const auto val = in[batch_id * volume_in + fm * width_in * height_in + j * width_in + i];
1468 curr_max = std::max(val, curr_max);
1469 }
1470 }
1471 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = curr_max;
1472 }
1473 }
1474 }
1475 }
1476 }
1477}
1478
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001479// Softmax Layer
Pablo Tello383deec2017-06-23 10:40:05 +01001480template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001481void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1482{
1483 const int cols = static_cast<int>(in.shape()[0]);
1484 const int upper_dims = in.shape().total_size() / cols;
1485 for(int r = 0; r < upper_dims; ++r)
1486 {
1487 // Find max
1488 T max = std::numeric_limits<T>::lowest();
1489 for(int c = 0; c < cols; ++c)
1490 {
1491 const T x = in[r * cols + c];
1492 if(x > max)
1493 {
1494 max = x;
1495 }
1496 }
1497
1498 // Regularize
1499 T sum = 0;
1500 for(int c = 0; c < cols; ++c)
1501 {
1502 const T res = exp(in[r * cols + c] - max);
1503 out[r * cols + c] = res;
1504 sum += res;
1505 }
1506
1507 // Normalize
1508 const T norm_val = 1 / sum;
1509 for(int c = 0; c < cols; ++c)
1510 {
1511 out[r * cols + c] *= norm_val;
1512 }
1513 }
1514}
1515template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1516void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1517{
1518 using namespace fixed_point_arithmetic;
1519 using promoted_T = typename test::traits::promote<T>::type;
1520
1521 const int fixed_point_position = in.fixed_point_position();
1522 const int cols = static_cast<int>(in.shape()[0]);
1523 const int upper_dims = in.shape().total_size() / cols;
1524
1525 for(int r = 0; r < upper_dims; ++r)
1526 {
1527 // Find max
1528 fixed_point<T> max(std::numeric_limits<T>::lowest(), fixed_point_position, true);
1529 for(int c = 0; c < cols; ++c)
1530 {
1531 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1532 if(x > max)
1533 {
1534 max = x;
1535 }
1536 }
1537
1538 // Regularize
1539 fixed_point<promoted_T> sum(0, fixed_point_position);
1540 for(int c = 0; c < cols; ++c)
1541 {
1542 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1543 fixed_point<T> res = exp(x - max);
1544 out[r * cols + c] = res.raw();
1545 sum = add(sum, static_cast<fixed_point<promoted_T>>(res));
1546 }
1547
1548 // Normalize
1549 fixed_point<T> sat_sum(sum);
1550 for(int c = 0; c < cols; ++c)
1551 {
1552 const fixed_point<T> x(out[r * cols + c], fixed_point_position, true);
1553 out[r * cols + c] = div(x, sat_sum).raw();
1554 }
1555 }
1556}
1557
1558// Fixed point operations
1559template <typename T>
1560void fixed_point_operation(const Tensor<T> &in, Tensor<T> &out, FixedPointOp op)
1561{
1562 int p = in.fixed_point_position();
1563 switch(op)
1564 {
1565 case FixedPointOp::EXP:
1566 for(int i = 0; i < in.num_elements(); ++i)
1567 {
1568 out[i] = fixed_point_arithmetic::exp(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1569 }
1570 break;
1571 case FixedPointOp::LOG:
1572 for(int i = 0; i < in.num_elements(); ++i)
1573 {
1574 out[i] = fixed_point_arithmetic::log(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1575 }
1576 break;
1577 case FixedPointOp::INV_SQRT:
1578 for(int i = 0; i < in.num_elements(); ++i)
1579 {
1580 out[i] = fixed_point_arithmetic::inv_sqrt(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1581 }
1582 break;
1583 case FixedPointOp::RECIPROCAL:
1584 for(int i = 0; i < in.num_elements(); ++i)
1585 {
1586 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();
1587 }
1588 break;
1589 default:
1590 ARM_COMPUTE_ERROR("Fixed point operation not supported");
1591 break;
1592 }
1593}
1594
1595// Tensor print
1596template <typename T>
1597void print(const Tensor<T> &in, std::ostream &out)
1598{
1599 out << "\n";
1600 for(int i = 0; i < in.num_elements(); ++i)
1601 {
1602 out << in[i] << " ";
1603 }
1604 out << "\n";
1605}
1606} // namespace tensor_operations
1607} // namespace validation
1608} // namespace test
1609} // namespace arm_compute
1610
1611#endif /* __ARM_COMPUTE_TEST_TENSOR_OPERATIONS_H__ */