blob: 882c9e07e1c0288588573de94031622911059631 [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
47namespace arm_compute
48{
49namespace test
50{
51namespace validation
52{
53namespace tensor_operations
54{
55namespace
56{
Pablo Tello383deec2017-06-23 10:40:05 +010057template <class T>
58struct is_floating_point
59 : std::integral_constant < bool,
60 std::is_same<float, typename std::remove_cv<T>::type>::value ||
Anthony Barbierac69aa12017-07-03 17:39:37 +010061#ifdef ARM_COMPUTE_ENABLE_FP16
Pablo Tello383deec2017-06-23 10:40:05 +010062 std::is_same<float16_t, typename std::remove_cv<T>::type>::value ||
Anthony Barbierac69aa12017-07-03 17:39:37 +010063#endif /* ARM_COMPUTE_ENABLE_FP16 */
Pablo Tello383deec2017-06-23 10:40:05 +010064 std::is_same<double, typename std::remove_cv<T>::type>::value || std::is_same<long double, typename std::remove_cv<T>::type>::value >
65{
66};
67
Anthony Barbier6ff3b192017-09-04 18:44:23 +010068bool is_valid_pixel(int i, int min, int max)
69{
70 return (i >= min && i < max);
71}
72
73// 3D convolution for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +010074template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010075void 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)
76{
77 const int half_width_weights = width_weights / 2;
78 const int half_height_weights = height_weights / 2;
79
80 // Reset accumulator
81 T acc = static_cast<T>(0);
82
83 // Compute a 2D convolution for each IFM and accumulate the result
84 for(int ifm = 0; ifm < depth_in; ++ifm)
85 {
86 // Compute the offset for the input slice
87 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
88
89 // Compute 2D convolution
90 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
91 {
92 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
93 {
94 // Check if the pixel is out-of-bound
95 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
96 {
97 const int idx = xk + half_width_weights;
98 const int idy = yk + half_height_weights;
99
100 const T i_value = in[offset_slice_in + xk + yk * width_in];
101 const T w_value = weights[idx + idy * width_weights + ifm * width_weights * height_weights];
102
103 acc += i_value * w_value;
104 }
105 }
106 }
107 }
108
109 // Accumulate the bias and store the result
110 *out = acc + (*bias);
111}
112
113// 3D convolution for fixed point type
114template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
115void 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,
116 int8_t fixed_point_position)
117{
118 const int half_width_weights = width_weights / 2;
119 const int half_height_weights = height_weights / 2;
120
121 using namespace fixed_point_arithmetic;
122 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
123
124 // Reset accumulator
125 fixed_point<promoted_type> acc(0, fixed_point_position);
126
127 // Compute a 2D convolution for each IFM and accumulate the result
128 for(int ifm = 0; ifm < depth_in; ++ifm)
129 {
130 // Compute the offset for the input slice
131 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
132
133 // Compute 2D convolution
134 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
135 {
136 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
137 {
138 // Check if the pixel is out-of-bound
139 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
140 {
141 const int idx = xk + half_width_weights;
142 const int idy = yk + half_height_weights;
143
144 const fixed_point<promoted_type> i_value(in[offset_slice_in + xk + yk * width_in], fixed_point_position, true);
145 const fixed_point<promoted_type> w_value(weights[idx + idy * width_weights + ifm * width_weights * height_weights], fixed_point_position, true);
146 const fixed_point<promoted_type> iw = i_value * w_value;
147 acc = iw + acc;
148 }
149 }
150 }
151 }
152
153 // Get the bias
154 const fixed_point<promoted_type> b(*bias, fixed_point_position, true);
155
156 // Accumulate the bias and covert back
157 acc = acc + b;
158 fixed_point<T> res(acc);
159 *out = res.raw();
160}
161
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100162template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100163void 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)
164{
165 for(int x = 0; x < cols_weights; ++x)
166 {
167 T acc = 0.0f;
168 for(int y = 0; y < rows_weights; ++y)
169 {
170 acc += in[y] * weights[x + y * cols_weights];
171 }
172 out[x] = acc + bias[x];
173 }
174}
175
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100176// Vector matrix multiply for fixed point type
177template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
178void 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 +0100179{
180 using namespace fixed_point_arithmetic;
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100181 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100182
183 for(int x = 0; x < cols_weights; ++x)
184 {
185 // Reset accumulator
186 fixed_point<promoted_type> acc(0, fixed_point_position);
187
188 for(int y = 0; y < rows_weights; ++y)
189 {
190 const fixed_point<promoted_type> i_value(in[y], fixed_point_position, true);
191 const fixed_point<promoted_type> w_value(weights[x + y * cols_weights], fixed_point_position, true);
192 const fixed_point<promoted_type> iw = i_value * w_value;
193 acc = iw + acc;
194 }
195
196 // Get the bias
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100197 const fixed_point<T> b(bias[x], fixed_point_position, true);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100198
199 // Convert back and accumulate the bias
Gian Marco Iodice2bbd9642017-07-04 16:46:32 +0100200 fixed_point<T> res(acc);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100201 res = res + b;
202
203 // Store the result
204 out[x] = res.raw();
205 }
206}
207
SiCong Libacaf9a2017-06-19 13:41:45 +0100208// Return a tensor element at a specified coordinate with different border modes
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100209template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
210T tensor_elem_at(const Tensor<T> &in, Coordinates &coord, BorderMode border_mode, T constant_border_value)
211{
212 const int x = coord.x();
213 const int y = coord.y();
214 const int width = static_cast<int>(in.shape().x());
215 const int height = static_cast<int>(in.shape().y());
216
SiCong Libacaf9a2017-06-19 13:41:45 +0100217 // If coordinates beyond range of tensor's width or height
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100218 if(x < 0 || y < 0 || x >= width || y >= height)
219 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100220 if(border_mode == BorderMode::REPLICATE)
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100221 {
222 coord.set(0, std::max(0, std::min(x, width - 1)));
223 coord.set(1, std::max(0, std::min(y, height - 1)));
224 return in[coord2index(in.shape(), coord)];
225 }
226 else
227 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100228 return constant_border_value;
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100229 }
230 }
231 else
232 {
233 return in[coord2index(in.shape(), coord)];
234 }
235}
236
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100237/** Apply 2D spatial filter on a single element of @p in at coordinates @p coord
238 *
239 * - filter sizes have to be odd number
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100240 * - Row major order of filter assumed
241 * - TO_ZERO rounding policy assumed
242 * - SATURATE convert policy assumed
243 *
244 */
245template <typename T1, typename T2, typename T3>
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100246void 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,
247 T1 constant_border_value = 0)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100248{
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100249 double val = 0;
250 const int x = coord.x();
251 const int y = coord.y();
252 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 +0100253 {
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100254 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 +0100255 {
256 coord.set(0, i);
257 coord.set(1, j);
SiCong Libacaf9a2017-06-19 13:41:45 +0100258 val += static_cast<double>(*filter_itr) * tensor_elem_at(in, coord, border_mode, constant_border_value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100259 ++filter_itr;
260 }
261 }
262 coord.set(0, x);
263 coord.set(1, y);
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100264 const double rounded_val = support::cpp11::trunc(val * static_cast<double>(scale));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100265 out[coord2index(in.shape(), coord)] = saturate_cast<T3>(rounded_val);
266}
267} // namespace
268
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100269// Sobel 3x3
270template <typename T1, typename T2>
271void sobel_3x3(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
272{
273 const std::array<int8_t, 9> sobel_x{ { -1, 0, 1, -2, 0, 2, -1, 0, 1 } };
274 const std::array<int8_t, 9> sobel_y{ { -1, -2, -1, 0, 0, 0, 1, 2, 1 } };
275
276 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
277 {
278 const Coordinates id = index2coord(in.shape(), element_idx);
279
280 apply_2d_spatial_filter(id, in, out_x, TensorShape(3U, 3U), sobel_x.data(), 1.f, border_mode, constant_border_value);
281 apply_2d_spatial_filter(id, in, out_y, TensorShape(3U, 3U), sobel_y.data(), 1.f, border_mode, constant_border_value);
282 }
283}
284
285// Sobel 5x5
286template <typename T1, typename T2>
287void sobel_5x5(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
288{
289 const std::array<int8_t, 25> sobel_x{ {
290 -1, -2, 0, 2, 1,
291 -4, -8, 0, 8, 4,
292 -6, -12, 0, 12, 6,
293 -4, -8, 0, 8, 4,
294 -1, -2, 0, 2, 1
295 } };
296
297 const std::array<int8_t, 25> sobel_y{ {
298 -1, -4, -6, -4, -1,
299 -2, -8, -12, -8, -2,
300 0, 0, 0, 0, 0,
301 2, 8, 12, 8, 2,
302 1, 4, 6, 4, 1
303 } };
304
305 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
306 {
307 const Coordinates id = index2coord(in.shape(), element_idx);
308
309 apply_2d_spatial_filter(id, in, out_x, TensorShape(5U, 5U), sobel_x.data(), 1.f, border_mode, constant_border_value);
310 apply_2d_spatial_filter(id, in, out_y, TensorShape(5U, 5U), sobel_y.data(), 1.f, border_mode, constant_border_value);
311 }
312}
313
Giorgio Arenaf7959862017-06-13 15:19:51 +0100314// Mean Standard Deviation
315template <typename T1>
316void mean_and_standard_deviation(const Tensor<T1> &in, float &mean, float &std_dev)
317{
318 int num_elements = in.num_elements();
319
320 // Calculate mean
321 mean = 0.f;
322 for(int i = 0; i < num_elements; ++i)
323 {
324 mean += in[i];
325 }
326 mean /= num_elements;
327
328 // Calculate standard deviation
329 std_dev = 0.f;
330 for(int i = 0; i < num_elements; ++i)
331 {
332 std_dev += (mean - in[i]) * (mean - in[i]);
333 }
334 std_dev = sqrt(std_dev / num_elements);
335}
336
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100337// Integral Image
338void integral_image(const Tensor<uint8_t> &in, Tensor<uint32_t> &out)
339{
340 // Length of dimensions
341 const size_t width = in.shape().x();
342 const size_t height = in.shape().y();
343 const size_t depth = in.shape().z() * in.shape()[3] * in.shape()[4] * in.shape()[5];
344
345 const size_t image_size = width * height;
346
347 for(size_t z = 0; z < depth; ++z)
348 {
349 size_t current_image = z * image_size;
350
351 //First element of each image
352 out[current_image] = in[current_image];
353
354 // First row of each image (add only pixel on the left)
355 for(size_t x = 1; x < width; ++x)
356 {
357 out[current_image + x] = static_cast<uint32_t>(in[current_image + x]) + out[current_image + x - 1];
358 }
359
360 // Subsequent rows
361 for(size_t y = 1; y < height; ++y)
362 {
363 size_t current_row = current_image + (width * y);
364
365 // First element of each row (add only pixel up)
366 out[current_row] = static_cast<uint32_t>(in[current_row]) + out[current_row - width];
367
368 // Following row elements
369 for(size_t x = 1; x < width; ++x)
370 {
371 size_t current_pixel = current_row + x;
372
373 // out = in + up(out) + left(out) - up_left(out)
374 out[current_pixel] = static_cast<uint32_t>(in[current_pixel]) + out[current_pixel - 1]
375 + out[current_pixel - width] - out[current_pixel - width - 1];
376 }
377 }
378 }
379}
380
381// Absolute difference
382template <typename T1, typename T2, typename T3>
383void absolute_difference(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out)
384{
385 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
386
387 for(int i = 0; i < in1.num_elements(); ++i)
388 {
389 intermediate_type val = std::abs(static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]));
390 out[i] = saturate_cast<T3>(val);
391 }
392}
393
394// Accumulate
395template <typename T1, typename T2>
396void accumulate(const Tensor<T1> &in, Tensor<T2> &out)
397{
398 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
399
400 for(int i = 0; i < in.num_elements(); ++i)
401 {
402 intermediate_type val = static_cast<intermediate_type>(out[i]) + static_cast<intermediate_type>(in[i]);
403 out[i] = saturate_cast<T2>(val);
404 }
405}
406
407// Accumulate squared
408template <typename T1, typename T2>
409void accumulate_squared(const Tensor<T1> &in, Tensor<T2> &out, uint32_t shift)
410{
411 if(shift > 15)
412 {
413 ARM_COMPUTE_ERROR("Shift in accumulate_squared must be within the range [0, 15]");
414 }
415 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
416 intermediate_type denom = 1 << shift;
417
418 for(int i = 0; i < in.num_elements(); ++i)
419 {
420 intermediate_type val = static_cast<intermediate_type>(out[i]) + (static_cast<intermediate_type>(in[i]) * static_cast<intermediate_type>(in[i]) / denom);
421 out[i] = saturate_cast<T2>(val);
422 }
423}
424
425// Accumulate weighted
426template <typename T>
427void accumulate_weighted(const Tensor<T> &in, Tensor<T> &out, float alpha)
428{
429 if(alpha < 0.f || alpha > 1.f)
430 {
431 ARM_COMPUTE_ERROR("Weight (alpha) specified in accumulate_weighted must be within the range [0, 1]");
432 }
433 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
434
435 for(int i = 0; i < in.num_elements(); ++i)
436 {
437 double val = (1. - static_cast<double>(alpha)) * static_cast<intermediate_type>(out[i]) + static_cast<double>(alpha) * static_cast<intermediate_type>(in[i]);
438 out[i] = static_cast<T>(val);
439 }
440}
441
442// Arithmetic addition
443template <typename T1, typename T2, typename T3>
444void arithmetic_addition(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
445{
446 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
447
448 for(int i = 0; i < in1.num_elements(); ++i)
449 {
450 intermediate_type val = static_cast<intermediate_type>(in1[i]) + static_cast<intermediate_type>(in2[i]);
451 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
452 }
453}
454
455// Arithmetic Subtraction
456template <typename T1, typename T2, typename T3>
457void arithmetic_subtraction(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
458{
459 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
460
461 for(int i = 0; i < in1.num_elements(); ++i)
462 {
463 intermediate_type val = static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]);
464 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
465 }
466}
467
468// Bitwise and
469template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
470void bitwise_and(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
471{
472 for(int i = 0; i < in1.num_elements(); ++i)
473 {
474 out[i] = in1[i] & in2[i];
475 }
476}
477
478// Bitwise or
479template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
480void bitwise_or(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
481{
482 for(int i = 0; i < in1.num_elements(); ++i)
483 {
484 out[i] = in1[i] | in2[i];
485 }
486}
487
488// Bitwise xor
489template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
490void bitwise_xor(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
491{
492 for(int i = 0; i < in1.num_elements(); ++i)
493 {
494 out[i] = in1[i] ^ in2[i];
495 }
496}
497
498// Bitwise not
499template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
500void bitwise_not(const Tensor<T> &in, Tensor<T> &out)
501{
502 for(int i = 0; i < in.num_elements(); ++i)
503 {
504 out[i] = ~in[i];
505 }
506}
507
SiCong Libacaf9a2017-06-19 13:41:45 +0100508// Box3x3 filter
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100509template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
SiCong Libacaf9a2017-06-19 13:41:45 +0100510void box3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100511{
512 const std::array<T, 9> filter{ { 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
SiCong Libacaf9a2017-06-19 13:41:45 +0100513 float scale = 1.f / static_cast<float>(filter.size());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100514 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
515 {
516 const Coordinates id = index2coord(in.shape(), element_idx);
SiCong Libacaf9a2017-06-19 13:41:45 +0100517 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 +0100518 }
519}
520
521// Depth conversion
Georgios Pinitase2229412017-07-12 12:30:40 +0100522template < 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 +0100523void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
524{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100525 using namespace fixed_point_arithmetic;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100526
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100527 const int fixed_point_position = in.fixed_point_position();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100528 for(int i = 0; i < in.num_elements(); ++i)
529 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100530 out[i] = static_cast<float>(fixed_point<T1>(in[i], fixed_point_position, true));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100531 }
532}
533
Georgios Pinitase2229412017-07-12 12:30:40 +0100534template < typename T1, typename T2, typename std::enable_if < std::is_floating_point<T1>::value &&std::is_integral<T2>::value, int >::type = 0 >
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100535void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100536{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100537 using namespace fixed_point_arithmetic;
538
539 const int fixed_point_position = out.fixed_point_position();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100540 for(int i = 0; i < in.num_elements(); ++i)
541 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100542 out[i] = fixed_point<T2>(in[i], fixed_point_position).raw();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100543 }
544}
545
Georgios Pinitase2229412017-07-12 12:30:40 +0100546template < 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 +0100547void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100548{
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100549 // Up-casting
550 if(std::numeric_limits<T1>::digits <= std::numeric_limits<T2>::digits)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100551 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100552 for(int i = 0; i < in.num_elements(); ++i)
553 {
554 out[i] = static_cast<T2>(in[i]) << shift;
555 }
556 }
557 // Down-casting
558 else
559 {
560 for(int i = 0; i < in.num_elements(); ++i)
561 {
562 T1 val = in[i] >> shift;
563 out[i] = ((policy == ConvertPolicy::SATURATE) ? saturate_cast<T2>(val) : static_cast<T2>(val));
564 }
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100565 }
566}
567
Georgios Pinitase2229412017-07-12 12:30:40 +0100568template < 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 >
569void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
570{
571 using namespace fixed_point_arithmetic;
572 bool is_in_place = (&in == &out);
573
574 const int fixed_point_position_in = in.fixed_point_position();
575 const int fixed_point_position_out = (is_in_place) ? static_cast<int>(shift) : out.fixed_point_position();
576
577 if(!is_in_place || (fixed_point_position_in != fixed_point_position_out))
578 {
579 for(int i = 0; i < in.num_elements(); ++i)
580 {
581 auto x = fixed_point<T2>(in[i], fixed_point_position_in, true);
582 x.rescale(fixed_point_position_out);
583 out[i] = x.raw();
584 }
585 }
586}
587
Pablo Tello331fc742017-07-06 11:47:06 +0100588template < 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 +0100589void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100590{
591 for(int i = 0; i < in.num_elements(); ++i)
592 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100593 out[i] = static_cast<T2>(in[i]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100594 }
595}
596
SiCong Li5a536642017-06-19 14:47:05 +0100597// Gaussian3x3 filter
598template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
599void gaussian3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
600{
601 const std::array<T, 9> filter{ { 1, 2, 1, 2, 4, 2, 1, 2, 1 } };
602 const float scale = 1.f / 16.f;
603 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
604 {
605 const Coordinates id = index2coord(in.shape(), element_idx);
606 apply_2d_spatial_filter(id, in, out, TensorShape(3U, 3U), filter.data(), scale, border_mode, constant_border_value);
607 }
608}
609
SiCong Li3eb263e2017-06-19 15:31:43 +0100610// Gaussian5x5 filter
611template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
612void gaussian5x5(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
613{
614 const std::array<T, 25> filter{ {
615 1, 4, 6, 4, 1,
616 4, 16, 24, 16, 4,
617 6, 24, 36, 24, 6,
618 4, 16, 24, 16, 4,
619 1, 4, 6, 4, 1
620 } };
621 const float scale = 1.f / 256.f;
622 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
623 {
624 const Coordinates id = index2coord(in.shape(), element_idx);
625 apply_2d_spatial_filter(id, in, out, TensorShape(5U, 5U), filter.data(), scale, border_mode, constant_border_value);
626 }
627}
628
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100629// Matrix multiplication for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100630template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100631void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
632{
633 const int M = out.shape().y();
634 const int N = out.shape().x();
635 const int K = in1.shape().x();
636
637 for(int r = 0; r < M; ++r)
638 {
639 for(int c = 0; c < N; ++c)
640 {
641 T acc = 0.0f;
642
643 for(int k = 0; k < K; ++k)
644 {
645 const T a0 = in1[r * K + k];
646 const T b0 = in2[k * N + c];
647
648 acc += a0 * b0;
649 }
650
651 // Finalize the result: A * B * alpha + C * beta
652 const T c0 = in3[c + r * N];
653 out[c + r * N] = alpha * acc + beta * c0;
654 }
655 }
656}
657
658// Matrix multiplication for fixed point type
659template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
660void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
661{
662 using namespace fixed_point_arithmetic;
663
664 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
665
666 const int M = out.shape().y();
667 const int N = out.shape().x();
668 const int K = in1.shape().x();
669 const int8_t fixed_point_position = static_cast<int8_t>(in1.fixed_point_position());
670
671 const fixed_point<T> alpha_q(alpha, fixed_point_position);
672 const fixed_point<T> beta_q(beta, fixed_point_position);
673
674 for(int r = 0; r < M; ++r)
675 {
676 for(int c = 0; c < N; ++c)
677 {
678 fixed_point<promoted_type> acc_q(0, fixed_point_position);
679
680 for(int k = 0; k < K; ++k)
681 {
682 const fixed_point<promoted_type> a0_q(in1[r * K + k], fixed_point_position, true);
683 const fixed_point<promoted_type> b0_q(in2[k * N + c], fixed_point_position, true);
684 const fixed_point<promoted_type> axb_q = a0_q * b0_q;
685
686 acc_q = axb_q + acc_q;
687 }
688
689 // Finalize the result: A * B * alpha + C * beta
690 const fixed_point<T> c0_q(in3[c + r * N], fixed_point_position, true);
691
692 fixed_point<T> res_q(acc_q);
693 res_q = alpha_q * res_q;
694 res_q = (c0_q * beta_q) + res_q;
695
696 // Store the result
697 out[c + r * N] = res_q.raw();
698 }
699 }
700}
701
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100702// Non linear filter
703template <typename T>
704void non_linear_filter(const Tensor<T> &in, Tensor<T> &out, NonLinearFilterFunction function, unsigned int mask_size,
705 MatrixPattern pattern, const uint8_t *mask, BorderMode border_mode, uint8_t constant_border_value)
706{
SiCong Li7a035752017-06-28 15:27:02 +0100707 ARM_COMPUTE_ERROR_ON(pattern == MatrixPattern::OTHER && mask == nullptr);
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100708
709 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
710
711 const int sq_mask_size = mask_size * mask_size;
712 const int half_mask_size = mask_size / 2;
713 std::vector<intermediate_type> vals(sq_mask_size);
714 intermediate_type current_value = 0;
715
SiCong Li7a035752017-06-28 15:27:02 +0100716 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 +0100717
718 for(int element_idx = 0, count = 0, index = 0; element_idx < in.num_elements(); ++element_idx, count = 0, index = 0)
719 {
720 Coordinates id = index2coord(in.shape(), element_idx);
721 if(is_in_valid_region(valid_region, id))
722 {
723 int idx = id.x();
724 int idy = id.y();
725 for(int y = idy - half_mask_size; y <= idy + half_mask_size; ++y)
726 {
727 for(int x = idx - half_mask_size; x <= idx + half_mask_size; ++x, ++index)
728 {
729 id.set(0, x);
730 id.set(1, y);
731 current_value = tensor_elem_at(in, id, border_mode, constant_border_value);
732
733 if(mask[index] == 255)
734 {
735 vals[count] = static_cast<intermediate_type>(current_value);
736 ++count;
737 }
738 }
739 }
740 std::sort(vals.begin(), vals.begin() + count);
741 switch(function)
742 {
743 case NonLinearFilterFunction::MIN:
744 out[element_idx] = saturate_cast<T>(vals[0]);
745 break;
746 case NonLinearFilterFunction::MAX:
747 out[element_idx] = saturate_cast<T>(vals[count - 1]);
748 break;
749 case NonLinearFilterFunction::MEDIAN:
750 out[element_idx] = saturate_cast<T>(vals[count / 2]);
751 break;
752 default:
753 ARM_COMPUTE_ERROR("Unsupported NonLinearFilter function.");
754 }
755 }
756 }
757}
758
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100759// Pixel-wise multiplication
760template <typename T1, typename T2, typename T3>
761void pixel_wise_multiplication(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, float scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
762{
763 if(scale < 0)
764 {
765 ARM_COMPUTE_ERROR("Scale of pixel-wise multiplication must be non-negative");
766 }
767 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
768 for(int i = 0; i < in1.num_elements(); ++i)
769 {
770 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 +0100771 if(is_floating_point<T3>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100772 {
773 out[i] = val;
774 }
775 else
776 {
777 double rounded_val = 0;
778 switch(rounding_policy)
779 {
780 case(RoundingPolicy::TO_ZERO):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100781 rounded_val = support::cpp11::trunc(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100782 break;
783 case(RoundingPolicy::TO_NEAREST_UP):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100784 rounded_val = round_half_up(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100785 break;
786 case(RoundingPolicy::TO_NEAREST_EVEN):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100787 rounded_val = round_half_even(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100788 break;
789 default:
790 ARM_COMPUTE_ERROR("Unsupported rounding policy");
791 }
792 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(rounded_val) : static_cast<T3>(rounded_val);
793 }
794 }
795}
796
797// Fixed-point Pixel-wise Multiplication
798template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
799void fixed_point_pixel_wise_multiplication(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out, int scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
800{
801 using namespace fixed_point_arithmetic;
802
803 const int fixed_point_position = in1.fixed_point_position();
804
805 ARM_COMPUTE_ERROR_ON_MSG(in1.data_type() != in2.data_type() || in1.data_type() != out.data_type(),
806 "Tensors must all have the same DataType");
807 ARM_COMPUTE_ERROR_ON_MSG(fixed_point_position != in2.fixed_point_position() || fixed_point_position != out.fixed_point_position(),
808 "Fixed-point position must be the same for both inputs and outputs");
809
810 // Validate fixed_point_position
811 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS8) && (fixed_point_position == 0 || fixed_point_position > 7));
812 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS16) && (fixed_point_position == 0 || fixed_point_position > 15));
813
814 fixed_point<T> fp_scale(scale, fixed_point_position);
815 const bool is_sat = convert_policy == ConvertPolicy::SATURATE;
816 const bool do_scaling = scale != 1;
817
818 for(int i = 0; i < in1.num_elements(); ++i)
819 {
820 fixed_point<T> val1(in1[i], fixed_point_position, true);
821 fixed_point<T> val2(in2[i], fixed_point_position, true);
822 fixed_point<T> res = (is_sat) ? val1 * val2 : mul<OverflowPolicy::WRAP>(val1, val2);
823 if(do_scaling)
824 {
825 res = (is_sat) ? res * fp_scale : mul<OverflowPolicy::WRAP>(res, fp_scale);
826 }
827 out[i] = res.raw();
828 }
829}
830
Isabella Gottardib797fa22017-06-23 15:02:11 +0100831//Table Lookup
832template <typename T, typename T1>
833void table_lookup(const Tensor<T> &in, Tensor<T> &out, std::map<T1, T1> &lut)
834{
835 for(int i = 0; i < in.num_elements(); ++i)
836 {
837 out[i] = static_cast<T>(lut[in[i]]);
838 }
839}
840
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100841// Threshold
842template <typename T>
843void threshold(const Tensor<T> &in, Tensor<T> &out, uint8_t threshold, uint8_t false_value, uint8_t true_value, ThresholdType type, uint8_t upper)
844{
845 switch(type)
846 {
847 case ThresholdType::BINARY:
848 for(int i = 0; i < in.num_elements(); ++i)
849 {
850 out[i] = ((in[i] > threshold) ? true_value : false_value);
851 }
852 break;
853 case ThresholdType::RANGE:
854 for(int i = 0; i < in.num_elements(); ++i)
855 {
856 if(in[i] > upper)
857 {
858 out[i] = false_value;
859 }
860 else if(in[i] < threshold)
861 {
862 out[i] = false_value;
863 }
864 else
865 {
866 out[i] = true_value;
867 }
868 }
869 break;
870 default:
871 ARM_COMPUTE_ERROR("Thresholding type not recognised");
872 break;
873 }
874}
875
876// Activation Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100877template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100878void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
879{
880 const T a = static_cast<T>(act_info.a());
881 const T b = static_cast<T>(act_info.b());
882
883 for(int i = 0; i < in.num_elements(); ++i)
884 {
885 T x = in[i];
886 switch(act_info.activation())
887 {
888 case ActivationLayerInfo::ActivationFunction::ABS:
889 out[i] = std::abs(x);
890 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100891 case ActivationLayerInfo::ActivationFunction::LINEAR:
892 out[i] = a * x + b;
893 break;
894 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
895 out[i] = static_cast<T>(1) / (static_cast<T>(1) + std::exp(-x));
896 break;
897 case ActivationLayerInfo::ActivationFunction::RELU:
898 out[i] = std::max<T>(0, x);
899 break;
Georgios Pinitas579c0492017-07-12 16:12:12 +0100900 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
901 out[i] = std::min<T>(a, std::max<T>(0, x));
902 break;
903 case ActivationLayerInfo::ActivationFunction::LEAKY_RELU:
904 out[i] = (x > 0) ? x : a * x;
905 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100906 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
907 out[i] = std::log(static_cast<T>(1) + std::exp(x));
908 break;
909 case ActivationLayerInfo::ActivationFunction::SQRT:
910 out[i] = std::sqrt(x);
911 break;
912 case ActivationLayerInfo::ActivationFunction::SQUARE:
913 out[i] = x * x;
914 break;
915 case ActivationLayerInfo::ActivationFunction::TANH:
916 out[i] = a * std::tanh(b * x);
917 break;
918 default:
919 ARM_COMPUTE_ERROR("Activation function not recognised");
920 break;
921 }
922 }
923}
924
925// Activation Layer for fixed point type
926template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
927void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
928{
929 using namespace fixed_point_arithmetic;
930 int fixed_point_position = in.fixed_point_position();
931 ActivationLayerInfo::ActivationFunction act_func = act_info.activation();
932 const fixed_point<T> a(act_info.a(), fixed_point_position);
933 const fixed_point<T> b(act_info.b(), fixed_point_position);
934 const fixed_point<T> const_0(0, fixed_point_position);
935 const fixed_point<T> const_1(1, fixed_point_position);
936
937 for(int i = 0; i < in.num_elements(); ++i)
938 {
939 fixed_point<T> x(in[i], fixed_point_position, true);
940 switch(act_func)
941 {
942 case ActivationLayerInfo::ActivationFunction::ABS:
943 out[i] = abs(x).raw();
944 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100945 case ActivationLayerInfo::ActivationFunction::LINEAR:
946 out[i] = add(b, mul(a, x)).raw();
947 break;
948 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
949 out[i] = (const_1 / (const_1 + exp(-x))).raw();
950 break;
951 case ActivationLayerInfo::ActivationFunction::RELU:
952 out[i] = max(const_0, x).raw();
953 break;
Georgios Pinitas579c0492017-07-12 16:12:12 +0100954 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
955 out[i] = min(a, max(const_0, x)).raw();
956 break;
957 case ActivationLayerInfo::ActivationFunction::LEAKY_RELU:
958 out[i] = (x > const_0) ? x.raw() : mul(a, x).raw();
959 break;
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100960 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
961 out[i] = log(const_1 + exp(x)).raw();
962 break;
963 case ActivationLayerInfo::ActivationFunction::SQRT:
964 out[i] = (const_1 / inv_sqrt(x)).raw();
965 break;
966 case ActivationLayerInfo::ActivationFunction::SQUARE:
967 out[i] = mul(x, x).raw();
968 break;
969 case ActivationLayerInfo::ActivationFunction::TANH:
Georgios Pinitasccc65d42017-06-27 17:39:11 +0100970 out[i] = mul(a, tanh(mul(b, x))).raw();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100971 break;
972 default:
973 ARM_COMPUTE_ERROR("Activation function not recognised");
974 break;
975 }
976 }
977}
978
979// Batch Normalization Layer for fixed point type
980template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
981void 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)
982{
983 const int cols = static_cast<int>(in.shape()[0]);
984 const int rows = static_cast<int>(in.shape()[1]);
985 const int depth = static_cast<int>(in.shape()[2]);
986 int upper_dims = in.shape().total_size() / (cols * rows * depth);
987
988 for(int r = 0; r < upper_dims; ++r)
989 {
990 for(int i = 0; i < depth; ++i)
991 {
992 for(int k = 0; k < rows; ++k)
993 {
994 for(int l = 0; l < cols; ++l)
995 {
996 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
Michalis Spyrou172e5702017-06-26 14:18:47 +0100997 fixed_point_arithmetic::fixed_point<T> in_qs(in[pos], fixed_point_position, true);
998 fixed_point_arithmetic::fixed_point<T> var_qs(var[i], fixed_point_position, true);
999 fixed_point_arithmetic::fixed_point<T> mean_qs(mean[i], fixed_point_position, true);
1000 fixed_point_arithmetic::fixed_point<T> beta_qs(beta[i], fixed_point_position, true);
1001 fixed_point_arithmetic::fixed_point<T> gamma_qs(gamma[i], fixed_point_position, true);
1002 fixed_point_arithmetic::fixed_point<T> epsilon_qs(epsilon, fixed_point_position);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001003
Michalis Spyrou172e5702017-06-26 14:18:47 +01001004 auto denominator = fixed_point_arithmetic::inv_sqrt(var_qs + epsilon_qs);
1005 auto numerator = in_qs - mean_qs;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001006 auto x_bar = numerator * denominator;
Michalis Spyrou172e5702017-06-26 14:18:47 +01001007 x_bar = beta_qs + x_bar * gamma_qs;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001008 out[pos] = x_bar.raw();
1009 }
1010 }
1011 }
1012 }
1013}
1014
1015// Batch Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001016template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001017void 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)
1018{
1019 const int cols = static_cast<int>(in.shape()[0]);
1020 const int rows = static_cast<int>(in.shape()[1]);
1021 const int depth = static_cast<int>(in.shape()[2]);
1022 int upper_dims = in.shape().total_size() / (cols * rows * depth);
1023
1024 for(int r = 0; r < upper_dims; ++r)
1025 {
1026 for(int i = 0; i < depth; ++i)
1027 {
1028 for(int k = 0; k < rows; ++k)
1029 {
1030 for(int l = 0; l < cols; ++l)
1031 {
1032 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
1033 const float denominator = sqrt(var[i] + epsilon);
1034 const float numerator = in[pos] - mean[i];
1035 const float x_bar = numerator / denominator;
1036 out[pos] = beta[i] + x_bar * gamma[i];
1037 }
1038 }
1039 }
1040 }
1041}
1042
Georgios Pinitasac4e8732017-07-05 17:02:25 +01001043// Depth Concatenate layer
1044template <typename T>
1045void depth_concatenate_layer(const std::vector<const Tensor<T> *> &srcs, Tensor<T> &out)
1046{
1047 unsigned depth_offset = 0;
1048 const int width_out = out.shape().x();
1049 const int height_out = out.shape().y();
1050 const int depth_out = out.shape().z();
1051 const int out_stride_z = width_out * height_out;
1052 const int batches = out.shape().total_size_upper(3);
1053
1054 // Set output tensor to 0
1055 memset(out.data(), 0, out.num_elements() * element_size_from_data_type(out.data_type()));
1056
1057 for(unsigned int i = 0; i < srcs.size(); ++i)
1058 {
1059 ARM_COMPUTE_ERROR_ON(srcs[i] == nullptr);
1060 ARM_COMPUTE_ERROR_ON(srcs[i]->data_type() != out.data_type());
1061 ARM_COMPUTE_ERROR_ON(depth_offset >= out.shape().z());
1062 ARM_COMPUTE_ERROR_ON(batches != static_cast<int>(srcs[i]->shape().total_size_upper(3)));
1063
1064 const Tensor<T> *src = srcs[i];
1065 const int width = src->shape().x();
1066 const int height = src->shape().y();
1067 const int depth = src->shape().z();
1068 const unsigned int x_diff = (width_out - width) / 2;
1069 const unsigned int y_diff = (height_out - height) / 2;
1070
1071 const T *src_ptr = src->data();
1072 for(int b = 0; b < batches; ++b)
1073 {
1074 const unsigned int offset_to_first_element = b * out_stride_z * depth_out + depth_offset * out_stride_z
1075 + y_diff * width_out + x_diff;
1076 for(int d = 0; d < depth; ++d)
1077 {
1078 for(int r = 0; r < height; ++r)
1079 {
1080 std::copy(src_ptr, src_ptr + width, out.data() + offset_to_first_element + d * out_stride_z + r * width_out);
1081 src_ptr += width;
1082 }
1083 }
1084 }
1085
1086 depth_offset += depth;
1087 }
1088}
1089
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001090// Convolution layer
1091template <typename T>
1092void convolution_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out, const PadStrideInfo &conv_info)
1093{
1094 const int width_in = in.shape().x();
1095 const int height_in = in.shape().y();
1096 const int depth_in = in.shape().z();
1097 const int width_out = out.shape().x();
1098 const int height_out = out.shape().y();
1099 const int depth_out = out.shape().z();
1100 const int width_weights = weights.shape().x();
1101 const int height_weights = weights.shape().y();
1102 const int depth_weights = weights.shape().z();
1103 const int pad_xi = std::min(static_cast<int>(conv_info.pad().first), width_weights / 2);
1104 const int pad_yi = std::min(static_cast<int>(conv_info.pad().second), height_weights / 2);
1105 const int start_xi = width_weights / 2 - pad_xi;
1106 const int start_yi = height_weights / 2 - pad_yi;
1107 const int end_xi = width_in - start_xi;
1108 const int end_yi = height_in - start_yi;
1109 const int stride_xi = conv_info.stride().first;
1110 const int stride_yi = conv_info.stride().second;
1111 const int num_batches = in.shape().total_size() / (width_in * height_in * depth_in);
1112
1113 for(int r = 0; r < num_batches; ++r)
1114 {
1115 for(int yi = start_yi; yi < end_yi; yi += stride_yi)
1116 {
1117 for(int xi = start_xi; xi < end_xi; xi += stride_xi)
1118 {
1119 for(int ofm = 0; ofm < depth_out; ++ofm)
1120 {
1121 // Compute input and output offsets
1122 const int offset_in = r * width_in * height_in * depth_in;
1123 const int xo = (xi - start_xi) / stride_xi;
1124 const int yo = (yi - start_yi) / stride_yi;
1125 const int offset_out = xo + yo * width_out + ofm * width_out * height_out + r * width_out * height_out * depth_out;
1126
1127 // Compute 3D convolution
1128 convolution3d(in.data() + offset_in,
1129 weights.data() + ofm * width_weights * height_weights * depth_weights,
1130 bias.data() + ofm,
1131 out.data() + offset_out,
1132 xi, yi,
1133 width_in, height_in, depth_in,
1134 width_weights, height_weights,
1135 static_cast<int8_t>(in.fixed_point_position()));
1136 }
1137 }
1138 }
1139 }
1140}
1141
1142// Fully connected layer
1143template <typename T>
1144void fully_connected_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out)
1145{
1146 ARM_COMPUTE_ERROR_ON(weights.shape().x() != out.shape().x());
1147 ARM_COMPUTE_ERROR_ON(weights.shape().y() != in.shape().x() * in.shape().y() * in.shape().z());
1148 const int cols_weights = weights.shape().x();
1149 const int rows_weights = weights.shape().y();
1150 const int num_batches = in.shape().total_size() / rows_weights;
1151
1152 for(int k = 0; k < num_batches; ++k)
1153 {
1154 vector_matrix_multiply<T>(in.data() + k * rows_weights,
1155 weights.data(),
1156 bias.data(),
1157 out.data() + k * cols_weights,
1158 cols_weights,
1159 rows_weights,
1160 in.fixed_point_position());
1161 }
1162}
1163
1164// Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001165template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001166void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1167{
1168 const uint32_t norm_size = norm_info.norm_size();
1169 NormType type = norm_info.type();
1170 float beta = norm_info.beta();
1171 uint32_t kappa = norm_info.kappa();
1172
1173 const int cols = static_cast<int>(in.shape()[0]);
1174 const int rows = static_cast<int>(in.shape()[1]);
1175 const int depth = static_cast<int>(in.shape()[2]);
1176 int upper_dims = in.shape().total_size() / (cols * rows);
1177
1178 float coeff = norm_info.scale_coeff();
1179 int radius_cols = norm_size / 2;
1180 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1181 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1182
1183 if(type == NormType::CROSS_MAP)
1184 {
1185 // Remove also depth from upper dimensions since it is the axes we want
1186 // to use for normalization
1187 upper_dims /= depth;
1188 for(int r = 0; r < upper_dims; ++r)
1189 {
1190 for(int i = 0; i < rows; ++i)
1191 {
1192 for(int k = 0; k < cols; ++k)
1193 {
1194 for(int l = 0; l < depth; ++l)
1195 {
1196 float accumulated_scale = 0.f;
1197 for(int j = -radius_cols; j <= radius_cols; ++j)
1198 {
1199 const int z = l + j;
1200 if(z >= 0 && z < depth)
1201 {
1202 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1203 accumulated_scale += value * value;
1204 }
1205 }
1206 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = kappa + accumulated_scale * coeff;
1207 }
1208 }
1209 }
1210 }
1211 }
1212 else
1213 {
1214 for(int r = 0; r < upper_dims; ++r)
1215 {
1216 for(int i = 0; i < rows; ++i)
1217 {
1218 for(int k = 0; k < cols; ++k)
1219 {
1220 float accumulated_scale = 0.f;
1221 for(int j = -radius_rows; j <= radius_rows; ++j)
1222 {
1223 const int y = i + j;
1224 for(int l = -radius_cols; l <= radius_cols; ++l)
1225 {
1226 const int x = k + l;
1227 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1228 {
1229 const T value = in[x + y * cols + r * cols * rows];
1230 accumulated_scale += value * value;
1231 }
1232 }
1233 }
1234 out[k + i * cols + r * cols * rows] = kappa + accumulated_scale * coeff;
1235 }
1236 }
1237 }
1238 }
1239
1240 if(beta == 1.f)
1241 {
1242 for(int i = 0; i < out.num_elements(); ++i)
1243 {
1244 out[i] = in[i] / out[i];
1245 }
1246 }
1247 else if(beta == 0.5f)
1248 {
1249 for(int i = 0; i < out.num_elements(); ++i)
1250 {
1251 out[i] = in[i] / std::sqrt(out[i]);
1252 }
1253 }
1254 else
1255 {
1256 for(int i = 0; i < out.num_elements(); ++i)
1257 {
1258 out[i] = in[i] * std::exp(std::log(out[i]) * -beta);
1259 }
1260 }
1261}
1262// Normalization Layer for fixed-point types
1263template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1264void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1265{
1266 using namespace fixed_point_arithmetic;
1267
1268 const int fixed_point_position = in.fixed_point_position();
1269
1270 const uint32_t norm_size = norm_info.norm_size();
1271 NormType type = norm_info.type();
1272 fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1273 fixed_point<T> kappa(norm_info.kappa(), fixed_point_position);
1274
1275 const int cols = static_cast<int>(in.shape()[0]);
1276 const int rows = static_cast<int>(in.shape()[1]);
1277 const int depth = static_cast<int>(in.shape()[2]);
1278 int upper_dims = in.shape().total_size() / (cols * rows);
1279
1280 fixed_point<T> coeff(norm_info.scale_coeff(), fixed_point_position);
1281 int radius_cols = norm_size / 2;
1282 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1283 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1284
1285 if(type == NormType::CROSS_MAP)
1286 {
1287 // Remove also depth from upper dimensions since it is the axes we want
1288 // to use for normalization
1289 upper_dims /= depth;
1290 for(int r = 0; r < upper_dims; ++r)
1291 {
1292 for(int i = 0; i < rows; ++i)
1293 {
1294 for(int k = 0; k < cols; ++k)
1295 {
1296 for(int l = 0; l < depth; ++l)
1297 {
1298 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1299 for(int j = -radius_cols; j <= radius_cols; ++j)
1300 {
1301 const int z = l + j;
1302 if(z >= 0 && z < depth)
1303 {
1304 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1305 const fixed_point<T> fp_value(value, fixed_point_position, true);
1306 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1307 }
1308 }
1309 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1310 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = accumulated_scale.raw();
1311 }
1312 }
1313 }
1314 }
1315 }
1316 else
1317 {
1318 for(int r = 0; r < upper_dims; ++r)
1319 {
1320 for(int i = 0; i < rows; ++i)
1321 {
1322 for(int k = 0; k < cols; ++k)
1323 {
1324 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1325 for(int j = -radius_rows; j <= radius_rows; ++j)
1326 {
1327 const int y = i + j;
1328 for(int l = -radius_cols; l <= radius_cols; ++l)
1329 {
1330 const int x = k + l;
1331 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1332 {
1333 const T value = in[x + y * cols + r * cols * rows];
1334 const fixed_point<T> fp_value(value, fixed_point_position, true);
1335 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1336 }
1337 }
1338 }
1339 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1340 out[k + i * cols + r * cols * rows] = accumulated_scale.raw();
1341 }
1342 }
1343 }
1344 }
1345
1346 if(norm_info.beta() == 1.f)
1347 {
1348 for(int i = 0; i < out.num_elements(); ++i)
1349 {
1350 fixed_point<T> res = div(fixed_point<T>(in[i], fixed_point_position, true), fixed_point<T>(out[i], fixed_point_position, true));
1351 out[i] = res.raw();
1352 }
1353 }
1354 else
1355 {
1356 const fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1357 for(int i = 0; i < out.num_elements(); ++i)
1358 {
1359 fixed_point<T> res = pow(fixed_point<T>(out[i], fixed_point_position, true), beta);
1360 res = div(fixed_point<T>(in[i], fixed_point_position, true), res);
1361 out[i] = res.raw();
1362 }
1363 }
1364}
1365
1366// Pooling layer
1367template <typename T>
1368void pooling_layer(const Tensor<T> &in, Tensor<T> &out, PoolingLayerInfo pool_info, int fixed_point_position)
1369{
1370 const int pool_size = pool_info.pool_size();
1371 PoolingType type = pool_info.pool_type();
1372 int pool_stride_x = 0;
1373 int pool_stride_y = 0;
1374 int pad_x = 0;
1375 int pad_y = 0;
1376 std::tie(pool_stride_x, pool_stride_y) = pool_info.pad_stride_info().stride();
1377 std::tie(pad_x, pad_y) = pool_info.pad_stride_info().pad();
1378
Georgios Pinitasce093142017-06-19 16:11:53 +01001379 const int w_in = static_cast<int>(in.shape()[0]);
1380 const int h_in = static_cast<int>(in.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001381
Georgios Pinitasce093142017-06-19 16:11:53 +01001382 const int w_out = static_cast<int>(out.shape()[0]);
1383 const int h_out = static_cast<int>(out.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001384
Georgios Pinitasce093142017-06-19 16:11:53 +01001385 int upper_dims = in.shape().total_size() / (w_in * h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001386
Georgios Pinitasce093142017-06-19 16:11:53 +01001387 int pooled_w = 0;
1388 int pooled_h = 0;
1389 if(pool_info.pad_stride_info().round() == DimensionRoundingType::CEIL)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001390 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001391 pooled_w = static_cast<int>(ceil(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1392 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 +01001393 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001394 else
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001395 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001396 pooled_w = static_cast<int>(floor(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1397 pooled_h = static_cast<int>(floor(static_cast<float>(h_in + 2 * pad_y - pool_size) / pool_stride_y)) + 1;
1398 }
1399
1400 if((pooled_w - 1) * pool_stride_x >= w_in + pad_x)
1401 {
1402 --pooled_w;
1403 }
1404 if((pooled_h - 1) * pool_stride_y >= h_in + pad_y)
1405 {
1406 --pooled_h;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001407 }
1408
1409 if(type == PoolingType::MAX)
1410 {
1411 for(int r = 0; r < upper_dims; ++r)
1412 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001413 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001414 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001415 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001416 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001417 int wstart = w * pool_stride_x - pad_x;
1418 int hstart = h * pool_stride_y - pad_y;
1419 int wend = std::min(wstart + pool_size, w_in);
1420 int hend = std::min(hstart + pool_size, h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001421 wstart = std::max(wstart, 0);
Georgios Pinitasce093142017-06-19 16:11:53 +01001422 hstart = std::max(hstart, 0);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001423
1424 T max_val = std::numeric_limits<T>::lowest();
1425 for(int y = hstart; y < hend; ++y)
1426 {
1427 for(int x = wstart; x < wend; ++x)
1428 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001429 T val = in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001430 if(val > max_val)
1431 {
1432 max_val = val;
1433 }
1434 }
1435 }
1436
Georgios Pinitasce093142017-06-19 16:11:53 +01001437 out[r * h_out * w_out + h * pooled_w + w] = max_val;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001438 }
1439 }
1440 }
1441 }
1442 else // Average pooling
1443 {
1444 for(int r = 0; r < upper_dims; ++r)
1445 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001446 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001447 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001448 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001449 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001450 T avg_val = 0;
1451 int wstart = w * pool_stride_x - pad_x;
1452 int hstart = h * pool_stride_y - pad_y;
1453 int wend = std::min(wstart + pool_size, w_in + pad_x);
1454 int hend = std::min(hstart + pool_size, h_in + pad_y);
1455 int pool = (hend - hstart) * (wend - wstart);
1456 wstart = std::max(wstart, 0);
1457 hstart = std::max(hstart, 0);
1458 wend = std::min(wend, w_in);
1459 hend = std::min(hend, h_in);
Pablo Tello383deec2017-06-23 10:40:05 +01001460 if(is_floating_point<T>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001461 {
1462 for(int y = hstart; y < hend; ++y)
1463 {
1464 for(int x = wstart; x < wend; ++x)
1465 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001466 avg_val += in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001467 }
1468 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001469 out[r * h_out * w_out + h * pooled_w + w] = avg_val / pool;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001470 }
1471 else
1472 {
1473 static std::array<qint8_t, 10> scale_values_q8 =
1474 { { 0x0, 0x0, 0x40, 0x2A, 0x20, 0x19, 0x15, 0x12, 0x10, 0xE } };
1475
1476 for(int y = hstart; y < hend; ++y)
1477 {
1478 for(int x = wstart; x < wend; ++x)
1479 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001480 avg_val = sqadd_qs8(avg_val, in[r * h_in * w_in + y * w_in + x]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001481 }
1482 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001483 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 +01001484 }
1485 }
1486 }
1487 }
1488 }
1489}
1490
Georgios Pinitas7b7858d2017-06-21 16:44:24 +01001491// Pooling layer
1492template <typename T>
1493void roi_pooling_layer(const Tensor<T> &in, Tensor<T> &out, const std::vector<ROI> &rois, const ROIPoolingLayerInfo &pool_info)
1494{
1495 const int num_rois = rois.size();
1496 const int width_in = in.shape().x();
1497 const int height_in = in.shape().y();
1498 const int fms = in.shape().z();
1499 const int volume_in = width_in * height_in * fms;
1500 const int pool_w = pool_info.pooled_width();
1501 const int pool_h = pool_info.pooled_height();
1502 const int volume_out = pool_w * pool_h * fms;
1503 const float roi_scale = pool_info.spatial_scale();
1504
1505 // Iterate through all rois
1506 for(int roi_idx = 0; roi_idx < num_rois; ++roi_idx)
1507 {
1508 // Get dimensions of current ROI
1509 const ROI &roi = rois[roi_idx];
1510
1511 int batch_id = roi.batch_idx;
1512 int roi_start_x = support::cpp11::round(roi.rect.x * roi_scale);
1513 int roi_start_y = support::cpp11::round(roi.rect.y * roi_scale);
1514 int roi_width = std::max(support::cpp11::round(roi.rect.width * roi_scale), 1.f);
1515 int roi_height = std::max(support::cpp11::round(roi.rect.height * roi_scale), 1.f);
1516
1517 // Determine pooling regions
1518 float pool_region_size_x = static_cast<float>(roi_width) / pool_w;
1519 float pool_region_size_y = static_cast<float>(roi_height) / pool_h;
1520
1521 // Iterate through all channel
1522 for(int fm = 0; fm < fms; ++fm)
1523 {
1524 // Calculate each output pixel
1525 for(int py = 0; py < pool_h; ++py)
1526 {
1527 for(int px = 0; px < pool_w; ++px)
1528 {
1529 int region_start_x = static_cast<int>(std::floor(px * pool_region_size_x));
1530 int region_end_x = static_cast<int>(std::ceil((px + 1) * pool_region_size_x));
1531 int region_start_y = static_cast<int>(std::floor(py * pool_region_size_y));
1532 int region_end_y = static_cast<int>(std::ceil((py + 1) * pool_region_size_y));
1533
1534 region_start_x = std::min(std::max(region_start_x + roi_start_x, 0), width_in);
1535 region_end_x = std::min(std::max(region_end_x + roi_start_x, 0), width_in);
1536 region_start_y = std::min(std::max(region_start_y + roi_start_y, 0), height_in);
1537 region_end_y = std::min(std::max(region_end_y + roi_start_y, 0), height_in);
1538
1539 // Iterate through each pixel in the pooling region
1540 if((region_end_x <= region_start_x) || (region_end_y <= region_start_y))
1541 {
1542 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = 0;
1543 }
1544 else
1545 {
1546 T curr_max = std::numeric_limits<T>::lowest();
1547 for(int j = region_start_y; j < region_end_y; ++j)
1548 {
1549 for(int i = region_start_x; i < region_end_x; ++i)
1550 {
1551 const auto val = in[batch_id * volume_in + fm * width_in * height_in + j * width_in + i];
1552 curr_max = std::max(val, curr_max);
1553 }
1554 }
1555 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = curr_max;
1556 }
1557 }
1558 }
1559 }
1560 }
1561}
1562
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001563// Softmax Layer
Pablo Tello383deec2017-06-23 10:40:05 +01001564template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001565void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1566{
1567 const int cols = static_cast<int>(in.shape()[0]);
1568 const int upper_dims = in.shape().total_size() / cols;
1569 for(int r = 0; r < upper_dims; ++r)
1570 {
1571 // Find max
1572 T max = std::numeric_limits<T>::lowest();
1573 for(int c = 0; c < cols; ++c)
1574 {
1575 const T x = in[r * cols + c];
1576 if(x > max)
1577 {
1578 max = x;
1579 }
1580 }
1581
1582 // Regularize
1583 T sum = 0;
1584 for(int c = 0; c < cols; ++c)
1585 {
1586 const T res = exp(in[r * cols + c] - max);
1587 out[r * cols + c] = res;
1588 sum += res;
1589 }
1590
1591 // Normalize
1592 const T norm_val = 1 / sum;
1593 for(int c = 0; c < cols; ++c)
1594 {
1595 out[r * cols + c] *= norm_val;
1596 }
1597 }
1598}
1599template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1600void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1601{
1602 using namespace fixed_point_arithmetic;
1603 using promoted_T = typename test::traits::promote<T>::type;
1604
1605 const int fixed_point_position = in.fixed_point_position();
1606 const int cols = static_cast<int>(in.shape()[0]);
1607 const int upper_dims = in.shape().total_size() / cols;
1608
1609 for(int r = 0; r < upper_dims; ++r)
1610 {
1611 // Find max
1612 fixed_point<T> max(std::numeric_limits<T>::lowest(), fixed_point_position, true);
1613 for(int c = 0; c < cols; ++c)
1614 {
1615 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1616 if(x > max)
1617 {
1618 max = x;
1619 }
1620 }
1621
1622 // Regularize
1623 fixed_point<promoted_T> sum(0, fixed_point_position);
1624 for(int c = 0; c < cols; ++c)
1625 {
1626 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1627 fixed_point<T> res = exp(x - max);
1628 out[r * cols + c] = res.raw();
1629 sum = add(sum, static_cast<fixed_point<promoted_T>>(res));
1630 }
1631
1632 // Normalize
1633 fixed_point<T> sat_sum(sum);
1634 for(int c = 0; c < cols; ++c)
1635 {
1636 const fixed_point<T> x(out[r * cols + c], fixed_point_position, true);
1637 out[r * cols + c] = div(x, sat_sum).raw();
1638 }
1639 }
1640}
1641
1642// Fixed point operations
1643template <typename T>
1644void fixed_point_operation(const Tensor<T> &in, Tensor<T> &out, FixedPointOp op)
1645{
1646 int p = in.fixed_point_position();
1647 switch(op)
1648 {
1649 case FixedPointOp::EXP:
1650 for(int i = 0; i < in.num_elements(); ++i)
1651 {
1652 out[i] = fixed_point_arithmetic::exp(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1653 }
1654 break;
1655 case FixedPointOp::LOG:
1656 for(int i = 0; i < in.num_elements(); ++i)
1657 {
1658 out[i] = fixed_point_arithmetic::log(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1659 }
1660 break;
1661 case FixedPointOp::INV_SQRT:
1662 for(int i = 0; i < in.num_elements(); ++i)
1663 {
1664 out[i] = fixed_point_arithmetic::inv_sqrt(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1665 }
1666 break;
1667 case FixedPointOp::RECIPROCAL:
1668 for(int i = 0; i < in.num_elements(); ++i)
1669 {
1670 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();
1671 }
1672 break;
1673 default:
1674 ARM_COMPUTE_ERROR("Fixed point operation not supported");
1675 break;
1676 }
1677}
1678
1679// Tensor print
1680template <typename T>
1681void print(const Tensor<T> &in, std::ostream &out)
1682{
1683 out << "\n";
1684 for(int i = 0; i < in.num_elements(); ++i)
1685 {
1686 out << in[i] << " ";
1687 }
1688 out << "\n";
1689}
1690} // namespace tensor_operations
1691} // namespace validation
1692} // namespace test
1693} // namespace arm_compute
1694
1695#endif /* __ARM_COMPUTE_TEST_TENSOR_OPERATIONS_H__ */