Imported Upstream version 1.12.0
[platform/core/ml/nnfw.git] / compute / ARMComputeEx / src / core / CL / kernels / CLInstanceNormalizationLayerKernelEx.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/CL/kernels/CLInstanceNormalizationLayerKernelEx.h"
42
43 #include "arm_compute/core/CL/CLHelpers.h"
44 #include "arm_compute/core/CL/CLKernelLibraryEx.h"
45 #include "arm_compute/core/CL/CLValidate.h"
46 #include "arm_compute/core/CL/ICLTensor.h"
47 #include "arm_compute/core/Helpers.h"
48 #include "arm_compute/core/TensorInfo.h"
49 #include "arm_compute/core/Utils.h"
50 #include "arm_compute/core/Window.h"
51 #include "support/StringSupport.h"
52 #include "support/ToolchainSupport.h"
53
54 namespace arm_compute
55 {
56 namespace
57 {
58 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output,
59                           const ITensorInfo *gamma, const ITensorInfo *beta, float epsilon)
60 {
61   ARM_COMPUTE_UNUSED(gamma);
62   ARM_COMPUTE_UNUSED(beta);
63   ARM_COMPUTE_RETURN_ERROR_ON_MSG(epsilon == 0.f, "Epsilon must be different than 0");
64
65   ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(input, DataType::F16, DataType::F32);
66
67   if (output != nullptr && output->total_size() != 0)
68   {
69     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input, output);
70     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
71     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input, output);
72     ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->num_channels() != output->num_channels(),
73                                     "Input and output have different number of channels");
74   }
75
76   return Status{};
77 }
78
79 std::tuple<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output)
80 {
81   // We handle the planes manually
82   Window win = calculate_max_window(*input, Steps(1));
83
84   // Output auto initialization if not yet initialized
85   auto_init_if_empty(*output, input->tensor_shape(), 1, input->data_type());
86
87   // CLInstanceNormalizationLayerKernelEx doesn't need padding so update_window_and_padding() can be
88   // skipped
89   Coordinates coord;
90   coord.set_num_dimensions(output->num_dimensions());
91   output->set_valid_region(ValidRegion(coord, output->tensor_shape()));
92   return std::make_pair(Status{}, win);
93 }
94 } // namespace
95
96 CLInstanceNormalizationLayerKernelEx::CLInstanceNormalizationLayerKernelEx()
97   : _input(nullptr), _output(nullptr), _gamma(nullptr), _beta(nullptr), _epsilon(1e-12),
98     _run_in_place(false)
99 {
100 }
101
102 void CLInstanceNormalizationLayerKernelEx::configure(ICLTensor *input, ICLTensor *output,
103                                                      ICLTensor *gamma, ICLTensor *beta,
104                                                      float epsilon)
105 {
106   ARM_COMPUTE_ERROR_ON_NULLPTR(input);
107
108   _input = input;
109   _output = output == nullptr ? input : output;
110   _gamma = gamma;
111   _beta = beta;
112   _epsilon = epsilon;
113
114   _run_in_place = (output == nullptr) || (output == input);
115   ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(_input->info(), _output->info(),
116                                                 gamma ? gamma->info() : nullptr,
117                                                 beta ? beta->info() : nullptr, epsilon));
118   const unsigned int num_elems_processed_per_iteration = 16 / input->info()->element_size();
119
120   CLBuildOptions build_opts;
121   build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
122   build_opts.add_option("-DVEC_SIZE=" +
123                         support::cpp11::to_string(num_elems_processed_per_iteration));
124   build_opts.add_option("-DDIM_X=" + support::cpp11::to_string(input->info()->dimension(0)));
125   build_opts.add_option("-DDIM_Y=" + support::cpp11::to_string(input->info()->dimension(1)));
126   build_opts.add_option("-DDIM_Z=" + support::cpp11::to_string(input->info()->dimension(2)));
127   build_opts.add_option("-DEPSILON=" + float_to_string_with_full_precision(epsilon));
128   build_opts.add_option_if(gamma, "-DGAMMA");
129   build_opts.add_option_if(beta, "-DBETA");
130   build_opts.add_option_if(_run_in_place, "-DIN_PLACE");
131   build_opts.add_option_if(_input->info()->data_layout() == DataLayout::NHWC, "-DNHWC");
132
133   // Create kernel
134   _kernel = static_cast<cl::Kernel>(
135     CLKernelLibraryEx::get().create_kernel("instance_normalization_ex", build_opts.options()));
136
137   // Configure kernel window
138   auto win_config = validate_and_configure_window(_input->info(), _output->info());
139   ARM_COMPUTE_ERROR_THROW_ON(std::get<0>(win_config));
140   ICLKernel::configure_internal(std::get<1>(win_config));
141 }
142
143 Status CLInstanceNormalizationLayerKernelEx::validate(const ITensorInfo *input,
144                                                       const ITensorInfo *output,
145                                                       const ITensorInfo *gamma,
146                                                       const ITensorInfo *beta, float epsilon)
147 {
148   ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, gamma, beta, epsilon));
149   ARM_COMPUTE_RETURN_ON_ERROR(std::get<0>(validate_and_configure_window(
150     input->clone().get(), (output == nullptr ? input->clone().get() : output->clone().get()))));
151   return Status{};
152 }
153
154 void CLInstanceNormalizationLayerKernelEx::run(const Window &window, cl::CommandQueue &queue)
155 {
156   ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
157   ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window);
158
159   Window collapsed_window = window.collapse(window, Window::DimZ);
160
161   // We will process the planes together
162   if (_input->info()->data_layout() == DataLayout::NCHW)
163   {
164     collapsed_window.set(Window::DimX, Window::Dimension(0, 1, 1));
165     collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
166   }
167   else
168   {
169     collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
170     collapsed_window.set(Window::DimZ, Window::Dimension(0, _input->info()->dimension(3), 1));
171   }
172
173   Window vec_window;
174   vec_window.set(Window::DimX, Window::Dimension(0, 0, 0));
175
176   unsigned int idx = 0;
177   add_4D_tensor_argument(idx, _input, collapsed_window);
178   if (!_run_in_place)
179   {
180     add_4D_tensor_argument(idx, _output, collapsed_window);
181   }
182   if (_gamma)
183   {
184     add_1D_tensor_argument(idx, _gamma, vec_window);
185   }
186   if (_beta)
187   {
188     add_1D_tensor_argument(idx, _beta, vec_window);
189   }
190
191   enqueue(queue, *this, collapsed_window, lws_hint());
192 }
193 } // namespace arm_compute