blob: 4f7765613cf6ad1daec2745a3466f73054141257 [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>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010044
45namespace arm_compute
46{
47namespace test
48{
49namespace validation
50{
51namespace tensor_operations
52{
53namespace
54{
Pablo Tello383deec2017-06-23 10:40:05 +010055template <class T>
56struct is_floating_point
57 : std::integral_constant < bool,
58 std::is_same<float, typename std::remove_cv<T>::type>::value ||
59#if ARM_COMPUTE_ENABLE_FP16
60 std::is_same<float16_t, typename std::remove_cv<T>::type>::value ||
61#endif
62 std::is_same<double, typename std::remove_cv<T>::type>::value || std::is_same<long double, typename std::remove_cv<T>::type>::value >
63{
64};
65
Anthony Barbier6ff3b192017-09-04 18:44:23 +010066bool is_valid_pixel(int i, int min, int max)
67{
68 return (i >= min && i < max);
69}
70
71// 3D convolution for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +010072template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +010073void 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)
74{
75 const int half_width_weights = width_weights / 2;
76 const int half_height_weights = height_weights / 2;
77
78 // Reset accumulator
79 T acc = static_cast<T>(0);
80
81 // Compute a 2D convolution for each IFM and accumulate the result
82 for(int ifm = 0; ifm < depth_in; ++ifm)
83 {
84 // Compute the offset for the input slice
85 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
86
87 // Compute 2D convolution
88 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
89 {
90 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
91 {
92 // Check if the pixel is out-of-bound
93 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
94 {
95 const int idx = xk + half_width_weights;
96 const int idy = yk + half_height_weights;
97
98 const T i_value = in[offset_slice_in + xk + yk * width_in];
99 const T w_value = weights[idx + idy * width_weights + ifm * width_weights * height_weights];
100
101 acc += i_value * w_value;
102 }
103 }
104 }
105 }
106
107 // Accumulate the bias and store the result
108 *out = acc + (*bias);
109}
110
111// 3D convolution for fixed point type
112template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
113void 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,
114 int8_t fixed_point_position)
115{
116 const int half_width_weights = width_weights / 2;
117 const int half_height_weights = height_weights / 2;
118
119 using namespace fixed_point_arithmetic;
120 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
121
122 // Reset accumulator
123 fixed_point<promoted_type> acc(0, fixed_point_position);
124
125 // Compute a 2D convolution for each IFM and accumulate the result
126 for(int ifm = 0; ifm < depth_in; ++ifm)
127 {
128 // Compute the offset for the input slice
129 const int offset_slice_in = xi + yi * width_in + ifm * width_in * height_in;
130
131 // Compute 2D convolution
132 for(int yk = -half_height_weights; yk <= half_height_weights; ++yk)
133 {
134 for(int xk = -half_width_weights; xk <= half_width_weights; ++xk)
135 {
136 // Check if the pixel is out-of-bound
137 if(is_valid_pixel(xi + xk, 0, width_in) && is_valid_pixel(yi + yk, 0, height_in))
138 {
139 const int idx = xk + half_width_weights;
140 const int idy = yk + half_height_weights;
141
142 const fixed_point<promoted_type> i_value(in[offset_slice_in + xk + yk * width_in], fixed_point_position, true);
143 const fixed_point<promoted_type> w_value(weights[idx + idy * width_weights + ifm * width_weights * height_weights], fixed_point_position, true);
144 const fixed_point<promoted_type> iw = i_value * w_value;
145 acc = iw + acc;
146 }
147 }
148 }
149 }
150
151 // Get the bias
152 const fixed_point<promoted_type> b(*bias, fixed_point_position, true);
153
154 // Accumulate the bias and covert back
155 acc = acc + b;
156 fixed_point<T> res(acc);
157 *out = res.raw();
158}
159
160template <typename T>
161void 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)
162{
163 for(int x = 0; x < cols_weights; ++x)
164 {
165 T acc = 0.0f;
166 for(int y = 0; y < rows_weights; ++y)
167 {
168 acc += in[y] * weights[x + y * cols_weights];
169 }
170 out[x] = acc + bias[x];
171 }
172}
173
174template <>
175void vector_matrix_multiply(const int8_t *in, const int8_t *weights, const int8_t *bias, int8_t *out, int cols_weights, int rows_weights, uint8_t fixed_point_position)
176{
177 using namespace fixed_point_arithmetic;
178 using promoted_type = typename fixed_point_arithmetic::traits::promote<int8_t>::type;
179
180 for(int x = 0; x < cols_weights; ++x)
181 {
182 // Reset accumulator
183 fixed_point<promoted_type> acc(0, fixed_point_position);
184
185 for(int y = 0; y < rows_weights; ++y)
186 {
187 const fixed_point<promoted_type> i_value(in[y], fixed_point_position, true);
188 const fixed_point<promoted_type> w_value(weights[x + y * cols_weights], fixed_point_position, true);
189 const fixed_point<promoted_type> iw = i_value * w_value;
190 acc = iw + acc;
191 }
192
193 // Get the bias
194 const fixed_point<int8_t> b(bias[x], fixed_point_position, true);
195
196 // Convert back and accumulate the bias
197 fixed_point<int8_t> res(acc);
198 res = res + b;
199
200 // Store the result
201 out[x] = res.raw();
202 }
203}
204
SiCong Libacaf9a2017-06-19 13:41:45 +0100205// Return a tensor element at a specified coordinate with different border modes
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100206template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
207T tensor_elem_at(const Tensor<T> &in, Coordinates &coord, BorderMode border_mode, T constant_border_value)
208{
209 const int x = coord.x();
210 const int y = coord.y();
211 const int width = static_cast<int>(in.shape().x());
212 const int height = static_cast<int>(in.shape().y());
213
SiCong Libacaf9a2017-06-19 13:41:45 +0100214 // If coordinates beyond range of tensor's width or height
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100215 if(x < 0 || y < 0 || x >= width || y >= height)
216 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100217 if(border_mode == BorderMode::REPLICATE)
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100218 {
219 coord.set(0, std::max(0, std::min(x, width - 1)));
220 coord.set(1, std::max(0, std::min(y, height - 1)));
221 return in[coord2index(in.shape(), coord)];
222 }
223 else
224 {
SiCong Libacaf9a2017-06-19 13:41:45 +0100225 return constant_border_value;
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100226 }
227 }
228 else
229 {
230 return in[coord2index(in.shape(), coord)];
231 }
232}
233
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100234/** Apply 2D spatial filter on a single element of @p in at coordinates @p coord
235 *
236 * - filter sizes have to be odd number
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100237 * - Row major order of filter assumed
238 * - TO_ZERO rounding policy assumed
239 * - SATURATE convert policy assumed
240 *
241 */
242template <typename T1, typename T2, typename T3>
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100243void 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,
244 T1 constant_border_value = 0)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100245{
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100246 double val = 0;
247 const int x = coord.x();
248 const int y = coord.y();
249 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 +0100250 {
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100251 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 +0100252 {
253 coord.set(0, i);
254 coord.set(1, j);
SiCong Libacaf9a2017-06-19 13:41:45 +0100255 val += static_cast<double>(*filter_itr) * tensor_elem_at(in, coord, border_mode, constant_border_value);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100256 ++filter_itr;
257 }
258 }
259 coord.set(0, x);
260 coord.set(1, y);
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100261 const double rounded_val = support::cpp11::trunc(val * static_cast<double>(scale));
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100262 out[coord2index(in.shape(), coord)] = saturate_cast<T3>(rounded_val);
263}
264} // namespace
265
Giorgio Arena50f9fd72017-06-19 17:05:30 +0100266// Sobel 3x3
267template <typename T1, typename T2>
268void sobel_3x3(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
269{
270 const std::array<int8_t, 9> sobel_x{ { -1, 0, 1, -2, 0, 2, -1, 0, 1 } };
271 const std::array<int8_t, 9> sobel_y{ { -1, -2, -1, 0, 0, 0, 1, 2, 1 } };
272
273 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
274 {
275 const Coordinates id = index2coord(in.shape(), element_idx);
276
277 apply_2d_spatial_filter(id, in, out_x, TensorShape(3U, 3U), sobel_x.data(), 1.f, border_mode, constant_border_value);
278 apply_2d_spatial_filter(id, in, out_y, TensorShape(3U, 3U), sobel_y.data(), 1.f, border_mode, constant_border_value);
279 }
280}
281
282// Sobel 5x5
283template <typename T1, typename T2>
284void sobel_5x5(Tensor<T1> &in, Tensor<T2> &out_x, Tensor<T2> &out_y, BorderMode border_mode, uint8_t constant_border_value)
285{
286 const std::array<int8_t, 25> sobel_x{ {
287 -1, -2, 0, 2, 1,
288 -4, -8, 0, 8, 4,
289 -6, -12, 0, 12, 6,
290 -4, -8, 0, 8, 4,
291 -1, -2, 0, 2, 1
292 } };
293
294 const std::array<int8_t, 25> sobel_y{ {
295 -1, -4, -6, -4, -1,
296 -2, -8, -12, -8, -2,
297 0, 0, 0, 0, 0,
298 2, 8, 12, 8, 2,
299 1, 4, 6, 4, 1
300 } };
301
302 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
303 {
304 const Coordinates id = index2coord(in.shape(), element_idx);
305
306 apply_2d_spatial_filter(id, in, out_x, TensorShape(5U, 5U), sobel_x.data(), 1.f, border_mode, constant_border_value);
307 apply_2d_spatial_filter(id, in, out_y, TensorShape(5U, 5U), sobel_y.data(), 1.f, border_mode, constant_border_value);
308 }
309}
310
Giorgio Arenaf7959862017-06-13 15:19:51 +0100311// Mean Standard Deviation
312template <typename T1>
313void mean_and_standard_deviation(const Tensor<T1> &in, float &mean, float &std_dev)
314{
315 int num_elements = in.num_elements();
316
317 // Calculate mean
318 mean = 0.f;
319 for(int i = 0; i < num_elements; ++i)
320 {
321 mean += in[i];
322 }
323 mean /= num_elements;
324
325 // Calculate standard deviation
326 std_dev = 0.f;
327 for(int i = 0; i < num_elements; ++i)
328 {
329 std_dev += (mean - in[i]) * (mean - in[i]);
330 }
331 std_dev = sqrt(std_dev / num_elements);
332}
333
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100334// Integral Image
335void integral_image(const Tensor<uint8_t> &in, Tensor<uint32_t> &out)
336{
337 // Length of dimensions
338 const size_t width = in.shape().x();
339 const size_t height = in.shape().y();
340 const size_t depth = in.shape().z() * in.shape()[3] * in.shape()[4] * in.shape()[5];
341
342 const size_t image_size = width * height;
343
344 for(size_t z = 0; z < depth; ++z)
345 {
346 size_t current_image = z * image_size;
347
348 //First element of each image
349 out[current_image] = in[current_image];
350
351 // First row of each image (add only pixel on the left)
352 for(size_t x = 1; x < width; ++x)
353 {
354 out[current_image + x] = static_cast<uint32_t>(in[current_image + x]) + out[current_image + x - 1];
355 }
356
357 // Subsequent rows
358 for(size_t y = 1; y < height; ++y)
359 {
360 size_t current_row = current_image + (width * y);
361
362 // First element of each row (add only pixel up)
363 out[current_row] = static_cast<uint32_t>(in[current_row]) + out[current_row - width];
364
365 // Following row elements
366 for(size_t x = 1; x < width; ++x)
367 {
368 size_t current_pixel = current_row + x;
369
370 // out = in + up(out) + left(out) - up_left(out)
371 out[current_pixel] = static_cast<uint32_t>(in[current_pixel]) + out[current_pixel - 1]
372 + out[current_pixel - width] - out[current_pixel - width - 1];
373 }
374 }
375 }
376}
377
378// Absolute difference
379template <typename T1, typename T2, typename T3>
380void absolute_difference(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out)
381{
382 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
383
384 for(int i = 0; i < in1.num_elements(); ++i)
385 {
386 intermediate_type val = std::abs(static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]));
387 out[i] = saturate_cast<T3>(val);
388 }
389}
390
391// Accumulate
392template <typename T1, typename T2>
393void accumulate(const Tensor<T1> &in, Tensor<T2> &out)
394{
395 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
396
397 for(int i = 0; i < in.num_elements(); ++i)
398 {
399 intermediate_type val = static_cast<intermediate_type>(out[i]) + static_cast<intermediate_type>(in[i]);
400 out[i] = saturate_cast<T2>(val);
401 }
402}
403
404// Accumulate squared
405template <typename T1, typename T2>
406void accumulate_squared(const Tensor<T1> &in, Tensor<T2> &out, uint32_t shift)
407{
408 if(shift > 15)
409 {
410 ARM_COMPUTE_ERROR("Shift in accumulate_squared must be within the range [0, 15]");
411 }
412 using intermediate_type = typename common_promoted_signed_type<T1, T2>::intermediate_type;
413 intermediate_type denom = 1 << shift;
414
415 for(int i = 0; i < in.num_elements(); ++i)
416 {
417 intermediate_type val = static_cast<intermediate_type>(out[i]) + (static_cast<intermediate_type>(in[i]) * static_cast<intermediate_type>(in[i]) / denom);
418 out[i] = saturate_cast<T2>(val);
419 }
420}
421
422// Accumulate weighted
423template <typename T>
424void accumulate_weighted(const Tensor<T> &in, Tensor<T> &out, float alpha)
425{
426 if(alpha < 0.f || alpha > 1.f)
427 {
428 ARM_COMPUTE_ERROR("Weight (alpha) specified in accumulate_weighted must be within the range [0, 1]");
429 }
430 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
431
432 for(int i = 0; i < in.num_elements(); ++i)
433 {
434 double val = (1. - static_cast<double>(alpha)) * static_cast<intermediate_type>(out[i]) + static_cast<double>(alpha) * static_cast<intermediate_type>(in[i]);
435 out[i] = static_cast<T>(val);
436 }
437}
438
439// Arithmetic addition
440template <typename T1, typename T2, typename T3>
441void arithmetic_addition(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
442{
443 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
444
445 for(int i = 0; i < in1.num_elements(); ++i)
446 {
447 intermediate_type val = static_cast<intermediate_type>(in1[i]) + static_cast<intermediate_type>(in2[i]);
448 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
449 }
450}
451
452// Arithmetic Subtraction
453template <typename T1, typename T2, typename T3>
454void arithmetic_subtraction(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, ConvertPolicy convert_policy)
455{
456 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
457
458 for(int i = 0; i < in1.num_elements(); ++i)
459 {
460 intermediate_type val = static_cast<intermediate_type>(in1[i]) - static_cast<intermediate_type>(in2[i]);
461 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(val) : static_cast<T3>(val);
462 }
463}
464
465// Bitwise and
466template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
467void bitwise_and(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
468{
469 for(int i = 0; i < in1.num_elements(); ++i)
470 {
471 out[i] = in1[i] & in2[i];
472 }
473}
474
475// Bitwise or
476template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
477void bitwise_or(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
478{
479 for(int i = 0; i < in1.num_elements(); ++i)
480 {
481 out[i] = in1[i] | in2[i];
482 }
483}
484
485// Bitwise xor
486template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
487void bitwise_xor(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out)
488{
489 for(int i = 0; i < in1.num_elements(); ++i)
490 {
491 out[i] = in1[i] ^ in2[i];
492 }
493}
494
495// Bitwise not
496template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
497void bitwise_not(const Tensor<T> &in, Tensor<T> &out)
498{
499 for(int i = 0; i < in.num_elements(); ++i)
500 {
501 out[i] = ~in[i];
502 }
503}
504
SiCong Libacaf9a2017-06-19 13:41:45 +0100505// Box3x3 filter
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100506template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
SiCong Libacaf9a2017-06-19 13:41:45 +0100507void box3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100508{
509 const std::array<T, 9> filter{ { 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
SiCong Libacaf9a2017-06-19 13:41:45 +0100510 float scale = 1.f / static_cast<float>(filter.size());
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100511 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
512 {
513 const Coordinates id = index2coord(in.shape(), element_idx);
SiCong Libacaf9a2017-06-19 13:41:45 +0100514 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 +0100515 }
516}
517
518// Depth conversion
519template <typename T1, typename T2>
520void depth_convert(const Tensor<T1> &in, Tensor<T2> &out, ConvertPolicy policy, uint32_t shift)
521{
522 ARM_COMPUTE_ERROR("The conversion is not supported");
523}
524
525template <>
526void depth_convert<int8_t, float>(const Tensor<int8_t> &in, Tensor<float> &out, ConvertPolicy policy, uint32_t shift)
527{
528 const int8_t fixed_point_position = static_cast<int8_t>(in.fixed_point_position());
529 for(int i = 0; i < in.num_elements(); ++i)
530 {
531 out[i] = static_cast<float>(in[i]) * (1.0f / (1 << fixed_point_position));
532 }
533}
534
535template <>
536void depth_convert<float, int8_t>(const Tensor<float> &in, Tensor<int8_t> &out, ConvertPolicy policy, uint32_t shift)
537{
538 const int8_t fixed_point_position = static_cast<int8_t>(in.fixed_point_position());
539 for(int i = 0; i < in.num_elements(); ++i)
540 {
541 float val = in[i] * (1 << fixed_point_position) + 0.5f;
542 out[i] = ((policy == ConvertPolicy::SATURATE) ? saturate_cast<int8_t>(val) : static_cast<int8_t>(val));
543 }
544}
545
546template <>
547void depth_convert<uint8_t, uint16_t>(const Tensor<uint8_t> &in, Tensor<uint16_t> &out, ConvertPolicy policy, uint32_t shift)
548{
549 for(int i = 0; i < in.num_elements(); ++i)
550 {
551 out[i] = static_cast<uint16_t>(in[i]) << shift;
552 }
553}
554
555template <>
556void depth_convert<uint8_t, int16_t>(const Tensor<uint8_t> &in, Tensor<int16_t> &out, ConvertPolicy policy, uint32_t shift)
557{
558 for(int i = 0; i < in.num_elements(); ++i)
559 {
560 out[i] = static_cast<int16_t>(in[i]) << shift;
561 }
562}
563
564template <>
565void depth_convert<uint8_t, int32_t>(const Tensor<uint8_t> &in, Tensor<int32_t> &out, ConvertPolicy policy, uint32_t shift)
566{
567 for(int i = 0; i < in.num_elements(); ++i)
568 {
569 out[i] = static_cast<int32_t>(in[i]) << shift;
570 }
571}
572
573template <>
574void depth_convert<uint16_t, uint8_t>(const Tensor<uint16_t> &in, Tensor<uint8_t> &out, ConvertPolicy policy, uint32_t shift)
575{
576 for(int i = 0; i < in.num_elements(); ++i)
577 {
578 uint16_t val = in[i] >> shift;
579 out[i] = ((policy == ConvertPolicy::SATURATE) ? saturate_cast<uint8_t>(val) : static_cast<uint8_t>(val));
580 }
581}
582
583template <>
584void depth_convert<uint16_t, uint32_t>(const Tensor<uint16_t> &in, Tensor<uint32_t> &out, ConvertPolicy policy, uint32_t shift)
585{
586 for(int i = 0; i < in.num_elements(); ++i)
587 {
588 out[i] = static_cast<uint32_t>(in[i]) << shift;
589 }
590}
591
592template <>
593void depth_convert<int16_t, uint8_t>(const Tensor<int16_t> &in, Tensor<uint8_t> &out, ConvertPolicy policy, uint32_t shift)
594{
595 for(int i = 0; i < in.num_elements(); ++i)
596 {
597 int16_t val = in[i] >> shift;
598 out[i] = ((policy == ConvertPolicy::SATURATE) ? saturate_cast<uint8_t>(val) : static_cast<uint8_t>(val));
599 }
600}
601template <>
602void depth_convert<int16_t, int32_t>(const Tensor<int16_t> &in, Tensor<int32_t> &out, ConvertPolicy policy, uint32_t shift)
603{
604 for(int i = 0; i < in.num_elements(); ++i)
605 {
606 out[i] = static_cast<int32_t>(in[i]) << shift;
607 }
608}
609
SiCong Li5a536642017-06-19 14:47:05 +0100610// Gaussian3x3 filter
611template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
612void gaussian3x3(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
613{
614 const std::array<T, 9> filter{ { 1, 2, 1, 2, 4, 2, 1, 2, 1 } };
615 const float scale = 1.f / 16.f;
616 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
617 {
618 const Coordinates id = index2coord(in.shape(), element_idx);
619 apply_2d_spatial_filter(id, in, out, TensorShape(3U, 3U), filter.data(), scale, border_mode, constant_border_value);
620 }
621}
622
SiCong Li3eb263e2017-06-19 15:31:43 +0100623// Gaussian5x5 filter
624template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
625void gaussian5x5(const Tensor<T> &in, Tensor<T> &out, BorderMode border_mode, T constant_border_value)
626{
627 const std::array<T, 25> filter{ {
628 1, 4, 6, 4, 1,
629 4, 16, 24, 16, 4,
630 6, 24, 36, 24, 6,
631 4, 16, 24, 16, 4,
632 1, 4, 6, 4, 1
633 } };
634 const float scale = 1.f / 256.f;
635 for(int element_idx = 0; element_idx < in.num_elements(); ++element_idx)
636 {
637 const Coordinates id = index2coord(in.shape(), element_idx);
638 apply_2d_spatial_filter(id, in, out, TensorShape(5U, 5U), filter.data(), scale, border_mode, constant_border_value);
639 }
640}
641
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100642// Matrix multiplication for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100643template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100644void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
645{
646 const int M = out.shape().y();
647 const int N = out.shape().x();
648 const int K = in1.shape().x();
649
650 for(int r = 0; r < M; ++r)
651 {
652 for(int c = 0; c < N; ++c)
653 {
654 T acc = 0.0f;
655
656 for(int k = 0; k < K; ++k)
657 {
658 const T a0 = in1[r * K + k];
659 const T b0 = in2[k * N + c];
660
661 acc += a0 * b0;
662 }
663
664 // Finalize the result: A * B * alpha + C * beta
665 const T c0 = in3[c + r * N];
666 out[c + r * N] = alpha * acc + beta * c0;
667 }
668 }
669}
670
671// Matrix multiplication for fixed point type
672template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
673void gemm(const Tensor<T> &in1, const Tensor<T> &in2, const Tensor<T> &in3, Tensor<T> &out, float alpha, float beta)
674{
675 using namespace fixed_point_arithmetic;
676
677 using promoted_type = typename fixed_point_arithmetic::traits::promote<T>::type;
678
679 const int M = out.shape().y();
680 const int N = out.shape().x();
681 const int K = in1.shape().x();
682 const int8_t fixed_point_position = static_cast<int8_t>(in1.fixed_point_position());
683
684 const fixed_point<T> alpha_q(alpha, fixed_point_position);
685 const fixed_point<T> beta_q(beta, fixed_point_position);
686
687 for(int r = 0; r < M; ++r)
688 {
689 for(int c = 0; c < N; ++c)
690 {
691 fixed_point<promoted_type> acc_q(0, fixed_point_position);
692
693 for(int k = 0; k < K; ++k)
694 {
695 const fixed_point<promoted_type> a0_q(in1[r * K + k], fixed_point_position, true);
696 const fixed_point<promoted_type> b0_q(in2[k * N + c], fixed_point_position, true);
697 const fixed_point<promoted_type> axb_q = a0_q * b0_q;
698
699 acc_q = axb_q + acc_q;
700 }
701
702 // Finalize the result: A * B * alpha + C * beta
703 const fixed_point<T> c0_q(in3[c + r * N], fixed_point_position, true);
704
705 fixed_point<T> res_q(acc_q);
706 res_q = alpha_q * res_q;
707 res_q = (c0_q * beta_q) + res_q;
708
709 // Store the result
710 out[c + r * N] = res_q.raw();
711 }
712 }
713}
714
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100715// Non linear filter
716template <typename T>
717void non_linear_filter(const Tensor<T> &in, Tensor<T> &out, NonLinearFilterFunction function, unsigned int mask_size,
718 MatrixPattern pattern, const uint8_t *mask, BorderMode border_mode, uint8_t constant_border_value)
719{
SiCong Li7a035752017-06-28 15:27:02 +0100720 ARM_COMPUTE_ERROR_ON(pattern == MatrixPattern::OTHER && mask == nullptr);
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100721
722 using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;
723
724 const int sq_mask_size = mask_size * mask_size;
725 const int half_mask_size = mask_size / 2;
726 std::vector<intermediate_type> vals(sq_mask_size);
727 intermediate_type current_value = 0;
728
SiCong Li7a035752017-06-28 15:27:02 +0100729 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 +0100730
731 for(int element_idx = 0, count = 0, index = 0; element_idx < in.num_elements(); ++element_idx, count = 0, index = 0)
732 {
733 Coordinates id = index2coord(in.shape(), element_idx);
734 if(is_in_valid_region(valid_region, id))
735 {
736 int idx = id.x();
737 int idy = id.y();
738 for(int y = idy - half_mask_size; y <= idy + half_mask_size; ++y)
739 {
740 for(int x = idx - half_mask_size; x <= idx + half_mask_size; ++x, ++index)
741 {
742 id.set(0, x);
743 id.set(1, y);
744 current_value = tensor_elem_at(in, id, border_mode, constant_border_value);
745
746 if(mask[index] == 255)
747 {
748 vals[count] = static_cast<intermediate_type>(current_value);
749 ++count;
750 }
751 }
752 }
753 std::sort(vals.begin(), vals.begin() + count);
754 switch(function)
755 {
756 case NonLinearFilterFunction::MIN:
757 out[element_idx] = saturate_cast<T>(vals[0]);
758 break;
759 case NonLinearFilterFunction::MAX:
760 out[element_idx] = saturate_cast<T>(vals[count - 1]);
761 break;
762 case NonLinearFilterFunction::MEDIAN:
763 out[element_idx] = saturate_cast<T>(vals[count / 2]);
764 break;
765 default:
766 ARM_COMPUTE_ERROR("Unsupported NonLinearFilter function.");
767 }
768 }
769 }
770}
771
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100772// Pixel-wise multiplication
773template <typename T1, typename T2, typename T3>
774void pixel_wise_multiplication(const Tensor<T1> &in1, const Tensor<T2> &in2, Tensor<T3> &out, float scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
775{
776 if(scale < 0)
777 {
778 ARM_COMPUTE_ERROR("Scale of pixel-wise multiplication must be non-negative");
779 }
780 using intermediate_type = typename common_promoted_signed_type<T1, T2, T3>::intermediate_type;
781 for(int i = 0; i < in1.num_elements(); ++i)
782 {
783 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 +0100784 if(is_floating_point<T3>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100785 {
786 out[i] = val;
787 }
788 else
789 {
790 double rounded_val = 0;
791 switch(rounding_policy)
792 {
793 case(RoundingPolicy::TO_ZERO):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100794 rounded_val = support::cpp11::trunc(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100795 break;
796 case(RoundingPolicy::TO_NEAREST_UP):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100797 rounded_val = round_half_up(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100798 break;
799 case(RoundingPolicy::TO_NEAREST_EVEN):
Moritz Pflanzerd0ae8b82017-06-29 14:51:57 +0100800 rounded_val = round_half_even(val);
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100801 break;
802 default:
803 ARM_COMPUTE_ERROR("Unsupported rounding policy");
804 }
805 out[i] = (convert_policy == ConvertPolicy::SATURATE) ? saturate_cast<T3>(rounded_val) : static_cast<T3>(rounded_val);
806 }
807 }
808}
809
810// Fixed-point Pixel-wise Multiplication
811template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
812void fixed_point_pixel_wise_multiplication(const Tensor<T> &in1, const Tensor<T> &in2, Tensor<T> &out, int scale, ConvertPolicy convert_policy, RoundingPolicy rounding_policy)
813{
814 using namespace fixed_point_arithmetic;
815
816 const int fixed_point_position = in1.fixed_point_position();
817
818 ARM_COMPUTE_ERROR_ON_MSG(in1.data_type() != in2.data_type() || in1.data_type() != out.data_type(),
819 "Tensors must all have the same DataType");
820 ARM_COMPUTE_ERROR_ON_MSG(fixed_point_position != in2.fixed_point_position() || fixed_point_position != out.fixed_point_position(),
821 "Fixed-point position must be the same for both inputs and outputs");
822
823 // Validate fixed_point_position
824 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS8) && (fixed_point_position == 0 || fixed_point_position > 7));
825 ARM_COMPUTE_ERROR_ON((in1.data_type() == DataType::QS16) && (fixed_point_position == 0 || fixed_point_position > 15));
826
827 fixed_point<T> fp_scale(scale, fixed_point_position);
828 const bool is_sat = convert_policy == ConvertPolicy::SATURATE;
829 const bool do_scaling = scale != 1;
830
831 for(int i = 0; i < in1.num_elements(); ++i)
832 {
833 fixed_point<T> val1(in1[i], fixed_point_position, true);
834 fixed_point<T> val2(in2[i], fixed_point_position, true);
835 fixed_point<T> res = (is_sat) ? val1 * val2 : mul<OverflowPolicy::WRAP>(val1, val2);
836 if(do_scaling)
837 {
838 res = (is_sat) ? res * fp_scale : mul<OverflowPolicy::WRAP>(res, fp_scale);
839 }
840 out[i] = res.raw();
841 }
842}
843
844// Threshold
845template <typename T>
846void threshold(const Tensor<T> &in, Tensor<T> &out, uint8_t threshold, uint8_t false_value, uint8_t true_value, ThresholdType type, uint8_t upper)
847{
848 switch(type)
849 {
850 case ThresholdType::BINARY:
851 for(int i = 0; i < in.num_elements(); ++i)
852 {
853 out[i] = ((in[i] > threshold) ? true_value : false_value);
854 }
855 break;
856 case ThresholdType::RANGE:
857 for(int i = 0; i < in.num_elements(); ++i)
858 {
859 if(in[i] > upper)
860 {
861 out[i] = false_value;
862 }
863 else if(in[i] < threshold)
864 {
865 out[i] = false_value;
866 }
867 else
868 {
869 out[i] = true_value;
870 }
871 }
872 break;
873 default:
874 ARM_COMPUTE_ERROR("Thresholding type not recognised");
875 break;
876 }
877}
878
879// Activation Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +0100880template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100881void activation_layer(const Tensor<T> &in, Tensor<T> &out, ActivationLayerInfo act_info)
882{
883 const T a = static_cast<T>(act_info.a());
884 const T b = static_cast<T>(act_info.b());
885
886 for(int i = 0; i < in.num_elements(); ++i)
887 {
888 T x = in[i];
889 switch(act_info.activation())
890 {
891 case ActivationLayerInfo::ActivationFunction::ABS:
892 out[i] = std::abs(x);
893 break;
894 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
895 out[i] = std::min<T>(a, std::max<T>(0, x));
896 break;
897 case ActivationLayerInfo::ActivationFunction::LINEAR:
898 out[i] = a * x + b;
899 break;
900 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
901 out[i] = static_cast<T>(1) / (static_cast<T>(1) + std::exp(-x));
902 break;
903 case ActivationLayerInfo::ActivationFunction::RELU:
904 out[i] = std::max<T>(0, x);
905 break;
906 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;
945 case ActivationLayerInfo::ActivationFunction::BOUNDED_RELU:
946 out[i] = min(a, max(const_0, x)).raw();
947 break;
948 case ActivationLayerInfo::ActivationFunction::LINEAR:
949 out[i] = add(b, mul(a, x)).raw();
950 break;
951 case ActivationLayerInfo::ActivationFunction::LOGISTIC:
952 out[i] = (const_1 / (const_1 + exp(-x))).raw();
953 break;
954 case ActivationLayerInfo::ActivationFunction::RELU:
955 out[i] = max(const_0, x).raw();
956 break;
957 case ActivationLayerInfo::ActivationFunction::SOFT_RELU:
958 out[i] = log(const_1 + exp(x)).raw();
959 break;
960 case ActivationLayerInfo::ActivationFunction::SQRT:
961 out[i] = (const_1 / inv_sqrt(x)).raw();
962 break;
963 case ActivationLayerInfo::ActivationFunction::SQUARE:
964 out[i] = mul(x, x).raw();
965 break;
966 case ActivationLayerInfo::ActivationFunction::TANH:
967 out[i] = tanh(x).raw();
968 break;
969 default:
970 ARM_COMPUTE_ERROR("Activation function not recognised");
971 break;
972 }
973 }
974}
975
976// Batch Normalization Layer for fixed point type
977template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
978void 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)
979{
980 const int cols = static_cast<int>(in.shape()[0]);
981 const int rows = static_cast<int>(in.shape()[1]);
982 const int depth = static_cast<int>(in.shape()[2]);
983 int upper_dims = in.shape().total_size() / (cols * rows * depth);
984
985 for(int r = 0; r < upper_dims; ++r)
986 {
987 for(int i = 0; i < depth; ++i)
988 {
989 for(int k = 0; k < rows; ++k)
990 {
991 for(int l = 0; l < cols; ++l)
992 {
993 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
994 fixed_point_arithmetic::fixed_point<T> in_qs8(in[pos], fixed_point_position, true);
995 fixed_point_arithmetic::fixed_point<T> var_qs8(var[i], fixed_point_position, true);
996 fixed_point_arithmetic::fixed_point<T> mean_qs8(mean[i], fixed_point_position, true);
997 fixed_point_arithmetic::fixed_point<T> beta_qs8(beta[i], fixed_point_position, true);
998 fixed_point_arithmetic::fixed_point<T> gamma_qs8(gamma[i], fixed_point_position, true);
999 fixed_point_arithmetic::fixed_point<T> epsilon_qs8(epsilon, fixed_point_position);
1000
1001 auto denominator = fixed_point_arithmetic::inv_sqrt(var_qs8 + epsilon_qs8);
1002 auto numerator = in_qs8 - mean_qs8;
1003 auto x_bar = numerator * denominator;
1004 x_bar = beta_qs8 + x_bar * gamma_qs8;
1005 out[pos] = x_bar.raw();
1006 }
1007 }
1008 }
1009 }
1010}
1011
1012// Batch Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001013template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001014void 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)
1015{
1016 const int cols = static_cast<int>(in.shape()[0]);
1017 const int rows = static_cast<int>(in.shape()[1]);
1018 const int depth = static_cast<int>(in.shape()[2]);
1019 int upper_dims = in.shape().total_size() / (cols * rows * depth);
1020
1021 for(int r = 0; r < upper_dims; ++r)
1022 {
1023 for(int i = 0; i < depth; ++i)
1024 {
1025 for(int k = 0; k < rows; ++k)
1026 {
1027 for(int l = 0; l < cols; ++l)
1028 {
1029 const int pos = l + k * cols + i * rows * cols + r * cols * rows * depth;
1030 const float denominator = sqrt(var[i] + epsilon);
1031 const float numerator = in[pos] - mean[i];
1032 const float x_bar = numerator / denominator;
1033 out[pos] = beta[i] + x_bar * gamma[i];
1034 }
1035 }
1036 }
1037 }
1038}
1039
1040// Convolution layer
1041template <typename T>
1042void convolution_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out, const PadStrideInfo &conv_info)
1043{
1044 const int width_in = in.shape().x();
1045 const int height_in = in.shape().y();
1046 const int depth_in = in.shape().z();
1047 const int width_out = out.shape().x();
1048 const int height_out = out.shape().y();
1049 const int depth_out = out.shape().z();
1050 const int width_weights = weights.shape().x();
1051 const int height_weights = weights.shape().y();
1052 const int depth_weights = weights.shape().z();
1053 const int pad_xi = std::min(static_cast<int>(conv_info.pad().first), width_weights / 2);
1054 const int pad_yi = std::min(static_cast<int>(conv_info.pad().second), height_weights / 2);
1055 const int start_xi = width_weights / 2 - pad_xi;
1056 const int start_yi = height_weights / 2 - pad_yi;
1057 const int end_xi = width_in - start_xi;
1058 const int end_yi = height_in - start_yi;
1059 const int stride_xi = conv_info.stride().first;
1060 const int stride_yi = conv_info.stride().second;
1061 const int num_batches = in.shape().total_size() / (width_in * height_in * depth_in);
1062
1063 for(int r = 0; r < num_batches; ++r)
1064 {
1065 for(int yi = start_yi; yi < end_yi; yi += stride_yi)
1066 {
1067 for(int xi = start_xi; xi < end_xi; xi += stride_xi)
1068 {
1069 for(int ofm = 0; ofm < depth_out; ++ofm)
1070 {
1071 // Compute input and output offsets
1072 const int offset_in = r * width_in * height_in * depth_in;
1073 const int xo = (xi - start_xi) / stride_xi;
1074 const int yo = (yi - start_yi) / stride_yi;
1075 const int offset_out = xo + yo * width_out + ofm * width_out * height_out + r * width_out * height_out * depth_out;
1076
1077 // Compute 3D convolution
1078 convolution3d(in.data() + offset_in,
1079 weights.data() + ofm * width_weights * height_weights * depth_weights,
1080 bias.data() + ofm,
1081 out.data() + offset_out,
1082 xi, yi,
1083 width_in, height_in, depth_in,
1084 width_weights, height_weights,
1085 static_cast<int8_t>(in.fixed_point_position()));
1086 }
1087 }
1088 }
1089 }
1090}
1091
1092// Fully connected layer
1093template <typename T>
1094void fully_connected_layer(const Tensor<T> &in, const Tensor<T> &weights, const Tensor<T> &bias, Tensor<T> &out)
1095{
1096 ARM_COMPUTE_ERROR_ON(weights.shape().x() != out.shape().x());
1097 ARM_COMPUTE_ERROR_ON(weights.shape().y() != in.shape().x() * in.shape().y() * in.shape().z());
1098 const int cols_weights = weights.shape().x();
1099 const int rows_weights = weights.shape().y();
1100 const int num_batches = in.shape().total_size() / rows_weights;
1101
1102 for(int k = 0; k < num_batches; ++k)
1103 {
1104 vector_matrix_multiply<T>(in.data() + k * rows_weights,
1105 weights.data(),
1106 bias.data(),
1107 out.data() + k * cols_weights,
1108 cols_weights,
1109 rows_weights,
1110 in.fixed_point_position());
1111 }
1112}
1113
1114// Normalization Layer for floating point type
Pablo Tello383deec2017-06-23 10:40:05 +01001115template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001116void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1117{
1118 const uint32_t norm_size = norm_info.norm_size();
1119 NormType type = norm_info.type();
1120 float beta = norm_info.beta();
1121 uint32_t kappa = norm_info.kappa();
1122
1123 const int cols = static_cast<int>(in.shape()[0]);
1124 const int rows = static_cast<int>(in.shape()[1]);
1125 const int depth = static_cast<int>(in.shape()[2]);
1126 int upper_dims = in.shape().total_size() / (cols * rows);
1127
1128 float coeff = norm_info.scale_coeff();
1129 int radius_cols = norm_size / 2;
1130 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1131 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1132
1133 if(type == NormType::CROSS_MAP)
1134 {
1135 // Remove also depth from upper dimensions since it is the axes we want
1136 // to use for normalization
1137 upper_dims /= depth;
1138 for(int r = 0; r < upper_dims; ++r)
1139 {
1140 for(int i = 0; i < rows; ++i)
1141 {
1142 for(int k = 0; k < cols; ++k)
1143 {
1144 for(int l = 0; l < depth; ++l)
1145 {
1146 float accumulated_scale = 0.f;
1147 for(int j = -radius_cols; j <= radius_cols; ++j)
1148 {
1149 const int z = l + j;
1150 if(z >= 0 && z < depth)
1151 {
1152 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1153 accumulated_scale += value * value;
1154 }
1155 }
1156 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = kappa + accumulated_scale * coeff;
1157 }
1158 }
1159 }
1160 }
1161 }
1162 else
1163 {
1164 for(int r = 0; r < upper_dims; ++r)
1165 {
1166 for(int i = 0; i < rows; ++i)
1167 {
1168 for(int k = 0; k < cols; ++k)
1169 {
1170 float accumulated_scale = 0.f;
1171 for(int j = -radius_rows; j <= radius_rows; ++j)
1172 {
1173 const int y = i + j;
1174 for(int l = -radius_cols; l <= radius_cols; ++l)
1175 {
1176 const int x = k + l;
1177 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1178 {
1179 const T value = in[x + y * cols + r * cols * rows];
1180 accumulated_scale += value * value;
1181 }
1182 }
1183 }
1184 out[k + i * cols + r * cols * rows] = kappa + accumulated_scale * coeff;
1185 }
1186 }
1187 }
1188 }
1189
1190 if(beta == 1.f)
1191 {
1192 for(int i = 0; i < out.num_elements(); ++i)
1193 {
1194 out[i] = in[i] / out[i];
1195 }
1196 }
1197 else if(beta == 0.5f)
1198 {
1199 for(int i = 0; i < out.num_elements(); ++i)
1200 {
1201 out[i] = in[i] / std::sqrt(out[i]);
1202 }
1203 }
1204 else
1205 {
1206 for(int i = 0; i < out.num_elements(); ++i)
1207 {
1208 out[i] = in[i] * std::exp(std::log(out[i]) * -beta);
1209 }
1210 }
1211}
1212// Normalization Layer for fixed-point types
1213template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1214void normalization_layer(const Tensor<T> &in, Tensor<T> &out, NormalizationLayerInfo norm_info)
1215{
1216 using namespace fixed_point_arithmetic;
1217
1218 const int fixed_point_position = in.fixed_point_position();
1219
1220 const uint32_t norm_size = norm_info.norm_size();
1221 NormType type = norm_info.type();
1222 fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1223 fixed_point<T> kappa(norm_info.kappa(), fixed_point_position);
1224
1225 const int cols = static_cast<int>(in.shape()[0]);
1226 const int rows = static_cast<int>(in.shape()[1]);
1227 const int depth = static_cast<int>(in.shape()[2]);
1228 int upper_dims = in.shape().total_size() / (cols * rows);
1229
1230 fixed_point<T> coeff(norm_info.scale_coeff(), fixed_point_position);
1231 int radius_cols = norm_size / 2;
1232 // IN_MAP_1D and CROSS_MAP normalize over a single axis only
1233 int radius_rows = (NormType::IN_MAP_2D == type) ? norm_size / 2 : 0;
1234
1235 if(type == NormType::CROSS_MAP)
1236 {
1237 // Remove also depth from upper dimensions since it is the axes we want
1238 // to use for normalization
1239 upper_dims /= depth;
1240 for(int r = 0; r < upper_dims; ++r)
1241 {
1242 for(int i = 0; i < rows; ++i)
1243 {
1244 for(int k = 0; k < cols; ++k)
1245 {
1246 for(int l = 0; l < depth; ++l)
1247 {
1248 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1249 for(int j = -radius_cols; j <= radius_cols; ++j)
1250 {
1251 const int z = l + j;
1252 if(z >= 0 && z < depth)
1253 {
1254 const T value = in[k + i * cols + z * rows * cols + r * cols * rows * depth];
1255 const fixed_point<T> fp_value(value, fixed_point_position, true);
1256 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1257 }
1258 }
1259 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1260 out[k + i * cols + l * rows * cols + r * cols * rows * depth] = accumulated_scale.raw();
1261 }
1262 }
1263 }
1264 }
1265 }
1266 else
1267 {
1268 for(int r = 0; r < upper_dims; ++r)
1269 {
1270 for(int i = 0; i < rows; ++i)
1271 {
1272 for(int k = 0; k < cols; ++k)
1273 {
1274 fixed_point<T> accumulated_scale(0.f, fixed_point_position);
1275 for(int j = -radius_rows; j <= radius_rows; ++j)
1276 {
1277 const int y = i + j;
1278 for(int l = -radius_cols; l <= radius_cols; ++l)
1279 {
1280 const int x = k + l;
1281 if((x >= 0 && y >= 0) && (x < cols && y < rows))
1282 {
1283 const T value = in[x + y * cols + r * cols * rows];
1284 const fixed_point<T> fp_value(value, fixed_point_position, true);
1285 accumulated_scale = add(accumulated_scale, mul(fp_value, fp_value));
1286 }
1287 }
1288 }
1289 accumulated_scale = add(kappa, mul(accumulated_scale, coeff));
1290 out[k + i * cols + r * cols * rows] = accumulated_scale.raw();
1291 }
1292 }
1293 }
1294 }
1295
1296 if(norm_info.beta() == 1.f)
1297 {
1298 for(int i = 0; i < out.num_elements(); ++i)
1299 {
1300 fixed_point<T> res = div(fixed_point<T>(in[i], fixed_point_position, true), fixed_point<T>(out[i], fixed_point_position, true));
1301 out[i] = res.raw();
1302 }
1303 }
1304 else
1305 {
1306 const fixed_point<T> beta(norm_info.beta(), fixed_point_position);
1307 for(int i = 0; i < out.num_elements(); ++i)
1308 {
1309 fixed_point<T> res = pow(fixed_point<T>(out[i], fixed_point_position, true), beta);
1310 res = div(fixed_point<T>(in[i], fixed_point_position, true), res);
1311 out[i] = res.raw();
1312 }
1313 }
1314}
1315
1316// Pooling layer
1317template <typename T>
1318void pooling_layer(const Tensor<T> &in, Tensor<T> &out, PoolingLayerInfo pool_info, int fixed_point_position)
1319{
1320 const int pool_size = pool_info.pool_size();
1321 PoolingType type = pool_info.pool_type();
1322 int pool_stride_x = 0;
1323 int pool_stride_y = 0;
1324 int pad_x = 0;
1325 int pad_y = 0;
1326 std::tie(pool_stride_x, pool_stride_y) = pool_info.pad_stride_info().stride();
1327 std::tie(pad_x, pad_y) = pool_info.pad_stride_info().pad();
1328
Georgios Pinitasce093142017-06-19 16:11:53 +01001329 const int w_in = static_cast<int>(in.shape()[0]);
1330 const int h_in = static_cast<int>(in.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001331
Georgios Pinitasce093142017-06-19 16:11:53 +01001332 const int w_out = static_cast<int>(out.shape()[0]);
1333 const int h_out = static_cast<int>(out.shape()[1]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001334
Georgios Pinitasce093142017-06-19 16:11:53 +01001335 int upper_dims = in.shape().total_size() / (w_in * h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001336
Georgios Pinitasce093142017-06-19 16:11:53 +01001337 int pooled_w = 0;
1338 int pooled_h = 0;
1339 if(pool_info.pad_stride_info().round() == DimensionRoundingType::CEIL)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001340 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001341 pooled_w = static_cast<int>(ceil(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1342 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 +01001343 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001344 else
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001345 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001346 pooled_w = static_cast<int>(floor(static_cast<float>(w_in + 2 * pad_x - pool_size) / pool_stride_x)) + 1;
1347 pooled_h = static_cast<int>(floor(static_cast<float>(h_in + 2 * pad_y - pool_size) / pool_stride_y)) + 1;
1348 }
1349
1350 if((pooled_w - 1) * pool_stride_x >= w_in + pad_x)
1351 {
1352 --pooled_w;
1353 }
1354 if((pooled_h - 1) * pool_stride_y >= h_in + pad_y)
1355 {
1356 --pooled_h;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001357 }
1358
1359 if(type == PoolingType::MAX)
1360 {
1361 for(int r = 0; r < upper_dims; ++r)
1362 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001363 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001364 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001365 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001366 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001367 int wstart = w * pool_stride_x - pad_x;
1368 int hstart = h * pool_stride_y - pad_y;
1369 int wend = std::min(wstart + pool_size, w_in);
1370 int hend = std::min(hstart + pool_size, h_in);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001371 wstart = std::max(wstart, 0);
Georgios Pinitasce093142017-06-19 16:11:53 +01001372 hstart = std::max(hstart, 0);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001373
1374 T max_val = std::numeric_limits<T>::lowest();
1375 for(int y = hstart; y < hend; ++y)
1376 {
1377 for(int x = wstart; x < wend; ++x)
1378 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001379 T val = in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001380 if(val > max_val)
1381 {
1382 max_val = val;
1383 }
1384 }
1385 }
1386
Georgios Pinitasce093142017-06-19 16:11:53 +01001387 out[r * h_out * w_out + h * pooled_w + w] = max_val;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001388 }
1389 }
1390 }
1391 }
1392 else // Average pooling
1393 {
1394 for(int r = 0; r < upper_dims; ++r)
1395 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001396 for(int h = 0; h < pooled_h; ++h)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001397 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001398 for(int w = 0; w < pooled_w; ++w)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001399 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001400 T avg_val = 0;
1401 int wstart = w * pool_stride_x - pad_x;
1402 int hstart = h * pool_stride_y - pad_y;
1403 int wend = std::min(wstart + pool_size, w_in + pad_x);
1404 int hend = std::min(hstart + pool_size, h_in + pad_y);
1405 int pool = (hend - hstart) * (wend - wstart);
1406 wstart = std::max(wstart, 0);
1407 hstart = std::max(hstart, 0);
1408 wend = std::min(wend, w_in);
1409 hend = std::min(hend, h_in);
Pablo Tello383deec2017-06-23 10:40:05 +01001410 if(is_floating_point<T>::value)
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001411 {
1412 for(int y = hstart; y < hend; ++y)
1413 {
1414 for(int x = wstart; x < wend; ++x)
1415 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001416 avg_val += in[r * h_in * w_in + y * w_in + x];
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001417 }
1418 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001419 out[r * h_out * w_out + h * pooled_w + w] = avg_val / pool;
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001420 }
1421 else
1422 {
1423 static std::array<qint8_t, 10> scale_values_q8 =
1424 { { 0x0, 0x0, 0x40, 0x2A, 0x20, 0x19, 0x15, 0x12, 0x10, 0xE } };
1425
1426 for(int y = hstart; y < hend; ++y)
1427 {
1428 for(int x = wstart; x < wend; ++x)
1429 {
Georgios Pinitasce093142017-06-19 16:11:53 +01001430 avg_val = sqadd_qs8(avg_val, in[r * h_in * w_in + y * w_in + x]);
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001431 }
1432 }
Georgios Pinitasce093142017-06-19 16:11:53 +01001433 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 +01001434 }
1435 }
1436 }
1437 }
1438 }
1439}
1440
1441// Softmax Layer
Pablo Tello383deec2017-06-23 10:40:05 +01001442template <typename T, typename std::enable_if<is_floating_point<T>::value, int>::type * = nullptr>
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001443void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1444{
1445 const int cols = static_cast<int>(in.shape()[0]);
1446 const int upper_dims = in.shape().total_size() / cols;
1447 for(int r = 0; r < upper_dims; ++r)
1448 {
1449 // Find max
1450 T max = std::numeric_limits<T>::lowest();
1451 for(int c = 0; c < cols; ++c)
1452 {
1453 const T x = in[r * cols + c];
1454 if(x > max)
1455 {
1456 max = x;
1457 }
1458 }
1459
1460 // Regularize
1461 T sum = 0;
1462 for(int c = 0; c < cols; ++c)
1463 {
1464 const T res = exp(in[r * cols + c] - max);
1465 out[r * cols + c] = res;
1466 sum += res;
1467 }
1468
1469 // Normalize
1470 const T norm_val = 1 / sum;
1471 for(int c = 0; c < cols; ++c)
1472 {
1473 out[r * cols + c] *= norm_val;
1474 }
1475 }
1476}
1477template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type * = nullptr>
1478void softmax_layer(const Tensor<T> &in, Tensor<T> &out)
1479{
1480 using namespace fixed_point_arithmetic;
1481 using promoted_T = typename test::traits::promote<T>::type;
1482
1483 const int fixed_point_position = in.fixed_point_position();
1484 const int cols = static_cast<int>(in.shape()[0]);
1485 const int upper_dims = in.shape().total_size() / cols;
1486
1487 for(int r = 0; r < upper_dims; ++r)
1488 {
1489 // Find max
1490 fixed_point<T> max(std::numeric_limits<T>::lowest(), fixed_point_position, true);
1491 for(int c = 0; c < cols; ++c)
1492 {
1493 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1494 if(x > max)
1495 {
1496 max = x;
1497 }
1498 }
1499
1500 // Regularize
1501 fixed_point<promoted_T> sum(0, fixed_point_position);
1502 for(int c = 0; c < cols; ++c)
1503 {
1504 const fixed_point<T> x(in[r * cols + c], fixed_point_position, true);
1505 fixed_point<T> res = exp(x - max);
1506 out[r * cols + c] = res.raw();
1507 sum = add(sum, static_cast<fixed_point<promoted_T>>(res));
1508 }
1509
1510 // Normalize
1511 fixed_point<T> sat_sum(sum);
1512 for(int c = 0; c < cols; ++c)
1513 {
1514 const fixed_point<T> x(out[r * cols + c], fixed_point_position, true);
1515 out[r * cols + c] = div(x, sat_sum).raw();
1516 }
1517 }
1518}
1519
1520// Fixed point operations
1521template <typename T>
1522void fixed_point_operation(const Tensor<T> &in, Tensor<T> &out, FixedPointOp op)
1523{
1524 int p = in.fixed_point_position();
1525 switch(op)
1526 {
1527 case FixedPointOp::EXP:
1528 for(int i = 0; i < in.num_elements(); ++i)
1529 {
1530 out[i] = fixed_point_arithmetic::exp(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1531 }
1532 break;
1533 case FixedPointOp::LOG:
1534 for(int i = 0; i < in.num_elements(); ++i)
1535 {
1536 out[i] = fixed_point_arithmetic::log(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1537 }
1538 break;
1539 case FixedPointOp::INV_SQRT:
1540 for(int i = 0; i < in.num_elements(); ++i)
1541 {
1542 out[i] = fixed_point_arithmetic::inv_sqrt(fixed_point_arithmetic::fixed_point<T>(in[i], p, true)).raw();
1543 }
1544 break;
1545 case FixedPointOp::RECIPROCAL:
1546 for(int i = 0; i < in.num_elements(); ++i)
1547 {
1548 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();
1549 }
1550 break;
1551 default:
1552 ARM_COMPUTE_ERROR("Fixed point operation not supported");
1553 break;
1554 }
1555}
1556
1557// Tensor print
1558template <typename T>
1559void print(const Tensor<T> &in, std::ostream &out)
1560{
1561 out << "\n";
1562 for(int i = 0; i < in.num_elements(); ++i)
1563 {
1564 out << in[i] << " ";
1565 }
1566 out << "\n";
1567}
1568} // namespace tensor_operations
1569} // namespace validation
1570} // namespace test
1571} // namespace arm_compute
1572
1573#endif /* __ARM_COMPUTE_TEST_TENSOR_OPERATIONS_H__ */