Compute Library
 21.02
GCBatchNormalizationLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-2020 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 
30 #include "arm_compute/core/Utils.h"
36 
37 #include "support/StringSupport.h"
38 
39 using namespace arm_compute;
40 
41 namespace
42 {
44  const ITensorInfo *mean, const ITensorInfo *var,
45  const ITensorInfo *beta, const ITensorInfo *gamma,
46  float epsilon, ActivationLayerInfo act_info)
47 {
48  ARM_COMPUTE_UNUSED(epsilon);
49  ARM_COMPUTE_UNUSED(var);
51 
54 
55  if(output->total_size() != 0)
56  {
59  }
60 
61  if(beta != nullptr)
62  {
65  }
66  if(gamma != nullptr)
67  {
70  }
71  if(act_info.enabled())
72  {
74  ARM_COMPUTE_ERROR_ON(act_info.activation() != ActivationLayerInfo::ActivationLayerInfo::ActivationFunction::RELU
75  && act_info.activation() != ActivationLayerInfo::ActivationLayerInfo::ActivationFunction::BOUNDED_RELU
76  && act_info.activation() != ActivationLayerInfo::ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU);
77  ARM_COMPUTE_ERROR_ON(act_info.b() > act_info.a());
78  }
79  return Status{};
80 }
81 
82 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output,
83  ITensorInfo *mean, ITensorInfo *var,
84  ITensorInfo *beta, ITensorInfo *gamma)
85 {
86  // Output tensor auto initialization if not yet initialized
87  auto_init_if_empty(*output, input->tensor_shape(), 1, input->data_type());
88 
89  unsigned int num_elems_processed_per_iteration = 1;
90  if(input->data_type() == DataType::F16)
91  {
92  num_elems_processed_per_iteration = 4;
93  }
94 
95  // Configure kernel window
96  Window win = calculate_max_window(*input, Steps(num_elems_processed_per_iteration));
97 
98  AccessWindowHorizontal input_access(input, 0, num_elems_processed_per_iteration);
99  AccessWindowHorizontal output_access(output, 0, num_elems_processed_per_iteration);
100  AccessWindowStatic mean_access(mean, 0, 0, mean->dimension(0) + 3, mean->dimension(1));
101  AccessWindowStatic var_access(var, 0, 0, var->dimension(0) + 3, var->dimension(1));
102 
103  bool window_changed = false;
104  if(beta != nullptr)
105  {
106  AccessWindowStatic beta_access(beta, 0, 0, beta->dimension(0) + 3, beta->dimension(1));
107  if(gamma != nullptr)
108  {
109  AccessWindowStatic gamma_access(gamma, 0, 0, gamma->dimension(0) + 3, gamma->dimension(1));
110  window_changed = update_window_and_padding(win, input_access, output_access, mean_access, var_access, beta_access, gamma_access);
111  }
112  else
113  {
114  window_changed = update_window_and_padding(win, input_access, output_access, mean_access, var_access, beta_access);
115  }
116  }
117  else
118  {
119  if(gamma != nullptr)
120  {
121  AccessWindowStatic gamma_access(gamma, 0, 0, gamma->dimension(0) + 3, gamma->dimension(1));
122  window_changed = update_window_and_padding(win, input_access, output_access, mean_access, var_access, gamma_access);
123  }
124  else
125  {
126  window_changed = update_window_and_padding(win, input_access, output_access, mean_access, var_access);
127  }
128  }
129  output_access.set_valid_region(win, input->valid_region());
130 
131  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
132  return std::make_pair(err, win);
133 }
134 } // namespace
135 
137  : _input(nullptr), _output(nullptr), _mean(nullptr), _var(nullptr), _beta(nullptr), _gamma(nullptr), _epsilon(0.0f)
138 {
139 }
140 
141 void GCBatchNormalizationLayerKernel::configure(const IGCTensor *input, IGCTensor *output, const IGCTensor *mean, const IGCTensor *var, const IGCTensor *beta, const IGCTensor *gamma,
142  float epsilon, ActivationLayerInfo act_info)
143 {
144  ARM_COMPUTE_ERROR_ON_NULLPTR(input, output, mean, var);
145 
146  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), mean->info(), var->info(),
147  (beta != nullptr) ? beta->info() : nullptr, (gamma != nullptr) ? gamma->info() : nullptr,
148  epsilon, act_info));
149 
150  _input = input;
151  _output = output;
152  _mean = mean;
153  _var = var;
154  _beta = beta;
155  _gamma = gamma;
156  _epsilon = epsilon;
157 
158  // Set build options
159  std::set<std::string> build_opts;
160  std::string dt_name = (input->info()->data_type() == DataType::F32) ? "DATA_TYPE_FP32" : "DATA_TYPE_FP16";
161  build_opts.emplace(("#define " + dt_name));
162  build_opts.emplace(("#define ESPILON " + float_to_string_with_full_precision(_epsilon)));
163  build_opts.emplace(("#define LOCAL_SIZE_X " + support::cpp11::to_string(1)));
164  build_opts.emplace(("#define LOCAL_SIZE_Y " + support::cpp11::to_string(1)));
165  build_opts.emplace(("#define LOCAL_SIZE_Z " + support::cpp11::to_string(1)));
166  if(beta == nullptr)
167  {
168  build_opts.emplace("#define USE_DEFAULT_BETA");
169  }
170  if(gamma == nullptr)
171  {
172  build_opts.emplace("#define USE_DEFAULT_GAMMA");
173  }
174 
175  if(act_info.enabled())
176  {
177  build_opts.emplace("#define " + string_from_activation_func(act_info.activation()));
178  build_opts.emplace("#define A_VAL " + float_to_string_with_full_precision(act_info.a()));
179  build_opts.emplace("#define B_VAL " + float_to_string_with_full_precision(act_info.b()));
180  }
181 
182  // Create kernel
183  _kernel = static_cast<GCKernel>(GCKernelLibrary::get().create_kernel("batchnormalization_layer", build_opts));
184 
185  // Configure kernel window
186  auto win_config = validate_and_configure_window(input->info(), output->info(), mean->info(), var->info(),
187  (beta != nullptr) ? beta->info() : nullptr, (gamma != nullptr) ? gamma->info() : nullptr);
188  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
189 
190  IGCKernel::configure(win_config.second);
191 }
192 
194  const ITensorInfo *mean, const ITensorInfo *var,
195  const ITensorInfo *beta, const ITensorInfo *gamma,
196  float epsilon, ActivationLayerInfo act_info)
197 {
198  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, mean, var, beta, gamma, epsilon, act_info));
199  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(),
200  mean->clone().get(), var->clone().get(),
201  beta->clone().get(), gamma->clone().get())
202  .first);
203 
204  return Status{};
205 }
206 
208 {
211 
212  _kernel.use();
213 
214  _output->set_needs_shifting(true);
215 
217  Window slice_in = window.first_slice_window_3D();
218 
219  Window vector_slice = window.first_slice_window_1D();
220  vector_slice.set(Window::DimX, Window::Dimension(0, 0, 0));
221 
222  unsigned int idx = 2 * num_arguments_per_3D_tensor();
223  unsigned int binding_point = 3;
224  add_1D_tensor_argument(idx, _mean, binding_point, vector_slice);
225  add_1D_tensor_argument(idx, _var, ++binding_point, vector_slice);
226  if(_beta != nullptr)
227  {
228  add_1D_tensor_argument(idx, _beta, ++binding_point, vector_slice);
229  }
230  if(_gamma != nullptr)
231  {
232  add_1D_tensor_argument(idx, _gamma, ++binding_point, vector_slice);
233  }
234 
235  slice.shift(Window::DimX, -(_output->info()->padding()).left);
236 
237  do
238  {
239  idx = 0;
240  add_3D_tensor_argument(idx, _input, 1, slice_in);
241  add_3D_tensor_argument(idx, _output, 2, slice);
242 
243  _kernel.update_shader_params();
244  enqueue(*this, slice);
245  }
246  while(window.slide_window_slice_3D(slice) && window.slide_window_slice_3D(slice_in));
247 }
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps, bool skip_border, BorderSize border_size)
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
void add_3D_tensor_argument(unsigned int &idx, const IGCTensor *tensor, const unsigned int binding_point, 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: IGCKernel.cpp:132
void enqueue(IGCKernel &kernel, const Window &window, const gles::NDRange &lws=gles::NDRange(1U, 1U, 1U))
Add the kernel to the command queue with the given window.
Definition: IGCKernel.cpp:41
bool enabled() const
Check if initialised.
Definition: Types.h:1600
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
void shift(size_t dimension, int shift_value)
Shift the values of a given dimension by the given shift_value.
Definition: Window.inl:133
float a() const
Get the alpha value.
Definition: Types.h:1590
#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
Store the tensor&#39;s metadata.
Definition: ITensorInfo.h:40
Interface for GLES Compute tensor.
Definition: IGCTensor.h:35
#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
GCKernel class.
unsigned int num_arguments_per_3D_tensor() const
Returns the number of arguments enqueued per 3D tensor object.
Definition: IGCKernel.cpp:147
Status class.
Definition: Error.h:52
Activation Layer Information class.
Definition: Types.h:1550
Copyright (c) 2017-2021 Arm Limited.
1 channel, 1 F16 per channel
virtual ValidRegion valid_region() const =0
Valid region of the tensor.
void run(const Window &window) override
Enqueue the OpenGL ES shader to process the given window.
Implementation of a static rectangular access pattern.
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 GCBatchNormalizationLaye...
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
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1262
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
#define ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:543
Manages all the GLES kernels compilation and caching, provides accessors for the GLES Context...
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
void set_needs_shifting(bool needs_shifting)
Set the flag indicating whether or not a tensor needs shifting.
Definition: IGCTensor.cpp:61
Implementation of a row access pattern.
#define ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:441
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.
void set(size_t dimension, const Dimension &dim)
Set the values of a given dimension.
Definition: Window.inl:49
virtual PaddingSize padding() const =0
Padding of tensor.
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:941
#define ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:790
static GCKernelLibrary & get()
Get the static instance of GCKernelLibrary.
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:443
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:545
void configure(const IGCTensor *input, IGCTensor *output, const IGCTensor *mean, const IGCTensor *var, const IGCTensor *beta=nullptr, const IGCTensor *gamma=nullptr, float epsilon=0.001f, ActivationLayerInfo act_info=ActivationLayerInfo())
Set the input and output tensors.
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
GCKernel create_kernel(const std::string &shader_name, const StringSet &build_options_set={}) const
Creates a kernel from the kernel library.
unsigned int num_elems_processed_per_iteration
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
ActivationFunction activation() const
Get the type of activation function.
Definition: Types.h:1585
float b() const
Get the beta value.
Definition: Types.h:1595
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
void add_1D_tensor_argument(unsigned int &idx, const IGCTensor *tensor, const unsigned int binding_point, 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: IGCKernel.cpp:122
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
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)