Compute Library
 21.11
CLInstanceNormalizationLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2019-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 #include "support/StringSupport.h"
36 
37 namespace arm_compute
38 {
39 namespace
40 {
41 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, const InstanceNormalizationLayerKernelInfo &info)
42 {
43  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.epsilon == 0.f, "Epsilon must be different than 0");
45 
46  if(output != nullptr && output->total_size() != 0)
47  {
51  ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->num_channels() != output->num_channels(), "Input and output have different number of channels");
52  }
53 
54  return Status{};
55 }
56 
57 Status validate_arguments_meanvar(const ITensorInfo *input, const ITensorInfo *output)
58 {
60 
61  if(output != nullptr && output->total_size() != 0)
62  {
65  ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->num_channels() != output->num_channels(), "Input and output have different number of channels");
66  }
67 
68  return Status{};
69 }
70 } // namespace
71 
73  : _input(nullptr), _output(nullptr)
74 {
76 }
77 
78 void CLComputeMeanVariance::configure(const CLCompileContext &compile_context, ICLTensor *input, ICLTensor *output, bool use_mixed_precision)
79 {
81  auto padding_info = get_padding_info({ input, output });
82 
83  _input = input;
84  _output = output == nullptr ? input : output;
85 
86  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments_meanvar(_input->info(), _output->info()));
87  const unsigned int num_elems_processed_per_iteration = 16 / input->info()->element_size();
88 
89  CLBuildOptions build_opts;
90  build_opts.add_option("-DINTERNAL_DATA_TYPE=" + (use_mixed_precision ? "float" : get_cl_type_from_data_type(input->info()->data_type())));
91  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
92  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration));
93  build_opts.add_option("-DDIM_X=" + support::cpp11::to_string(input->info()->dimension(0)));
94  build_opts.add_option("-DDIM_Y=" + support::cpp11::to_string(input->info()->dimension(1)));
95  build_opts.add_option("-DDIM_Z=" + support::cpp11::to_string(input->info()->dimension(2)));
96  build_opts.add_option_if(_input->info()->data_layout() == DataLayout::NHWC, "-DNHWC");
97  // Create kernel
98  _kernel = create_kernel(compile_context, "compute_mean_var", build_opts.options());
99 
100  // We handle the planes manually
101  Window win = calculate_max_window(*(input->info()), Steps(1));
102  const auto data_layout = input->info()->data_layout();
103  const unsigned int channel_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL);
104  const unsigned int batches_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::BATCHES);
105  const unsigned int input_channel = input->info()->dimension(channel_idx);
106  const unsigned int input_batches = input->info()->dimension(batches_idx);
107  const TensorShape out_shape(input_channel, 2u, input_batches);
108 
109  // Output auto initialization if not yet initialized
110  if(use_mixed_precision)
111  {
112  auto_init_if_empty(*_output->info(), out_shape, 1, DataType::F32);
113  }
114  else
115  {
116  auto_init_if_empty(*_output->info(), out_shape, 1, input->info()->data_type());
117  }
118  ICLKernel::configure_internal(win);
120 }
121 
123 {
124  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments_meanvar(input, output));
125  return Status{};
126 }
127 
128 void CLComputeMeanVariance::run(const Window &window, cl::CommandQueue &queue)
129 {
132 
133  Window collapsed_window = window.collapse(window, Window::DimZ);
134 
135  // We will process the planes together
136  if(_input->info()->data_layout() == DataLayout::NCHW)
137  {
138  collapsed_window.set(Window::DimX, Window::Dimension(0, 1, 1));
139  collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
140  }
141  else
142  {
143  collapsed_window.set(Window::DimZ, Window::Dimension(0, 1, 1));
144  collapsed_window.set(Window::DimY, Window::Dimension(0, _input->info()->dimension(3), 1));
145  }
146  unsigned int idx = 0;
147  add_4D_tensor_argument(idx, _input, collapsed_window);
148  add_3D_tensor_argument(idx, _output, collapsed_window);
149 
150  enqueue(queue, *this, collapsed_window, lws_hint());
151 }
152 
154  : _input(nullptr), _output(nullptr), _mean(nullptr), _run_in_place(false)
155 {
157 }
158 
160 {
162  auto padding_info = get_padding_info({ input, output });
163 
164  _input = input;
165  _output = output == nullptr ? input : output;
166  _mean = mean_var;
167 
168  _run_in_place = (output == nullptr) || (output == input);
169  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(_input->info(), _output->info(), info));
170  const unsigned int num_elems_processed_per_iteration = 16 / input->info()->element_size();
171 
172  CLBuildOptions build_opts;
173  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
174  build_opts.add_option("-DINTERNAL_DATA_TYPE=" + (info.use_mixed_precision ? "float" : get_cl_type_from_data_type(input->info()->data_type())));
175  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration));
176  build_opts.add_option("-DDIM_X=" + support::cpp11::to_string(input->info()->dimension(0)));
177  build_opts.add_option("-DDIM_Y=" + support::cpp11::to_string(input->info()->dimension(1)));
178  build_opts.add_option("-DDIM_Z=" + support::cpp11::to_string(input->info()->dimension(2)));
179  build_opts.add_option("-DGAMMA=" + float_to_string_with_full_precision(info.gamma));
180  build_opts.add_option("-DBETA=" + float_to_string_with_full_precision(info.beta));
181  build_opts.add_option("-DEPSILON=" + float_to_string_with_full_precision(info.epsilon));
182  build_opts.add_option_if(_run_in_place, "-DIN_PLACE");
183  build_opts.add_option_if(_input->info()->data_layout() == DataLayout::NHWC, "-DNHWC");
184 
185  // Create kernel
186  _kernel = create_kernel(compile_context, "instance_normalization", build_opts.options());
187 
188  // Configure kernel window
189  Window win = calculate_max_window(*input->info(), Steps(1));
190  if(output != nullptr)
191  {
192  auto_init_if_empty(*output->info(), input->info()->tensor_shape(), 1, input->info()->data_type());
193  }
194 
195  ICLKernel::configure_internal(win);
197 }
198 
200 {
201  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, info));
202  return Status{};
203 }
204 
205 void CLInstanceNormalizationLayerKernel::run(const Window &window, cl::CommandQueue &queue)
206 {
209 
210  Window collapsed_window = window.collapse(window, Window::DimZ);
211 
212  // We will process the planes together
213  if(_input->info()->data_layout() == DataLayout::NCHW)
214  {
215  collapsed_window.set(Window::DimX, Window::Dimension(0, 1, 1));
216  collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
217  }
218  else
219  {
220  collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
221  collapsed_window.set(Window::DimZ, Window::Dimension(0, _input->info()->dimension(3), 1));
222  }
223 
224  unsigned int idx = 0;
225  add_4D_tensor_argument(idx, _input, collapsed_window);
226  add_3D_tensor_argument(idx, _mean, collapsed_window);
227 
228  if(!_run_in_place)
229  {
230  add_4D_tensor_argument(idx, _output, collapsed_window);
231  }
232 
233  enqueue(queue, *this, collapsed_window, lws_hint());
234 }
235 } // namespace arm_compute
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
Shape of a tensor.
Definition: TensorShape.h:39
void configure(const CLCompileContext &compile_context, ICLTensor *input, ICLTensor *output, bool use_mixed_precision)
Set the input and output tensors.
#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.
void configure(const CLCompileContext &compile_context, ICLTensor *input, ICLTensor *mean_var, ICLTensor *output, const InstanceNormalizationLayerKernelInfo &info)
Set the input and output tensors.
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
Store the tensor's metadata.
Definition: ITensorInfo.h:40
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Describe one of the image'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
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
bool use_mixed_precision
Use mixed precision in case of FP16 execution.
void add_option(std::string option)
Adds option to the existing build option list.
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
static Status validate(const ITensorInfo *input, const ITensorInfo *output, const InstanceNormalizationLayerKernelInfo &info)
Static function to check if given info will lead to a valid configuration of CLInstanceNormalizationL...
static constexpr size_t DimX
Alias for dimension 0 also known as X dimension.
Definition: Window.h:43
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1075
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
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 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;.
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
#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
Num samples, channels, height, width.
CLCompileContext class.
float epsilon
Lower bound value for the normalization.
static constexpr size_t DimY
Alias for dimension 1 also known as Y dimension.
Definition: Window.h:45
ScaleKernelInfo info(interpolation_policy, default_border_mode, PixelValue(), sampling_policy, false)
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
float gamma
The scale scalar value applied to the normalized tensor.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
Num samples, height, width, channels.
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_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
static Status validate(const ITensorInfo *input, const ITensorInfo *output)
Static function to check if given info will lead to a valid configuration of CLInstanceNormalizationL...
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(t,...)
Definition: Validate.h:690
void add_4D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, const Window &window)
Add the passed 4D tensor&#39;s parameters to the object&#39;s kernel&#39;s arguments starting from the index idx...
Definition: ICLKernel.h:224
Describe a multidimensional execution window.
Definition: Window.h:39
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
float beta
The offset scalar value applied to the normalized tensor.
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:201
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue...
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.