Compute Library
 21.11
CLBatchNormalizationLayerKernel.cpp
Go to the documentation of this file.
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  */
25 
31 #include "arm_compute/core/Utils.h"
32 #include "src/core/CL/CLValidate.h"
35 
36 #include "support/StringSupport.h"
37 
38 using namespace arm_compute;
39 
40 namespace
41 {
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);
53  if(beta != nullptr)
54  {
57  }
58  if(gamma != nullptr)
59  {
62  }
63 
64  if(act_info.enabled())
65  {
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  {
79  }
80 
81  return Status{};
82 }
83 
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 
110  : _input(nullptr), _output(nullptr), _mean(nullptr), _var(nullptr), _beta(nullptr), _gamma(nullptr), _epsilon(0), _run_in_place(false)
111 {
113 }
114 
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 
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 
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 
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 
222 void CLBatchNormalizationLayerKernel::run(const Window &window, cl::CommandQueue &queue)
223 {
226 
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 }
static constexpr unsigned int num_arguments_per_1D_tensor()
Returns the number of arguments enqueued per 1D tensor object.
Definition: ICLKernel.h:240
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
#define ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(tensor)
Definition: CLValidate.h:35
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:490
bool enabled() const
Check if initialised.
Definition: Types.h:1559
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
void enqueue(cl::CommandQueue &queue, ICLKernel &kernel, const Window &window, const cl::NDRange &lws_hint=CLKernelLibrary::get().default_ndrange(), bool use_dummy_work_items=false)
Add the kernel to the command queue with the given window.
Definition: ICLKernel.cpp:32
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:318
float a() const
Get the alpha value.
Definition: Types.h:1549
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
std::string to_string(T &&value)
Convert integer and float values to string.
virtual DataType data_type() const =0
Data type used for each element of the tensor.
1 channel, 1 F32 per channel
#define ARM_COMPUTE_ERROR_ON(cond)
If the condition is true then an error message is printed and an exception thrown.
Definition: Error.h:466
const std::string & string_from_activation_func(ActivationLayerInfo::ActivationFunction act)
Translates a given activation function to a string.
Definition: Utils.cpp:163
static CLKernelLibrary & get()
Access the KernelLibrary singleton.
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Describe one of the image&#39;s dimensions with a start, end and step.
Definition: Window.h:77
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
Status class.
Definition: Error.h:52
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:326
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Activation Layer Information class.
Definition: Types.h:1509
void add_3D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 3D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:214
Copyright (c) 2017-2021 Arm Limited.
ActivationFunction
Available activation functions.
Definition: Types.h:1513
1 channel, 1 F16 per channel
virtual ValidRegion valid_region() const =0
Valid region of the tensor.
void add_option(std::string option)
Adds option to the existing build option list.
cl::Kernel create_kernel(const CLCompileContext &ctx, const std::string &kernel_name, const std::set< std::string > &build_opts=std::set< std::string >())
Creates an opencl kernel using a compile context.
Definition: CLHelpers.cpp:391
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:135
static constexpr size_t DimX
Alias for dimension 0 also known as X dimension.
Definition: Window.h:43
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: WindowHelpers.h:46
static constexpr unsigned int num_arguments_per_3D_tensor()
Returns the number of arguments enqueued per 3D tensor object.
Definition: ICLKernel.h:256
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const ITensorInfo *mean, const ITensorInfo *var, const ITensorInfo *beta=nullptr, const ITensorInfo *gamma=nullptr, float epsilon=0.001f, ActivationLayerInfo act_info=ActivationLayerInfo())
Static function to check if given info will lead to a valid configuration of CLBatchNormalizationLaye...
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1075
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
Implementation of a row access pattern.
unsigned int num_elems_processed_per_iteration
std::string get_cl_type_from_data_type(const DataType &dt)
Translates a tensor data type to the appropriate OpenCL type.
Definition: CLHelpers.cpp:39
bool auto_init_if_empty(ITensorInfo &info, const TensorShape &shape, int num_channels, DataType data_type, QuantizationInfo quantization_info=QuantizationInfo())
Auto initialize the tensor info (shape, number of channels and data type) if the current assignment i...
virtual std::unique_ptr< T > clone() const =0
Provide a clone of the current object of class T.
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor&#39;s metadata.
virtual size_t element_size() const =0
Element size in bytes calculated as data_size() * num_channels()
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
Elementeise CL kernel type.
Definition: CLTypes.h:84
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:335
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:915
bool has_padding_changed(const std::unordered_map< const ITensorInfo *, PaddingSize > &padding_map)
Check if the previously stored padding info has changed after configuring a kernel.
Definition: Utils.cpp:533
CLCompileContext class.
void configure(ICLTensor *input, ICLTensor *output, const ICLTensor *mean, const ICLTensor *var, const ICLTensor *beta=nullptr, const ICLTensor *gamma=nullptr, float epsilon=0.001f, ActivationLayerInfo act_info=ActivationLayerInfo())
Set the input and output tensors.
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
const std::string & string_from_data_layout(DataLayout dl)
Convert a data layout identity into a string.
Definition: Utils.cpp:123
virtual size_t total_size() const =0
Returns the total size of the tensor in bytes.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:439
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
size_t get_data_layout_dimension_index(const DataLayout &data_layout, const DataLayoutDimension &data_layout_dimension)
Get the index of the given dimension.
Definition: Helpers.inl:193
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
Num samples, height, width, channels.
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:788
std::unordered_map< const ITensorInfo *, PaddingSize > get_padding_info(std::initializer_list< const ITensorInfo *> infos)
Stores padding information before configuring a kernel.
Definition: Utils.cpp:518
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
unsigned int adjust_vec_size(unsigned int vec_size, size_t dim0)
Returns the adjusted vector size in case it is less than the input&#39;s first dimension, getting rounded down to its closest valid vector size.
Definition: Utils.h:1171
ActivationFunction activation() const
Get the type of activation function.
Definition: Types.h:1544
float b() const
Get the beta value.
Definition: Types.h:1554
void add_1D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 1D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:166
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:201
Window first_slice_window_1D() const
First 1D slice of the window.
Definition: Window.h:275
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...