49adf14626e933d0ca77e4e87432419444cf36ac
[platform/core/ml/nnfw.git] / compute / ARMComputeEx / src / core / NEON / kernels / NEInstanceNormalizationLayerKernelEx.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * Copyright (c) 2019 ARM Limited.
19  *
20  * SPDX-License-Identifier: MIT
21  *
22  * Permission is hereby granted, free of charge, to any person obtaining a copy
23  * of this software and associated documentation files (the "Software"), to
24  * deal in the Software without restriction, including without limitation the
25  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
26  * sell copies of the Software, and to permit persons to whom the Software is
27  * furnished to do so, subject to the following conditions:
28  *
29  * The above copyright notice and this permission notice shall be included in all
30  * copies or substantial portions of the Software.
31  *
32  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38  * SOFTWARE.
39  */
40
41 #include "arm_compute/core/NEON/kernels/NEInstanceNormalizationLayerKernelEx.h"
42
43 #include "arm_compute/core/CPP/Validate.h"
44 #include "arm_compute/core/Error.h"
45 #include "arm_compute/core/Helpers.h"
46 #include "arm_compute/core/ITensor.h"
47 #include "arm_compute/core/NEON/NEMath.h"
48 #include "arm_compute/core/NEON/wrapper/wrapper.h"
49 #include "arm_compute/core/TensorInfo.h"
50 #include "arm_compute/core/Utils.h"
51 #include "arm_compute/core/Validate.h"
52 #include "arm_compute/core/Window.h"
53
54 #include <arm_neon.h>
55
56 namespace arm_compute
57 {
58 namespace
59 {
60 template <typename T>
61 void instance_normalization_nchw(ITensor *input, ITensor *output, ITensor *gamma, ITensor *beta,
62                                  float epsilon, const Window &window)
63 {
64   /** NEON vector tag type. */
65   using ExactTagType =
66       typename wrapper::traits::neon_bitvector_tag_t<T, wrapper::traits::BitWidth::W128>;
67
68   // Clear X/Y dimensions on execution window as we handle the planes manually
69   Window win = window;
70   win.set(Window::DimX, Window::Dimension(0, 1, 1));
71   win.set(Window::DimY, Window::Dimension(0, 1, 1));
72
73   constexpr int window_step_x = 16 / sizeof(T);
74   const unsigned int elements_plane = input->info()->dimension(0) * output->info()->dimension(1);
75   const auto channel_idx =
76       get_data_layout_dimension_index(input->info()->data_layout(), DataLayoutDimension::CHANNEL);
77
78   Iterator input_it(input, win);
79   execute_window_loop(
80       win,
81       [&](const Coordinates &id) {
82         Window win_plane = window;
83         win_plane.set(Window::DimX, Window::Dimension(0, 1, 1));
84         win_plane.set(Window::DimZ, Window::Dimension(id[2], id[2] + 1, 1));
85         win_plane.set(3, Window::Dimension(id[3], id[3] + 1, 1));
86
87         Iterator input_plane_it(input, win_plane);
88         Iterator output_plane_it(output, win_plane);
89
90         auto sum_h_w = static_cast<T>(0.f);
91         auto sum_squares_h_w = static_cast<T>(0.f);
92
93         execute_window_loop(
94             win_plane,
95             [&](const Coordinates &) {
96               const auto input_ptr = reinterpret_cast<const T *>(input_plane_it.ptr());
97
98               auto vec_sum_h_w = wrapper::vdup_n(static_cast<T>(0.f), ExactTagType{});
99               auto vec_sum_squares_h_w = wrapper::vdup_n(static_cast<T>(0.f), ExactTagType{});
100
101               // Compute S elements per iteration
102               int x = window.x().start();
103               for (; x <= (window.x().end() - window_step_x); x += window_step_x)
104               {
105                 auto vec_input_val = wrapper::vloadq(input_ptr + x);
106                 vec_sum_h_w = wrapper::vadd(vec_sum_h_w, vec_input_val);
107                 vec_sum_squares_h_w =
108                     wrapper::vadd(vec_sum_squares_h_w, wrapper::vmul(vec_input_val, vec_input_val));
109               }
110
111               auto vec2_sum_h_w =
112                   wrapper::vpadd(wrapper::vgethigh(vec_sum_h_w), wrapper::vgetlow(vec_sum_h_w));
113               auto vec2_sum_squares_h_w = wrapper::vpadd(wrapper::vgethigh(vec_sum_squares_h_w),
114                                                          wrapper::vgetlow(vec_sum_squares_h_w));
115               for (int i = 0; i < window_step_x / 4; ++i)
116               {
117                 vec2_sum_h_w = wrapper::vpadd(vec2_sum_h_w, vec2_sum_h_w);
118                 vec2_sum_squares_h_w = wrapper::vpadd(vec2_sum_squares_h_w, vec2_sum_squares_h_w);
119               }
120               sum_h_w += wrapper::vgetlane(vec2_sum_h_w, 0);
121               sum_squares_h_w += wrapper::vgetlane(vec2_sum_squares_h_w, 0);
122
123               // Compute left-over elements
124               for (; x < window.x().end(); ++x)
125               {
126                 const auto value = *(input_ptr + x);
127                 sum_h_w += value;
128                 sum_squares_h_w += value * value;
129               }
130             },
131             input_plane_it, output_plane_it);
132
133         const auto mean_h_w = sum_h_w / elements_plane;
134         const auto var_h_w = sum_squares_h_w / elements_plane - mean_h_w * mean_h_w;
135
136         auto gamma_val = 1.0f;
137         if (gamma != nullptr)
138         {
139           gamma_val = *reinterpret_cast<T *>(gamma->ptr_to_element({id[channel_idx]}));
140         }
141         const auto multip_h_w = gamma_val / std::sqrt(var_h_w + epsilon);
142         const auto vec_mean_h_w = wrapper::vdup_n(static_cast<T>(mean_h_w), ExactTagType{});
143         const auto vec_multip_h_w = wrapper::vdup_n(static_cast<T>(multip_h_w), ExactTagType{});
144         auto beta_val = 0.0f;
145         if (beta != nullptr)
146         {
147           beta_val = *reinterpret_cast<T *>(beta->ptr_to_element({id[channel_idx]}));
148         }
149         const auto vec_beta = wrapper::vdup_n(static_cast<T>(beta_val), ExactTagType{});
150
151         execute_window_loop(
152             win_plane,
153             [&](const Coordinates &) {
154               auto input_ptr = reinterpret_cast<T *>(input_plane_it.ptr());
155               auto output_ptr = reinterpret_cast<T *>(output_plane_it.ptr());
156
157               // Compute S elements per iteration
158               int x = window.x().start();
159               auto vec_val = wrapper::vdup_n(static_cast<T>(0.0f), ExactTagType{});
160               for (; x <= (window.x().end() - window_step_x); x += window_step_x)
161               {
162                 vec_val = wrapper::vloadq(input_ptr + x);
163                 vec_val = wrapper::vadd(
164                     wrapper::vmul(wrapper::vsub(vec_val, vec_mean_h_w), vec_multip_h_w), vec_beta);
165                 wrapper::vstore(output_ptr + x, vec_val);
166               }
167
168               // Compute left-over elements
169               for (; x < window.x().end(); ++x)
170               {
171                 *(output_ptr + x) = ((*(input_ptr + x)) - mean_h_w) * multip_h_w + beta_val;
172               }
173             },
174             input_plane_it, output_plane_it);
175       },
176       input_it);
177 }
178
179 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output,
180                           const ITensorInfo *gamma, const ITensorInfo *beta, float epsilon)
181 {
182   ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(input);
183   ARM_COMPUTE_RETURN_ERROR_ON_MSG(epsilon == 0.f, "Epsilon must be different than 0");
184
185   ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(input, DataType::F16, DataType::F32);
186   ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->data_layout() == DataLayout::NHWC,
187                                   "NHWC data layout is not supported by the kernel directly");
188
189   if (output != nullptr && output->total_size() != 0)
190   {
191     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input, output);
192     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
193     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input, output);
194     ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->num_channels() != output->num_channels(),
195                                     "Input and output have different number of channels");
196   }
197
198   if (gamma != nullptr)
199   {
200     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, gamma);
201     ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->dimension(get_data_layout_dimension_index(
202                                         input->data_layout(), DataLayoutDimension::CHANNEL)) !=
203                                         gamma->dimension(0),
204                                     "Gamma's size must be the same as size of input's channel");
205   }
206
207   if (beta != nullptr)
208   {
209     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, beta);
210     ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->dimension(get_data_layout_dimension_index(
211                                         input->data_layout(), DataLayoutDimension::CHANNEL)) !=
212                                         beta->dimension(0),
213                                     "Beta's size must be the same as size of input's channel");
214   }
215
216   return Status{};
217 }
218
219 std::tuple<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output)
220 {
221   // We handle the planes manually
222   Window win = calculate_max_window(*input, Steps(1));
223
224   // Output auto initialization if not yet initialized
225   auto_init_if_empty(*output, input->tensor_shape(), 1, input->data_type());
226
227   // NEInstanceNormalizationLayerKernelEx doesn't need padding so update_window_and_padding() can be
228   // skipped
229   Coordinates coord;
230   coord.set_num_dimensions(output->num_dimensions());
231   output->set_valid_region(ValidRegion(coord, output->tensor_shape()));
232   return std::make_pair(Status{}, win);
233 }
234 } // namespace
235
236 NEInstanceNormalizationLayerKernelEx::NEInstanceNormalizationLayerKernelEx()
237     : _func(nullptr), _input(nullptr), _output(nullptr), _gamma(nullptr), _beta(nullptr),
238       _epsilon(1e-12)
239 {
240 }
241
242 void NEInstanceNormalizationLayerKernelEx::configure(ITensor *input, ITensor *output,
243                                                      ITensor *gamma, ITensor *beta, float epsilon)
244 {
245   ARM_COMPUTE_ERROR_ON_NULLPTR(input);
246
247   _input = input;
248   _output = output == nullptr ? input : output;
249   _gamma = gamma;
250   _beta = beta;
251   _epsilon = epsilon;
252
253   ARM_COMPUTE_ERROR_THROW_ON(
254       validate_arguments(_input->info(), _output->info(), gamma->info(), beta->info(), epsilon));
255
256   if (_input->info()->data_type() == DataType::F32)
257   {
258     _func = &instance_normalization_nchw<float>;
259   }
260 #ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
261   else if (_input->info()->data_type() == DataType::F16)
262   {
263     _func = &instance_normalization_nchw<float16_t>;
264   }
265 #endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
266   else
267   {
268     ARM_COMPUTE_ERROR("Unsupported data type");
269   }
270
271   // Configure kernel window
272   auto win_config = validate_and_configure_window(_input->info(), _output->info());
273   ARM_COMPUTE_ERROR_THROW_ON(std::get<0>(win_config));
274
275   INEKernel::configure(std::get<1>(win_config));
276 }
277
278 Status NEInstanceNormalizationLayerKernelEx::validate(const ITensorInfo *input,
279                                                       const ITensorInfo *output,
280                                                       const ITensorInfo *gamma,
281                                                       const ITensorInfo *beta, float epsilon)
282 {
283   ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, gamma, beta, epsilon));
284   ARM_COMPUTE_RETURN_ON_ERROR(std::get<0>(validate_and_configure_window(
285       input->clone().get(), (output == nullptr ? input->clone().get() : output->clone().get()))));
286   return Status{};
287 }
288
289 void NEInstanceNormalizationLayerKernelEx::run(const Window &window, const ThreadInfo &info)
290 {
291   ARM_COMPUTE_UNUSED(info);
292   ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
293   ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
294   (*_func)(_input, _output, _gamma, _beta, _epsilon, window);
295 }
296 } // namespace arm_compute