xref: /aosp_15_r20/external/ComputeLibrary/src/core/CL/kernels/CLBatchNormalizationLayerKernel.cpp (revision c217d954acce2dbc11938adb493fc0abd69584f3)
1 /*
2  * Copyright (c) 2017-2021 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 #include "src/core/CL/kernels/CLBatchNormalizationLayerKernel.h"
25 
26 #include "arm_compute/core/CL/CLHelpers.h"
27 #include "arm_compute/core/CL/CLKernelLibrary.h"
28 #include "arm_compute/core/CL/ICLTensor.h"
29 #include "arm_compute/core/Helpers.h"
30 #include "arm_compute/core/TensorInfo.h"
31 #include "arm_compute/core/Utils.h"
32 #include "src/core/CL/CLValidate.h"
33 #include "src/core/helpers/AutoConfiguration.h"
34 #include "src/core/helpers/WindowHelpers.h"
35 
36 #include "support/StringSupport.h"
37 
38 using namespace arm_compute;
39 
40 namespace
41 {
validate_arguments(const ITensorInfo * input,const ITensorInfo * output,const ITensorInfo * mean,const ITensorInfo * var,const ITensorInfo * beta,const ITensorInfo * gamma,float epsilon,ActivationLayerInfo act_info)42 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output,
43                           const ITensorInfo *mean, const ITensorInfo *var,
44                           const ITensorInfo *beta, const ITensorInfo *gamma,
45                           float epsilon, ActivationLayerInfo act_info)
46 {
47     ARM_COMPUTE_UNUSED(epsilon);
48     ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(input);
49     ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::F16, DataType::F32);
50     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(mean, var);
51     ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, mean, var);
52     ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(get_data_layout_dimension_index(input->data_layout(), DataLayoutDimension::CHANNEL)) != mean->dimension(0));
53     if(beta != nullptr)
54     {
55         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(mean, beta);
56         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, beta);
57     }
58     if(gamma != nullptr)
59     {
60         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(mean, gamma);
61         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, gamma);
62     }
63 
64     if(act_info.enabled())
65     {
66         ActivationLayerInfo::ActivationFunction act = act_info.activation();
67         ARM_COMPUTE_RETURN_ERROR_ON(input->data_type() != DataType::F32 && input->data_type() != DataType::F16);
68         ARM_COMPUTE_RETURN_ERROR_ON(act != ActivationLayerInfo::ActivationLayerInfo::ActivationFunction::RELU
69                                     && act != ActivationLayerInfo::ActivationLayerInfo::ActivationFunction::BOUNDED_RELU
70                                     && act != ActivationLayerInfo::ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
71         ARM_COMPUTE_RETURN_ERROR_ON(act_info.b() > act_info.a());
72     }
73 
74     if(output != nullptr && output->total_size() != 0)
75     {
76         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input, output);
77         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input, output);
78         ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
79     }
80 
81     return Status{};
82 }
83 
validate_and_configure_window_nchw(ITensorInfo * input,ITensorInfo * output)84 std::pair<Status, Window> validate_and_configure_window_nchw(ITensorInfo *input, ITensorInfo *output)
85 {
86     const unsigned int num_elems_processed_per_iteration = adjust_vec_size(16 / input->element_size(), input->dimension(0));
87 
88     // Configure kernel window
89     Window                 win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration));
90     AccessWindowHorizontal input_access(input, 0, num_elems_processed_per_iteration);
91 
92     bool window_changed = false;
93     if(output != nullptr)
94     {
95         AccessWindowHorizontal output_access(output, 0, num_elems_processed_per_iteration);
96         window_changed = update_window_and_padding(win, input_access, output_access);
97         output_access.set_valid_region(win, input->valid_region());
98     }
99     else
100     {
101         window_changed = update_window_and_padding(win, input_access);
102     }
103 
104     Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
105     return std::make_pair(err, win);
106 }
107 } // namespace
108 
CLBatchNormalizationLayerKernel()109 CLBatchNormalizationLayerKernel::CLBatchNormalizationLayerKernel()
110     : _input(nullptr), _output(nullptr), _mean(nullptr), _var(nullptr), _beta(nullptr), _gamma(nullptr), _epsilon(0), _run_in_place(false)
111 {
112     _type = CLKernelType::ELEMENTWISE;
113 }
114 
configure(ICLTensor * input,ICLTensor * output,const ICLTensor * mean,const ICLTensor * var,const ICLTensor * beta,const ICLTensor * gamma,float epsilon,ActivationLayerInfo act_info)115 void CLBatchNormalizationLayerKernel::configure(ICLTensor *input, ICLTensor *output, const ICLTensor *mean, const ICLTensor *var, const ICLTensor *beta, const ICLTensor *gamma,
116                                                 float epsilon, ActivationLayerInfo act_info)
117 {
118     configure(CLKernelLibrary::get().get_compile_context(), input, output, mean, var, beta, gamma, epsilon, act_info);
119 }
120 
configure(const CLCompileContext & compile_context,ICLTensor * input,ICLTensor * output,const ICLTensor * mean,const ICLTensor * var,const ICLTensor * beta,const ICLTensor * gamma,float epsilon,ActivationLayerInfo act_info)121 void CLBatchNormalizationLayerKernel::configure(const CLCompileContext &compile_context, ICLTensor *input, ICLTensor *output, const ICLTensor *mean, const ICLTensor *var, const ICLTensor *beta,
122                                                 const ICLTensor *gamma,
123                                                 float epsilon, ActivationLayerInfo act_info)
124 {
125     ARM_COMPUTE_ERROR_ON_NULLPTR(input, mean, var);
126 
127     auto padding_info = get_padding_info({ input, output, mean, var, beta, gamma });
128     _input            = input;
129     _output           = output;
130     _mean             = mean;
131     _var              = var;
132     _beta             = beta;
133     _gamma            = gamma;
134     _epsilon          = epsilon;
135 
136     _run_in_place = (output == nullptr) || (output == input);
137 
138     ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), (output != nullptr) ? output->info() : nullptr,
139                                                   mean->info(), var->info(), (beta != nullptr) ? beta->info() : nullptr,
140                                                   (gamma != nullptr) ? gamma->info() : nullptr, epsilon, act_info));
141 
142     unsigned int num_elems_processed_per_iteration = adjust_vec_size(16 / input->info()->element_size(), input->info()->dimension(0));
143 
144     // Set build options
145     CLBuildOptions build_opts;
146     build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
147     build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration));
148     build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(input->info()->dimension(0) % num_elems_processed_per_iteration));
149     build_opts.add_option("-DACTIVATION_TYPE=" + lower_string(string_from_activation_func(act_info.activation())));
150     build_opts.add_option_if(act_info.enabled(), "-DA_VAL=" + float_to_string_with_full_precision(act_info.a()));
151     build_opts.add_option_if(act_info.enabled(), "-DB_VAL=" + float_to_string_with_full_precision(act_info.b()));
152     build_opts.add_option_if(_run_in_place, "-DIN_PLACE");
153     build_opts.add_option_if(beta == nullptr, "-DUSE_DEFAULT_BETA");
154     build_opts.add_option_if(gamma == nullptr, "-DUSE_DEFAULT_GAMMA");
155 
156     // Create kernel
157     _kernel = create_kernel(compile_context, "batchnormalization_layer_" + lower_string(string_from_data_layout(input->info()->data_layout())), build_opts.options());
158 
159     // Set kernel static arguments
160     unsigned int include_output = (!_run_in_place) ? 1 : 0;
161     unsigned int idx            = (1 + include_output) * num_arguments_per_3D_tensor() + 2 * num_arguments_per_1D_tensor(); // Skip the input and output parameters
162     if(_beta != nullptr)
163     {
164         idx += num_arguments_per_1D_tensor(); // Skip beta parameter
165     }
166     if(_gamma != nullptr)
167     {
168         idx += num_arguments_per_1D_tensor(); // Skip gamma parameter
169     }
170     _kernel.setArg<cl_float>(idx++, _epsilon);
171 
172     if(output != nullptr)
173     {
174         // Output tensor auto initialization if not yet initialized
175         auto_init_if_empty(*output->info(), *input->info()->clone());
176     }
177 
178     // Configure kernel window
179     if(input->info()->data_layout() == DataLayout::NHWC)
180     {
181         Window win = calculate_max_window(*input->info(), Steps(num_elems_processed_per_iteration));
182         ICLKernel::configure_internal(win);
183     }
184     else
185     {
186         auto win_config = validate_and_configure_window_nchw(input->info(), (_run_in_place) ? nullptr : output->info());
187         ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
188         ICLKernel::configure_internal(win_config.second);
189     }
190 
191     ARM_COMPUTE_ERROR_ON(input->info()->data_layout() == DataLayout::NHWC && has_padding_changed(padding_info));
192 
193     _config_id = "batch_normalization_layer_";
194     _config_id += string_from_data_type(input->info()->data_type());
195     _config_id += "_";
196     _config_id += support::cpp11::to_string(input->info()->dimension(0));
197     _config_id += "_";
198     _config_id += support::cpp11::to_string(input->info()->dimension(1));
199     _config_id += "_";
200     _config_id += support::cpp11::to_string(input->info()->dimension(2));
201     _config_id += "_";
202     _config_id += lower_string(string_from_data_layout(input->info()->data_layout()));
203 }
204 
validate(const ITensorInfo * input,const ITensorInfo * output,const ITensorInfo * mean,const ITensorInfo * var,const ITensorInfo * beta,const ITensorInfo * gamma,float epsilon,ActivationLayerInfo act_info)205 Status CLBatchNormalizationLayerKernel::validate(const ITensorInfo *input, const ITensorInfo *output,
206                                                  const ITensorInfo *mean, const ITensorInfo *var,
207                                                  const ITensorInfo *beta, const ITensorInfo *gamma,
208                                                  float epsilon, ActivationLayerInfo act_info)
209 {
210     const bool run_in_place = (output == nullptr) || (output == input);
211     ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, mean, var, beta, gamma, epsilon, act_info));
212 
213     if(input->data_layout() != DataLayout::NHWC)
214     {
215         ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window_nchw(input->clone().get(), (run_in_place) ? nullptr : output->clone().get())
216                                     .first);
217     }
218 
219     return Status{};
220 }
221 
run(const Window & window,cl::CommandQueue & queue)222 void CLBatchNormalizationLayerKernel::run(const Window &window, cl::CommandQueue &queue)
223 {
224     ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
225     ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window);
226 
227     Window slice = window.first_slice_window_3D();
228 
229     Window vector_slice = window.first_slice_window_1D();
230     vector_slice.set(Window::DimX, Window::Dimension(0, 0, 0));
231 
232     unsigned int include_output = (!_run_in_place) ? 1 : 0;
233     unsigned int idx            = (1 + include_output) * num_arguments_per_3D_tensor();
234     add_1D_tensor_argument(idx, _mean, vector_slice);
235     add_1D_tensor_argument(idx, _var, vector_slice);
236     if(_beta != nullptr)
237     {
238         add_1D_tensor_argument(idx, _beta, vector_slice);
239     }
240     if(_gamma != nullptr)
241     {
242         add_1D_tensor_argument(idx, _gamma, vector_slice);
243     }
244 
245     do
246     {
247         idx = 0;
248         add_3D_tensor_argument(idx, _input, slice);
249         if(!_run_in_place)
250         {
251             add_3D_tensor_argument(idx, _output, slice);
252         }
253         enqueue(queue, *this, slice, lws_hint());
254     }
255     while(window.slide_window_slice_3D(slice));
256 }
257