blob: e2747249b4eab024d4379b6f1120c404c3c3daea [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
Pablo Tello331fc742017-07-06 11:47:06 +0100522template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&is_floating_point<T2>::value, int >::type = 0 >
Anthony Barbier6ff3b192017-09-04 18:44:23 +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
Pablo Tello331fc742017-07-06 11:47:06 +0100534template < typename T1, typename T2, typename std::enable_if < is_floating_point<T1>::value &&std::is_integral<T2>::value, int >::type = 0 >
Georgios Pinitas21efeb42017-07-04 12:47:17 +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 Pinitas21efeb42017-07-04 12:47:17 +0100546template < typename T1, typename T2, typename std::enable_if < std::is_integral<T1>::value &&std::is_integral<T2>::value, int >::type = 0 >
547void 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
Pablo Tello331fc742017-07-06 11:47:06 +0100568template < 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 +0100569void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100570{
571 for(int i = 0; i < in.num_elements(); ++i)
572 {
Georgios Pinitas21efeb42017-07-04 12:47:17 +0100573 out[i] = static_cast<T2>(in[i]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100574 }
575}
576
SiCong Li5a536642017-06-19 14:47:05 +0100577// Gaussian3x3 filter
578template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
579void gaussian3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
580{
581 const std::array<T, 9> filter{ { 1, 2, 1, 2, 4, 2, 1, 2, 1 } };
582 const float scale = 1.f / 16.f;
583 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
584 {
585 const Coordinates id = index2coord(in.shape(), element_idx);
586 apply_2d_spatial_filter(id, in, out, TensorShape(3U, 3U), filter.data(), scale, border_mode, constant_border_value);
587 }
588}
589
SiCong Li3eb263e2017-06-19 15:31:43 +0100590// Gaussian5x5 filter
591template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
592void gaussian5x5(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
593{
594 const std::array<T, 25> filter{ {
595 1, 4, 6, 4, 1,
596 4, 16, 24, 16, 4,
597 6, 24, 36, 24, 6,
598 4, 16, 24, 16, 4,
599 1, 4, 6, 4, 1
600 } };
601 const float scale = 1.f / 256.f;
602 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
603 {
604 const Coordinates id = index2coord(in.shape(), element_idx);
605 apply_2d_spatial_filter(id, in, out, TensorShape(5U, 5U), filter.data(), scale, border_mode, constant_border_value);
606 }
607}
608
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100609// Matrix multiplication for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100610template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100611void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
612{
613 const int M = out.shape().y();
614 const int N = out.shape().x();
615 const int K = in1.shape().x();
616
617 for(int r = 0; r < M; ++r)
618 {
619 for(int c = 0; c < N; ++c)
620 {
621 T acc = 0.0f;
622
623 for(int k = 0; k < K; ++k)
624 {
625 const T a0 = in1[r * K + k];
626 const T b0 = in2[k * N + c];
627
628 acc += a0 * b0;
629 }
630
631 // Finalize the result: A * B * alpha + C * beta
632 const T c0 = in3[c + r * N];
633 out[c + r * N] = alpha * acc + beta * c0;
634 }
635 }
636}
637
638// Matrix multiplication for fixed point type
639template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
640void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
641{
642 using namespace fixed_point_arithmetic;
643
644 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
645
646 const int M = out.shape().y();
647 const int N = out.shape().x();
648 const int K = in1.shape().x();
649 const int8_t fixed_point_position = static_cast<int8_t>(in1.fixed_point_position());
650
651 const fixed_point<T> alpha_q(alpha, fixed_point_position);
652 const fixed_point<T> beta_q(beta, fixed_point_position);
653
654 for(int r = 0; r < M; ++r)
655 {
656 for(int c = 0; c < N; ++c)
657 {
658 fixed_point<promoted_type> acc_q(0, fixed_point_position);
659
660 for(int k = 0; k < K; ++k)
661 {
662 const fixed_point<promoted_type> a0_q(in1[r * K + k], fixed_point_position, true);
663 const fixed_point<promoted_type> b0_q(in2[k * N + c], fixed_point_position, true);
664 const fixed_point<promoted_type> axb_q = a0_q * b0_q;
665
666 acc_q = axb_q + acc_q;
667 }
668
669 // Finalize the result: A * B * alpha + C * beta
670 const fixed_point<T> c0_q(in3[c + r * N], fixed_point_position, true);
671
672 fixed_point<T> res_q(acc_q);
673 res_q = alpha_q * res_q;
674 res_q = (c0_q * beta_q) + res_q;
675
676 // Store the result
677 out[c + r * N] = res_q.raw();
678 }
679 }
680}
681
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100682// Non linear filter
683template <typename T>
684void non_linear_filter(const Tensor<T> &in, Tensor<T> &out, NonLinearFilterFunction function, unsigned int mask_size,
685 MatrixPattern pattern, const uint8_t *mask, BorderMode border_mode, uint8_t constant_border_value)
686{
SiCong Li7a035752017-06-28 15:27:02 +0100687 ARM_COMPUTE_ERROR_ON(pattern == MatrixPattern::OTHER && mask == nullptr);
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100688
689 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
690
691 const int sq_mask_size = mask_size * mask_size;
692 const int half_mask_size = mask_size / 2;
693 std::vector<intermediate_type> vals(sq_mask_size);
694 intermediate_type current_value = 0;
695
SiCong Li7a035752017-06-28 15:27:02 +0100696 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 +0100697
698 for(int element_idx = 0, count = 0, index = 0; element_idx < in.num_elements(); ++element_idx, count = 0, index = 0)
699 {
700 Coordinates id = index2coord(in.shape(), element_idx);
701 if(is_in_valid_region(valid_region, id))
702 {
703 int idx = id.x();
704 int idy = id.y();
705 for(int y = idy - half_mask_size; y <= idy + half_mask_size; ++y)
706 {
707 for(int x = idx - half_mask_size; x <= idx + half_mask_size; ++x, ++index)
708 {
709 id.set(0, x);
710 id.set(1, y);
711 current_value = tensor_elem_at(in, id, border_mode, constant_border_value);
712
713 if(mask[index] == 255)
714 {
715 vals[count] = static_cast<intermediate_type>(current_value);
716 ++count;
717 }
718 }
719 }
720 std::sort(vals.begin(), vals.begin() + count);
721 switch(function)
722 {
723 case NonLinearFilterFunction::MIN:
724 out[element_idx] = saturate_cast<T>(vals[0]);
725 break;
726 case NonLinearFilterFunction::MAX:
727 out[element_idx] = saturate_cast<T>(vals[count - 1]);
728 break;
729 case NonLinearFilterFunction::MEDIAN:
730 out[element_idx] = saturate_cast<T>(vals[count / 2]);
731 break;
732 default:
733 ARM_COMPUTE_ERROR("Unsupported NonLinearFilter function.");
734 }
735 }
736 }
737}
738
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100739// Pixel-wise multiplication
740template <typename T1, typename T2, typename T3>
741void pixel_wise_multiplication(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, float scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
742{
743 if(scale < 0)
744 {
745 ARM_COMPUTE_ERROR("Scale of pixel-wise multiplication must be non-negative");
746 }
747 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
748 for(int i = 0; i < in1.num_elements(); ++i)
749 {
750 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 +0100751 if(is_floating_point<T3>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100752 {
753 out[i] = val;
754 }
755 else
756 {
757 double rounded_val = 0;
758 switch(rounding_policy)
759 {
760 case(RoundingPolicy::TO_ZERO):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100761 rounded_val = support::cpp11::trunc(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100762 break;
763 case(RoundingPolicy::TO_NEAREST_UP):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100764 rounded_val = round_half_up(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100765 break;
766 case(RoundingPolicy::TO_NEAREST_EVEN):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100767 rounded_val = round_half_even(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100768 break;
769 default:
770 ARM_COMPUTE_ERROR("Unsupported rounding policy");
771 }
772 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(rounded_val) : static_cast<T3>(rounded_val);
773 }
774 }
775}
776
777// Fixed-point Pixel-wise Multiplication
778template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
779void fixed_point_pixel_wise_multiplication(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out, int scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
780{
781 using namespace fixed_point_arithmetic;
782
783 const int fixed_point_position = in1.fixed_point_position();
784
785 ARM_COMPUTE_ERROR_ON_MSG(in1.data_type() != in2.data_type() || in1.data_type() != out.data_type(),
786 "Tensors must all have the same DataType");
787 ARM_COMPUTE_ERROR_ON_MSG(fixed_point_position != in2.fixed_point_position() || fixed_point_position != out.fixed_point_position(),
788 "Fixed-point position must be the same for both inputs and outputs");
789
790 // Validate fixed_point_position
791 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS8) && (fixed_point_position == 0 || fixed_point_position > 7));
792 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS16) && (fixed_point_position == 0 || fixed_point_position > 15));
793
794 fixed_point<T> fp_scale(scale, fixed_point_position);
795 const bool is_sat = convert_policy == ConvertPolicy::SATURATE;
796 const bool do_scaling = scale != 1;
797
798 for(int i = 0; i < in1.num_elements(); ++i)
799 {
800 fixed_point<T> val1(in1[i], fixed_point_position, true);
801 fixed_point<T> val2(in2[i], fixed_point_position, true);
802 fixed_point<T> res = (is_sat) ? val1 * val2 : mul<OverflowPolicy::WRAP>(val1, val2);
803 if(do_scaling)
804 {
805 res = (is_sat) ? res * fp_scale : mul<OverflowPolicy::WRAP>(res, fp_scale);
806 }
807 out[i] = res.raw();
808 }
809}
810
Isabella Gottardib797fa22017-06-23 15:02:11 +0100811//Table Lookup
812template <typename T, typename T1>
813void table_lookup(const Tensor<T> &in, Tensor<T> &out, std::map<T1, T1> &lut)
814{
815 for(int i = 0; i < in.num_elements(); ++i)
816 {
817 out[i] = static_cast<T>(lut[in[i]]);
818 }
819}
820
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100821// Threshold
822template <typename T>
823void threshold(const Tensor<T> &in, Tensor<T> &out, uint8_t threshold, uint8_t false_value, uint8_t true_value, ThresholdType type, uint8_t upper)
824{
825 switch(type)
826 {
827 case ThresholdType::BINARY:
828 for(int i = 0; i < in.num_elements(); ++i)
829 {
830 out[i] = ((in[i] > threshold) ? true_value : false_value);
831 }
832 break;
833 case ThresholdType::RANGE:
834 for(int i = 0; i < in.num_elements(); ++i)
835 {
836 if(in[i] > upper)
837 {
838 out[i] = false_value;
839 }
840 else if(in[i] < threshold)
841 {
842 out[i] = false_value;
843 }
844 else
845 {
846 out[i] = true_value;
847 }
848 }
849 break;
850 default:
851 ARM_COMPUTE_ERROR("Thresholding type not recognised");
852 break;
853 }
854}
855
856// Activation Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100857template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100858void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
859{
860 const T a = static_cast<T>(act_info.a());
861 const T b = static_cast<T>(act_info.b());
862
863 for(int i = 0; i < in.num_elements(); ++i)
864 {
865 T x = in[i];
866 switch(act_info.activation())
867 {
868 case ActivationLayerInfo::ActivationFunction::ABS:
869 out[i] = std::abs(x);
870 break;
871 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
872 out[i] = std::min<T>(a, std::max<T>(0, x));
873 break;
874 case ActivationLayerInfo::ActivationFunction::LINEAR:
875 out[i] = a * x + b;
876 break;
877 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
878 out[i] = static_cast<T>(1) / (static_cast<T>(1) + std::exp(-x));
879 break;
880 case ActivationLayerInfo::ActivationFunction::RELU:
881 out[i] = std::max<T>(0, x);
882 break;
883 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
884 out[i] = std::log(static_cast<T>(1) + std::exp(x));
885 break;
886 case ActivationLayerInfo::ActivationFunction::SQRT:
887 out[i] = std::sqrt(x);
888 break;
889 case ActivationLayerInfo::ActivationFunction::SQUARE:
890 out[i] = x * x;
891 break;
892 case ActivationLayerInfo::ActivationFunction::TANH:
893 out[i] = a * std::tanh(b * x);
894 break;
895 default:
896 ARM_COMPUTE_ERROR("Activation function not recognised");
897 break;
898 }
899 }
900}
901
902// Activation Layer for fixed point type
903template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
904void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
905{
906 using namespace fixed_point_arithmetic;
907 int fixed_point_position = in.fixed_point_position();
908 ActivationLayerInfo::ActivationFunction act_func = act_info.activation();
909 const fixed_point<T> a(act_info.a(), fixed_point_position);
910 const fixed_point<T> b(act_info.b(), fixed_point_position);
911 const fixed_point<T> const_0(0, fixed_point_position);
912 const fixed_point<T> const_1(1, fixed_point_position);
913
914 for(int i = 0; i < in.num_elements(); ++i)
915 {
916 fixed_point<T> x(in[i], fixed_point_position, true);
917 switch(act_func)
918 {
919 case ActivationLayerInfo::ActivationFunction::ABS:
920 out[i] = abs(x).raw();
921 break;
922 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
923 out[i] = min(a, max(const_0, x)).raw();
924 break;
925 case ActivationLayerInfo::ActivationFunction::LINEAR:
926 out[i] = add(b, mul(a, x)).raw();
927 break;
928 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
929 out[i] = (const_1 / (const_1 + exp(-x))).raw();
930 break;
931 case ActivationLayerInfo::ActivationFunction::RELU:
932 out[i] = max(const_0, x).raw();
933 break;
934 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
935 out[i] = log(const_1 + exp(x)).raw();
936 break;
937 case ActivationLayerInfo::ActivationFunction::SQRT:
938 out[i] = (const_1 / inv_sqrt(x)).raw();
939 break;
940 case ActivationLayerInfo::ActivationFunction::SQUARE:
941 out[i] = mul(x, x).raw();
942 break;
943 case ActivationLayerInfo::ActivationFunction::TANH:
Georgios Pinitasccc65d42017-06-27 17:39:11 +0100944 out[i] = mul(a, tanh(mul(b, x))).raw();
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100945 break;
946 default:
947 ARM_COMPUTE_ERROR("Activation function not recognised");
948 break;
949 }
950 }
951}
952
953// Batch Normalization Layer for fixed point type
954template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
955void 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)
956{
957 const int cols = static_cast<int>(in.shape()[0]);
958 const int rows = static_cast<int>(in.shape()[1]);
959 const int depth = static_cast<int>(in.shape()[2]);
960 int upper_dims = in.shape().total_size() / (cols * rows * depth);
961
962 for(int r = 0; r < upper_dims; ++r)
963 {
964 for(int i = 0; i < depth; ++i)
965 {
966 for(int k = 0; k < rows; ++k)
967 {
968 for(int l = 0; l < cols; ++l)
969 {
970 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
971 fixed_point_arithmetic::fixed_point<T> in_qs8(in[pos], fixed_point_position, true);
972 fixed_point_arithmetic::fixed_point<T> var_qs8(var[i], fixed_point_position, true);
973 fixed_point_arithmetic::fixed_point<T> mean_qs8(mean[i], fixed_point_position, true);
974 fixed_point_arithmetic::fixed_point<T> beta_qs8(beta[i], fixed_point_position, true);
975 fixed_point_arithmetic::fixed_point<T> gamma_qs8(gamma[i], fixed_point_position, true);
976 fixed_point_arithmetic::fixed_point<T> epsilon_qs8(epsilon, fixed_point_position);
977
978 auto denominator = fixed_point_arithmetic::inv_sqrt(var_qs8 + epsilon_qs8);
979 auto numerator = in_qs8 - mean_qs8;
980 auto x_bar = numerator * denominator;
981 x_bar = beta_qs8 + x_bar * gamma_qs8;
982 out[pos] = x_bar.raw();
983 }
984 }
985 }
986 }
987}
988
989// Batch Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100990template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100991void 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)
992{
993 const int cols = static_cast<int>(in.shape()[0]);
994 const int rows = static_cast<int>(in.shape()[1]);
995 const int depth = static_cast<int>(in.shape()[2]);
996 int upper_dims = in.shape().total_size() / (cols * rows * depth);
997
998 for(int r = 0; r < upper_dims; ++r)
999 {
1000 for(int i = 0; i < depth; ++i)
1001 {
1002 for(int k = 0; k < rows; ++k)
1003 {
1004 for(int l = 0; l < cols; ++l)
1005 {
1006 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
1007 const float denominator = sqrt(var[i] + epsilon);
1008 const float numerator = in[pos] - mean[i];
1009 const float x_bar = numerator / denominator;
1010 out[pos] = beta[i] + x_bar * gamma[i];
1011 }
1012 }
1013 }
1014 }
1015}
1016
Georgios Pinitasac4e8732017-07-05 17:02:25 +01001017// Depth Concatenate layer
1018template <typename T>
1019void depth_concatenate_layer(const std::vector<const Tensor<T> *> &srcs, Tensor<T> &out)
1020{
1021 unsigned depth_offset = 0;
1022 const int width_out = out.shape().x();
1023 const int height_out = out.shape().y();
1024 const int depth_out = out.shape().z();
1025 const int out_stride_z = width_out * height_out;
1026 const int batches = out.shape().total_size_upper(3);
1027
1028 // Set output tensor to 0
1029 memset(out.data(), 0, out.num_elements() * element_size_from_data_type(out.data_type()));
1030
1031 for(unsigned int i = 0; i < srcs.size(); ++i)
1032 {
1033 ARM_COMPUTE_ERROR_ON(srcs[i] == nullptr);
1034 ARM_COMPUTE_ERROR_ON(srcs[i]->data_type() != out.data_type());
1035 ARM_COMPUTE_ERROR_ON(depth_offset >= out.shape().z());
1036 ARM_COMPUTE_ERROR_ON(batches != static_cast<int>(srcs[i]->shape().total_size_upper(3)));
1037
1038 const Tensor<T> *src = srcs[i];
1039 const int width = src->shape().x();
1040 const int height = src->shape().y();
1041 const int depth = src->shape().z();
1042 const unsigned int x_diff = (width_out - width) / 2;
1043 const unsigned int y_diff = (height_out - height) / 2;
1044
1045 const T *src_ptr = src->data();
1046 for(int b = 0; b < batches; ++b)
1047 {
1048 const unsigned int offset_to_first_element = b * out_stride_z * depth_out + depth_offset * out_stride_z
1049 + y_diff * width_out + x_diff;
1050 for(int d = 0; d < depth; ++d)
1051 {
1052 for(int r = 0; r < height; ++r)
1053 {
1054 std::copy(src_ptr, src_ptr + width, out.data() + offset_to_first_element + d * out_stride_z + r * width_out);
1055 src_ptr += width;
1056 }
1057 }
1058 }
1059
1060 depth_offset += depth;
1061 }
1062}
1063
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001064// Convolution layer
1065template <typename T>
1066void convolution_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out, const PadStrideInfo &conv_info)
1067{
1068 const int width_in = in.shape().x();
1069 const int height_in = in.shape().y();
1070 const int depth_in = in.shape().z();
1071 const int width_out = out.shape().x();
1072 const int height_out = out.shape().y();
1073 const int depth_out = out.shape().z();
1074 const int width_weights = weights.shape().x();
1075 const int height_weights = weights.shape().y();
1076 const int depth_weights = weights.shape().z();
1077 const int pad_xi = std::min(static_cast<int>(conv_info.pad().first), width_weights / 2);
1078 const int pad_yi = std::min(static_cast<int>(conv_info.pad().second), height_weights / 2);
1079 const int start_xi = width_weights / 2 - pad_xi;
1080 const int start_yi = height_weights / 2 - pad_yi;
1081 const int end_xi = width_in - start_xi;
1082 const int end_yi = height_in - start_yi;
1083 const int stride_xi = conv_info.stride().first;
1084 const int stride_yi = conv_info.stride().second;
1085 const int num_batches = in.shape().total_size() / (width_in * height_in * depth_in);
1086
1087 for(int r = 0; r < num_batches; ++r)
1088 {
1089 for(int yi = start_yi; yi < end_yi; yi += stride_yi)
1090 {
1091 for(int xi = start_xi; xi < end_xi; xi += stride_xi)
1092 {
1093 for(int ofm = 0; ofm < depth_out; ++ofm)
1094 {
1095 // Compute input and output offsets
1096 const int offset_in = r * width_in * height_in * depth_in;
1097 const int xo = (xi - start_xi) / stride_xi;
1098 const int yo = (yi - start_yi) / stride_yi;
1099 const int offset_out = xo + yo * width_out + ofm * width_out * height_out + r * width_out * height_out * depth_out;
1100
1101 // Compute 3D convolution
1102 convolution3d(in.data() + offset_in,
1103 weights.data() + ofm * width_weights * height_weights * depth_weights,
1104 bias.data() + ofm,
1105 out.data() + offset_out,
1106 xi, yi,
1107 width_in, height_in, depth_in,
1108 width_weights, height_weights,
1109 static_cast<int8_t>(in.fixed_point_position()));
1110 }
1111 }
1112 }
1113 }
1114}
1115
1116// Fully connected layer
1117template <typename T>
1118void fully_connected_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out)
1119{
1120 ARM_COMPUTE_ERROR_ON(weights.shape().x() != out.shape().x());
1121 ARM_COMPUTE_ERROR_ON(weights.shape().y() != in.shape().x() * in.shape().y() * in.shape().z());
1122 const int cols_weights = weights.shape().x();
1123 const int rows_weights = weights.shape().y();
1124 const int num_batches = in.shape().total_size() / rows_weights;
1125
1126 for(int k = 0; k < num_batches; ++k)
1127 {
1128 vector_matrix_multiply<T>(in.data() + k * rows_weights,
1129 weights.data(),
1130 bias.data(),
1131 out.data() + k * cols_weights,
1132 cols_weights,
1133 rows_weights,
1134 in.fixed_point_position());
1135 }
1136}
1137
1138// Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001139template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001140void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1141{
1142 const uint32_t norm_size = norm_info.norm_size();
1143 NormType type = norm_info.type();
1144 float beta = norm_info.beta();
1145 uint32_t kappa = norm_info.kappa();
1146
1147 const int cols = static_cast<int>(in.shape()[0]);
1148 const int rows = static_cast<int>(in.shape()[1]);
1149 const int depth = static_cast<int>(in.shape()[2]);
1150 int upper_dims = in.shape().total_size() / (cols * rows);
1151
1152 float coeff = norm_info.scale_coeff();
1153 int radius_cols = norm_size / 2;
1154 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1155 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1156
1157 if(type == NormType::CROSS_MAP)
1158 {
1159 // Remove also depth from upper dimensions since it is the axes we want
1160 // to use for normalization
1161 upper_dims /= depth;
1162 for(int r = 0; r < upper_dims; ++r)
1163 {
1164 for(int i = 0; i < rows; ++i)
1165 {
1166 for(int k = 0; k < cols; ++k)
1167 {
1168 for(int l = 0; l < depth; ++l)
1169 {
1170 float accumulated_scale = 0.f;
1171 for(int j = -radius_cols; j <= radius_cols; ++j)
1172 {
1173 const int z = l + j;
1174 if(z >= 0 && z < depth)
1175 {
1176 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1177 accumulated_scale += value * value;
1178 }
1179 }
1180 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = kappa + accumulated_scale * coeff;
1181 }
1182 }
1183 }
1184 }
1185 }
1186 else
1187 {
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 float accumulated_scale = 0.f;
1195 for(int j = -radius_rows; j <= radius_rows; ++j)
1196 {
1197 const int y = i + j;
1198 for(int l = -radius_cols; l <= radius_cols; ++l)
1199 {
1200 const int x = k + l;
1201 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1202 {
1203 const T value = in[x + y * cols + r * cols * rows];
1204 accumulated_scale += value * value;
1205 }
1206 }
1207 }
1208 out[k + i * cols + r * cols * rows] = kappa + accumulated_scale * coeff;
1209 }
1210 }
1211 }
1212 }
1213
1214 if(beta == 1.f)
1215 {
1216 for(int i = 0; i < out.num_elements(); ++i)
1217 {
1218 out[i] = in[i] / out[i];
1219 }
1220 }
1221 else if(beta == 0.5f)
1222 {
1223 for(int i = 0; i < out.num_elements(); ++i)
1224 {
1225 out[i] = in[i] / std::sqrt(out[i]);
1226 }
1227 }
1228 else
1229 {
1230 for(int i = 0; i < out.num_elements(); ++i)
1231 {
1232 out[i] = in[i] * std::exp(std::log(out[i]) * -beta);
1233 }
1234 }
1235}
1236// Normalization Layer for fixed-point types
1237template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1238void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1239{
1240 using namespace fixed_point_arithmetic;
1241
1242 const int fixed_point_position = in.fixed_point_position();
1243
1244 const uint32_t norm_size = norm_info.norm_size();
1245 NormType type = norm_info.type();
1246 fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1247 fixed_point<T> kappa(norm_info.kappa(), fixed_point_position);
1248
1249 const int cols = static_cast<int>(in.shape()[0]);
1250 const int rows = static_cast<int>(in.shape()[1]);
1251 const int depth = static_cast<int>(in.shape()[2]);
1252 int upper_dims = in.shape().total_size() / (cols * rows);
1253
1254 fixed_point<T> coeff(norm_info.scale_coeff(), fixed_point_position);
1255 int radius_cols = norm_size / 2;
1256 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1257 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1258
1259 if(type == NormType::CROSS_MAP)
1260 {
1261 // Remove also depth from upper dimensions since it is the axes we want
1262 // to use for normalization
1263 upper_dims /= depth;
1264 for(int r = 0; r < upper_dims; ++r)
1265 {
1266 for(int i = 0; i < rows; ++i)
1267 {
1268 for(int k = 0; k < cols; ++k)
1269 {
1270 for(int l = 0; l < depth; ++l)
1271 {
1272 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1273 for(int j = -radius_cols; j <= radius_cols; ++j)
1274 {
1275 const int z = l + j;
1276 if(z >= 0 && z < depth)
1277 {
1278 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1279 const fixed_point<T> fp_value(value, fixed_point_position, true);
1280 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1281 }
1282 }
1283 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1284 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = accumulated_scale.raw();
1285 }
1286 }
1287 }
1288 }
1289 }
1290 else
1291 {
1292 for(int r = 0; r < upper_dims; ++r)
1293 {
1294 for(int i = 0; i < rows; ++i)
1295 {
1296 for(int k = 0; k < cols; ++k)
1297 {
1298 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1299 for(int j = -radius_rows; j <= radius_rows; ++j)
1300 {
1301 const int y = i + j;
1302 for(int l = -radius_cols; l <= radius_cols; ++l)
1303 {
1304 const int x = k + l;
1305 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1306 {
1307 const T value = in[x + y * cols + r * cols * rows];
1308 const fixed_point<T> fp_value(value, fixed_point_position, true);
1309 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1310 }
1311 }
1312 }
1313 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1314 out[k + i * cols + r * cols * rows] = accumulated_scale.raw();
1315 }
1316 }
1317 }
1318 }
1319
1320 if(norm_info.beta() == 1.f)
1321 {
1322 for(int i = 0; i < out.num_elements(); ++i)
1323 {
1324 fixed_point<T> res = div(fixed_point<T>(in[i], fixed_point_position, true), fixed_point<T>(out[i], fixed_point_position, true));
1325 out[i] = res.raw();
1326 }
1327 }
1328 else
1329 {
1330 const fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1331 for(int i = 0; i < out.num_elements(); ++i)
1332 {
1333 fixed_point<T> res = pow(fixed_point<T>(out[i], fixed_point_position, true), beta);
1334 res = div(fixed_point<T>(in[i], fixed_point_position, true), res);
1335 out[i] = res.raw();
1336 }
1337 }
1338}
1339
1340// Pooling layer
1341template <typename T>
1342void pooling_layer(const Tensor<T> &in, Tensor<T> &out, PoolingLayerInfo pool_info, int fixed_point_position)
1343{
1344 const int pool_size = pool_info.pool_size();
1345 PoolingType type = pool_info.pool_type();
1346 int pool_stride_x = 0;
1347 int pool_stride_y = 0;
1348 int pad_x = 0;
1349 int pad_y = 0;
1350 std::tie(pool_stride_x, pool_stride_y) = pool_info.pad_stride_info().stride();
1351 std::tie(pad_x, pad_y) = pool_info.pad_stride_info().pad();
1352
Georgios Pinitasce093142017-06-19 16:11:53 +01001353 const int w_in = static_cast<int>(in.shape()[0]);
1354 const int h_in = static_cast<int>(in.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001355
Georgios Pinitasce093142017-06-19 16:11:53 +01001356 const int w_out = static_cast<int>(out.shape()[0]);
1357 const int h_out = static_cast<int>(out.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001358
Georgios Pinitasce093142017-06-19 16:11:53 +01001359 int upper_dims = in.shape().total_size() / (w_in * h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001360
Georgios Pinitasce093142017-06-19 16:11:53 +01001361 int pooled_w = 0;
1362 int pooled_h = 0;
1363 if(pool_info.pad_stride_info().round() == DimensionRoundingType::CEIL)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001364 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001365 pooled_w = static_cast<int>(ceil(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1366 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 +01001367 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001368 else
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001369 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001370 pooled_w = static_cast<int>(floor(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1371 pooled_h = static_cast<int>(floor(static_cast<float>(h_in + 2 * pad_y - pool_size) / pool_stride_y)) + 1;
1372 }
1373
1374 if((pooled_w - 1) * pool_stride_x >= w_in + pad_x)
1375 {
1376 --pooled_w;
1377 }
1378 if((pooled_h - 1) * pool_stride_y >= h_in + pad_y)
1379 {
1380 --pooled_h;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001381 }
1382
1383 if(type == PoolingType::MAX)
1384 {
1385 for(int r = 0; r < upper_dims; ++r)
1386 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001387 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001388 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001389 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001390 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001391 int wstart = w * pool_stride_x - pad_x;
1392 int hstart = h * pool_stride_y - pad_y;
1393 int wend = std::min(wstart + pool_size, w_in);
1394 int hend = std::min(hstart + pool_size, h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001395 wstart = std::max(wstart, 0);
Georgios Pinitasce093142017-06-19 16:11:53 +01001396 hstart = std::max(hstart, 0);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001397
1398 T max_val = std::numeric_limits<T>::lowest();
1399 for(int y = hstart; y < hend; ++y)
1400 {
1401 for(int x = wstart; x < wend; ++x)
1402 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001403 T val = in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001404 if(val > max_val)
1405 {
1406 max_val = val;
1407 }
1408 }
1409 }
1410
Georgios Pinitasce093142017-06-19 16:11:53 +01001411 out[r * h_out * w_out + h * pooled_w + w] = max_val;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001412 }
1413 }
1414 }
1415 }
1416 else // Average pooling
1417 {
1418 for(int r = 0; r < upper_dims; ++r)
1419 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001420 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001421 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001422 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001423 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001424 T avg_val = 0;
1425 int wstart = w * pool_stride_x - pad_x;
1426 int hstart = h * pool_stride_y - pad_y;
1427 int wend = std::min(wstart + pool_size, w_in + pad_x);
1428 int hend = std::min(hstart + pool_size, h_in + pad_y);
1429 int pool = (hend - hstart) * (wend - wstart);
1430 wstart = std::max(wstart, 0);
1431 hstart = std::max(hstart, 0);
1432 wend = std::min(wend, w_in);
1433 hend = std::min(hend, h_in);
Pablo Tello383deec2017-06-23 10:40:05 +01001434 if(is_floating_point<T>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001435 {
1436 for(int y = hstart; y < hend; ++y)
1437 {
1438 for(int x = wstart; x < wend; ++x)
1439 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001440 avg_val += in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001441 }
1442 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001443 out[r * h_out * w_out + h * pooled_w + w] = avg_val / pool;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001444 }
1445 else
1446 {
1447 static std::array<qint8_t, 10> scale_values_q8 =
1448 { { 0x0, 0x0, 0x40, 0x2A, 0x20, 0x19, 0x15, 0x12, 0x10, 0xE } };
1449
1450 for(int y = hstart; y < hend; ++y)
1451 {
1452 for(int x = wstart; x < wend; ++x)
1453 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001454 avg_val = sqadd_qs8(avg_val, in[r * h_in * w_in + y * w_in + x]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001455 }
1456 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001457 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 +01001458 }
1459 }
1460 }
1461 }
1462 }
1463}
1464
Georgios Pinitas7b7858d2017-06-21 16:44:24 +01001465// Pooling layer
1466template <typename T>
1467void roi_pooling_layer(const Tensor<T> &in, Tensor<T> &out, const std::vector<ROI> &rois, const ROIPoolingLayerInfo &pool_info)
1468{
1469 const int num_rois = rois.size();
1470 const int width_in = in.shape().x();
1471 const int height_in = in.shape().y();
1472 const int fms = in.shape().z();
1473 const int volume_in = width_in * height_in * fms;
1474 const int pool_w = pool_info.pooled_width();
1475 const int pool_h = pool_info.pooled_height();
1476 const int volume_out = pool_w * pool_h * fms;
1477 const float roi_scale = pool_info.spatial_scale();
1478
1479 // Iterate through all rois
1480 for(int roi_idx = 0; roi_idx < num_rois; ++roi_idx)
1481 {
1482 // Get dimensions of current ROI
1483 const ROI &roi = rois[roi_idx];
1484
1485 int batch_id = roi.batch_idx;
1486 int roi_start_x = support::cpp11::round(roi.rect.x * roi_scale);
1487 int roi_start_y = support::cpp11::round(roi.rect.y * roi_scale);
1488 int roi_width = std::max(support::cpp11::round(roi.rect.width * roi_scale), 1.f);
1489 int roi_height = std::max(support::cpp11::round(roi.rect.height * roi_scale), 1.f);
1490
1491 // Determine pooling regions
1492 float pool_region_size_x = static_cast<float>(roi_width) / pool_w;
1493 float pool_region_size_y = static_cast<float>(roi_height) / pool_h;
1494
1495 // Iterate through all channel
1496 for(int fm = 0; fm < fms; ++fm)
1497 {
1498 // Calculate each output pixel
1499 for(int py = 0; py < pool_h; ++py)
1500 {
1501 for(int px = 0; px < pool_w; ++px)
1502 {
1503 int region_start_x = static_cast<int>(std::floor(px * pool_region_size_x));
1504 int region_end_x = static_cast<int>(std::ceil((px + 1) * pool_region_size_x));
1505 int region_start_y = static_cast<int>(std::floor(py * pool_region_size_y));
1506 int region_end_y = static_cast<int>(std::ceil((py + 1) * pool_region_size_y));
1507
1508 region_start_x = std::min(std::max(region_start_x + roi_start_x, 0), width_in);
1509 region_end_x = std::min(std::max(region_end_x + roi_start_x, 0), width_in);
1510 region_start_y = std::min(std::max(region_start_y + roi_start_y, 0), height_in);
1511 region_end_y = std::min(std::max(region_end_y + roi_start_y, 0), height_in);
1512
1513 // Iterate through each pixel in the pooling region
1514 if((region_end_x <= region_start_x) || (region_end_y <= region_start_y))
1515 {
1516 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = 0;
1517 }
1518 else
1519 {
1520 T curr_max = std::numeric_limits<T>::lowest();
1521 for(int j = region_start_y; j < region_end_y; ++j)
1522 {
1523 for(int i = region_start_x; i < region_end_x; ++i)
1524 {
1525 const auto val = in[batch_id * volume_in + fm * width_in * height_in + j * width_in + i];
1526 curr_max = std::max(val, curr_max);
1527 }
1528 }
1529 out[roi_idx * volume_out + fm * pool_w * pool_h + py * pool_w + px] = curr_max;
1530 }
1531 }
1532 }
1533 }
1534 }
1535}
1536
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001537// Softmax Layer
Pablo Tello383deec2017-06-23 10:40:05 +01001538template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001539void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1540{
1541 const int cols = static_cast<int>(in.shape()[0]);
1542 const int upper_dims = in.shape().total_size() / cols;
1543 for(int r = 0; r < upper_dims; ++r)
1544 {
1545 // Find max
1546 T max = std::numeric_limits<T>::lowest();
1547 for(int c = 0; c < cols; ++c)
1548 {
1549 const T x = in[r * cols + c];
1550 if(x > max)
1551 {
1552 max = x;
1553 }
1554 }
1555
1556 // Regularize
1557 T sum = 0;
1558 for(int c = 0; c < cols; ++c)
1559 {
1560 const T res = exp(in[r * cols + c] - max);
1561 out[r * cols + c] = res;
1562 sum += res;
1563 }
1564
1565 // Normalize
1566 const T norm_val = 1 / sum;
1567 for(int c = 0; c < cols; ++c)
1568 {
1569 out[r * cols + c] *= norm_val;
1570 }
1571 }
1572}
1573template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1574void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1575{
1576 using namespace fixed_point_arithmetic;
1577 using promoted_T = typename test::traits::promote<T>::type;
1578
1579 const int fixed_point_position = in.fixed_point_position();
1580 const int cols = static_cast<int>(in.shape()[0]);
1581 const int upper_dims = in.shape().total_size() / cols;
1582
1583 for(int r = 0; r < upper_dims; ++r)
1584 {
1585 // Find max
1586 fixed_point<T> max(std::numeric_limits<T>::lowest(), fixed_point_position, true);
1587 for(int c = 0; c < cols; ++c)
1588 {
1589 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1590 if(x > max)
1591 {
1592 max = x;
1593 }
1594 }
1595
1596 // Regularize
1597 fixed_point<promoted_T> sum(0, fixed_point_position);
1598 for(int c = 0; c < cols; ++c)
1599 {
1600 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1601 fixed_point<T> res = exp(x - max);
1602 out[r * cols + c] = res.raw();
1603 sum = add(sum, static_cast<fixed_point<promoted_T>>(res));
1604 }
1605
1606 // Normalize
1607 fixed_point<T> sat_sum(sum);
1608 for(int c = 0; c < cols; ++c)
1609 {
1610 const fixed_point<T> x(out[r * cols + c], fixed_point_position, true);
1611 out[r * cols + c] = div(x, sat_sum).raw();
1612 }
1613 }
1614}
1615
1616// Fixed point operations
1617template <typename T>
1618void fixed_point_operation(const Tensor<T> &in, Tensor<T> &out, FixedPointOp op)
1619{
1620 int p = in.fixed_point_position();
1621 switch(op)
1622 {
1623 case FixedPointOp::EXP:
1624 for(int i = 0; i < in.num_elements(); ++i)
1625 {
1626 out[i] = fixed_point_arithmetic::exp(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1627 }
1628 break;
1629 case FixedPointOp::LOG:
1630 for(int i = 0; i < in.num_elements(); ++i)
1631 {
1632 out[i] = fixed_point_arithmetic::log(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1633 }
1634 break;
1635 case FixedPointOp::INV_SQRT:
1636 for(int i = 0; i < in.num_elements(); ++i)
1637 {
1638 out[i] = fixed_point_arithmetic::inv_sqrt(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1639 }
1640 break;
1641 case FixedPointOp::RECIPROCAL:
1642 for(int i = 0; i < in.num_elements(); ++i)
1643 {
1644 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();
1645 }
1646 break;
1647 default:
1648 ARM_COMPUTE_ERROR("Fixed point operation not supported");
1649 break;
1650 }
1651}
1652
1653// Tensor print
1654template <typename T>
1655void print(const Tensor<T> &in, std::ostream &out)
1656{
1657 out << "\n";
1658 for(int i = 0; i < in.num_elements(); ++i)
1659 {
1660 out << in[i] << " ";
1661 }
1662 out << "\n";
1663}
1664} // namespace tensor_operations
1665} // namespace validation
1666} // namespace test
1667} // namespace arm_compute
1668
1669#endif /* __ARM_COMPUTE_TEST_TENSOR_OPERATIONS_H__ */