Compute Library
 21.11
CLFuseBatchNormalizationKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-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 namespace arm_compute
39 {
40 namespace
41 {
42 Status validate_arguments(const ITensorInfo *input_weights, const ITensorInfo *bn_mean, const ITensorInfo *bn_var,
43  const ITensorInfo *fused_weights, const ITensorInfo *fused_bias,
44  const ITensorInfo *input_bias, const ITensorInfo *bn_beta, const ITensorInfo *bn_gamma,
45  float epsilon, FuseBatchNormalizationType fbn_type)
46 {
47  ARM_COMPUTE_UNUSED(epsilon);
48  ARM_COMPUTE_ERROR_ON_NULLPTR(input_weights, bn_mean, bn_var);
52  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input_weights, bn_mean, bn_var);
53  ARM_COMPUTE_RETURN_ERROR_ON(input_bias == nullptr && fused_bias == nullptr);
54  ARM_COMPUTE_RETURN_ERROR_ON(bn_mean->num_dimensions() > 1);
55 
57  {
58  ARM_COMPUTE_RETURN_ERROR_ON(input_weights->dimension(3) != bn_mean->dimension(0));
59  }
60  else
61  {
62  const size_t channel_idx = get_data_layout_dimension_index(input_weights->data_layout(), DataLayoutDimension::CHANNEL);
63  ARM_COMPUTE_RETURN_ERROR_ON(input_weights->dimension(channel_idx) != bn_mean->dimension(0));
64  }
65 
66  // Validate bias
67  if(input_bias != nullptr)
68  {
70  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input_weights, input_bias);
71  }
72  // Validate beta
73  if(bn_beta != nullptr)
74  {
77  }
78  // Validate gamma
79  if(bn_gamma != nullptr)
80  {
83  }
84  // Validate output weights
85  if(fused_weights != nullptr && fused_weights->total_size() != 0)
86  {
87  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input_weights, fused_weights);
88  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input_weights, fused_weights);
89  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input_weights, fused_weights);
90  }
91  // Validate output bias
92  if(fused_bias != nullptr && fused_bias->total_size() != 0)
93  {
95  ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input_weights, fused_bias);
96  }
97 
98  return Status{};
99 }
100 } // namespace
101 
103  : _input_weights(nullptr), _input_bias(nullptr), _bn_mean(nullptr), _bn_var(nullptr), _bn_gamma(nullptr), _bn_beta(nullptr), _fused_weights(nullptr), _fused_bias(nullptr), _epsilon(),
104  _run_in_place_weights(false), _run_in_place_bias(false)
105 {
107 }
108 
109 void CLFuseBatchNormalizationKernel::configure(const ICLTensor *input_weights, const ICLTensor *bn_mean, const ICLTensor *bn_var,
110  ICLTensor *fused_weights, ICLTensor *fused_bias,
111  const ICLTensor *input_bias, const ICLTensor *bn_beta, const ICLTensor *bn_gamma,
112  float epsilon, FuseBatchNormalizationType fbn_type)
113 {
114  configure(CLKernelLibrary::get().get_compile_context(), input_weights, bn_mean, bn_var, fused_weights, fused_bias, input_bias, bn_beta, bn_gamma, epsilon, fbn_type);
115 }
116 
117 void CLFuseBatchNormalizationKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input_weights, const ICLTensor *bn_mean, const ICLTensor *bn_var,
118  ICLTensor *fused_weights, ICLTensor *fused_bias,
119  const ICLTensor *input_bias, const ICLTensor *bn_beta, const ICLTensor *bn_gamma,
120  float epsilon, FuseBatchNormalizationType fbn_type)
121 {
122  ARM_COMPUTE_ERROR_ON_NULLPTR(input_weights, bn_mean, bn_var);
123 
124  auto padding_info = get_padding_info({ input_weights, bn_mean, bn_var, fused_weights, fused_bias, input_bias, bn_beta, bn_gamma });
125 
126  _input_weights = input_weights;
127  _input_bias = input_bias;
128  _bn_mean = bn_mean;
129  _bn_var = bn_var;
130  _bn_beta = bn_beta;
131  _bn_gamma = bn_gamma;
132  _fused_weights = fused_weights;
133  _fused_bias = fused_bias;
134  _epsilon = epsilon;
135 
136  _run_in_place_weights = (fused_weights == nullptr) || (fused_weights == input_weights);
137  _run_in_place_bias = (input_bias != nullptr && fused_bias == nullptr) || (input_bias != nullptr && fused_bias == input_bias);
138 
139  // Auto initialize outputs
140  if(_fused_weights != nullptr)
141  {
142  // Output tensor auto initialization if not yet initialized
143  auto_init_if_empty(*_fused_weights->info(), *_input_weights->info()->clone());
144  }
145  if(_fused_bias != nullptr)
146  {
147  // Output tensor auto initialization if not yet initialized
148  auto_init_if_empty(*_fused_bias->info(), *_bn_mean->info()->clone());
149  }
150 
151  // Validate arguments
152  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input_weights->info(), bn_mean->info(), bn_var->info(),
153  (fused_weights != nullptr) ? fused_weights->info() : nullptr,
154  (fused_bias != nullptr) ? fused_bias->info() : nullptr,
155  (input_bias != nullptr) ? input_bias->info() : nullptr,
156  (bn_beta != nullptr) ? bn_beta->info() : nullptr,
157  (bn_gamma != nullptr) ? bn_gamma->info() : nullptr,
158  epsilon, fbn_type));
159 
160  // Configure kernel window
161  Window win = calculate_max_window(*input_weights->info());
162  ICLKernel::configure_internal(win);
163 
164  // Set build options
165  CLBuildOptions build_opts;
166  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input_weights->info()->data_type()));
167  build_opts.add_option_if(fbn_type == FuseBatchNormalizationType::CONVOLUTION, "-DDIM2=" + support::cpp11::to_string(input_weights->info()->dimension(2)));
168  build_opts.add_option("-DEPSILON=" + float_to_string_with_full_precision(epsilon));
169  build_opts.add_option_if(_input_weights->info()->data_layout() == DataLayout::NHWC, "-DNHWC");
170  build_opts.add_option_if(_run_in_place_weights, "-DIN_PLACE_W");
171  build_opts.add_option_if(_run_in_place_bias, "-DIN_PLACE_B");
172  build_opts.add_option_if(input_bias != nullptr, "-DBIAS");
173  build_opts.add_option_if(bn_beta != nullptr, "-DBETA");
174  build_opts.add_option_if(bn_gamma != nullptr, "-DGAMMA");
175 
176  // Create kernel
177  _kernel = create_kernel(compile_context, "fuse_batchnormalization_layer", build_opts.options());
178 
180 }
181 
182 Status CLFuseBatchNormalizationKernel::validate(const ITensorInfo *input_weights, const ITensorInfo *bn_mean, const ITensorInfo *bn_var,
183  const ITensorInfo *fused_weights, const ITensorInfo *fused_bias,
184  const ITensorInfo *input_bias, const ITensorInfo *bn_beta, const ITensorInfo *bn_gamma,
185  float epsilon, FuseBatchNormalizationType fbn_type)
186 {
187  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input_weights, bn_mean, bn_var, fused_weights, fused_bias, input_bias, bn_beta, bn_gamma, epsilon, fbn_type));
188  return Status{};
189 }
190 
192 {
195 
196  // Create window slice
197  Window collapsed_window = window.collapse(window, Window::DimZ);
198  Window slice_1d = window.first_slice_window_1D();
199  Window slice_3d = collapsed_window.first_slice_window_3D();
200 
201  // Add kernel arguments
202  unsigned int idx = 0;
203  add_3D_tensor_argument(idx, _input_weights, slice_3d);
204  if(_input_bias != nullptr)
205  {
206  add_1D_tensor_argument(idx, _input_bias, slice_1d);
207  }
208  add_1D_tensor_argument(idx, _bn_mean, slice_1d);
209  add_1D_tensor_argument(idx, _bn_var, slice_1d);
210  if(!_run_in_place_weights)
211  {
212  add_3D_tensor_argument(idx, _fused_weights, slice_3d);
213  }
214  if(!_run_in_place_bias)
215  {
216  add_1D_tensor_argument(idx, _fused_bias, slice_1d);
217  }
218  if(_bn_beta != nullptr)
219  {
220  add_1D_tensor_argument(idx, _bn_beta, slice_1d);
221  }
222  if(_bn_gamma != nullptr)
223  {
224  add_1D_tensor_argument(idx, _bn_gamma, slice_1d);
225  }
226  enqueue(queue, *this, slice_3d, lws_hint());
227 }
228 } // namespace arm_compute
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
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
const StringSet & options() const
Gets the current options list set.
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:318
#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.
static Status validate(const ITensorInfo *input_weights, const ITensorInfo *bn_mean, const ITensorInfo *bn_var, const ITensorInfo *fused_weights, const ITensorInfo *fused_bias, const ITensorInfo *input_bias=nullptr, const ITensorInfo *bn_beta=nullptr, const ITensorInfo *bn_gamma=nullptr, float epsilon=0.001f, FuseBatchNormalizationType fbn_type=FuseBatchNormalizationType::CONVOLUTION)
Static function to check if given info will lead to a valid configuration of CLFuseBatchNormalization...
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
static CLKernelLibrary & get()
Access the KernelLibrary singleton.
Store the tensor's metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
Status class.
Definition: Error.h:52
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
void add_3D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 3D tensor's parameters to the object's kernel's arguments starting from the index idx...
Definition: ICLKernel.h:214
Copyright (c) 2017-2021 Arm Limited.
1 channel, 1 F16 per channel
void configure(const ICLTensor *input_weights, const ICLTensor *bn_mean, const ICLTensor *bn_var, ICLTensor *fused_weights, ICLTensor *fused_bias, const ICLTensor *input_bias=nullptr, const ICLTensor *bn_beta=nullptr, const ICLTensor *bn_gamma=nullptr, float epsilon=0.001f, FuseBatchNormalizationType fbn_type=FuseBatchNormalizationType::CONVOLUTION)
Set the source, destination of the kernel.
void add_option(std::string option)
Adds option to the existing build option list.
FuseBatchNormalizationType
Available FuseBatchNormalizationType.
Definition: Types.h:158
Window collapse(const Window &full_window, size_t first, size_t last=Coordinates::num_max_dimensions) const
Collapse the dimensions between first and last.
Definition: Window.inl:111
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
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1075
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.
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
Elementeise CL kernel type.
Definition: CLTypes.h:84
#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.
Interface for OpenCL tensor.
Definition: ICLTensor.h:42
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:439
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
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
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