Compute Library
 21.02
CLInstanceNormalizationLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2019-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 
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, const ITensorInfo *output, const InstanceNormalizationLayerKernelInfo &info)
43 {
44  ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.epsilon == 0.f, "Epsilon must be different than 0");
46 
47  if(output != nullptr && output->total_size() != 0)
48  {
52  ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->num_channels() != output->num_channels(), "Input and output have different number of channels");
53  }
54 
55  return Status{};
56 }
57 
58 std::tuple<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output)
59 {
60  // We handle the planes manually
61  Window win = calculate_max_window(*input, Steps(1));
62 
63  // Output auto initialization if not yet initialized
64  auto_init_if_empty(*output, input->tensor_shape(), 1, input->data_type());
65 
66  // CLInstanceNormalizationLayerKernel doesn't need padding so update_window_and_padding() can be skipped
67  Coordinates coord;
68  coord.set_num_dimensions(output->num_dimensions());
69  output->set_valid_region(ValidRegion(coord, output->tensor_shape()));
70  return std::make_pair(Status{}, win);
71 }
72 } // namespace
73 
75  : _input(nullptr), _output(nullptr), _run_in_place(false)
76 {
77 }
78 
80 {
81  configure(CLKernelLibrary::get().get_compile_context(), input, output, info);
82 }
83 
85 {
87  auto padding_info = get_padding_info({ input, output });
88 
89  _input = input;
90  _output = output == nullptr ? input : output;
91 
92  _run_in_place = (output == nullptr) || (output == input);
93  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(_input->info(), _output->info(), info));
94  const unsigned int num_elems_processed_per_iteration = 16 / input->info()->element_size();
95 
96  CLBuildOptions build_opts;
97  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
98  build_opts.add_option("-DINTERNAL_DATA_TYPE=" + (info.use_mixed_precision ? "float" : get_cl_type_from_data_type(input->info()->data_type())));
99  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration));
100  build_opts.add_option("-DDIM_X=" + support::cpp11::to_string(input->info()->dimension(0)));
101  build_opts.add_option("-DDIM_Y=" + support::cpp11::to_string(input->info()->dimension(1)));
102  build_opts.add_option("-DDIM_Z=" + support::cpp11::to_string(input->info()->dimension(2)));
103  build_opts.add_option("-DGAMMA=" + float_to_string_with_full_precision(info.gamma));
104  build_opts.add_option("-DBETA=" + float_to_string_with_full_precision(info.beta));
105  build_opts.add_option("-DEPSILON=" + float_to_string_with_full_precision(info.epsilon));
106  build_opts.add_option_if(_run_in_place, "-DIN_PLACE");
107  build_opts.add_option_if(_input->info()->data_layout() == DataLayout::NHWC, "-DNHWC");
108 
109  // Create kernel
110  _kernel = create_kernel(compile_context, "instance_normalization", build_opts.options());
111 
112  // Configure kernel window
113  auto win_config = validate_and_configure_window(_input->info(), _output->info());
114  ARM_COMPUTE_ERROR_THROW_ON(std::get<0>(win_config));
115  ICLKernel::configure_internal(std::get<1>(win_config));
117 }
118 
120 {
121  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, info));
122  ARM_COMPUTE_RETURN_ON_ERROR(std::get<0>(validate_and_configure_window(input->clone().get(), (output == nullptr ? input->clone().get() : output->clone().get()))));
123  return Status{};
124 }
125 
126 void CLInstanceNormalizationLayerKernel::run(const Window &window, cl::CommandQueue &queue)
127 {
130 
131  Window collapsed_window = window.collapse(window, Window::DimZ);
132 
133  // We will process the planes together
134  if(_input->info()->data_layout() == DataLayout::NCHW)
135  {
136  collapsed_window.set(Window::DimX, Window::Dimension(0, 1, 1));
137  collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
138  }
139  else
140  {
141  collapsed_window.set(Window::DimY, Window::Dimension(0, 1, 1));
142  collapsed_window.set(Window::DimZ, Window::Dimension(0, _input->info()->dimension(3), 1));
143  }
144 
145  unsigned int idx = 0;
146  add_4D_tensor_argument(idx, _input, collapsed_window);
147  if(!_run_in_place)
148  {
149  add_4D_tensor_argument(idx, _output, collapsed_window);
150  }
151 
152  enqueue(queue, *this, collapsed_window, lws_hint());
153 }
154 } // 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
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
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:494
virtual size_t dimension(size_t index) const =0
Return the size of the requested dimension.
const StringSet & options() const
Gets the current options list set.
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:276
#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
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
Status class.
Definition: Error.h:52
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:403
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:1262
std::string get_cl_type_from_data_type(const DataType &dt)
Translates a tensor data type to the appropriate OpenCL type.
Definition: CLHelpers.cpp:37
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;.
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
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:941
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:528
Num samples, channels, height, width.
CLCompileContext class.
void configure(ICLTensor *input, ICLTensor *output, const InstanceNormalizationLayerKernelInfo &info)
Set the input and output tensors.
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:443
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
float gamma
The scale scalar value applied to the normalized tensor.
Manages all the OpenCL kernels compilation and caching, provides accessors for the OpenCL Context...
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:545
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:513
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *bias, const ITensorInfo *output, const GEMMLowpOutputStageInfo *output_stage)
unsigned int num_elems_processed_per_iteration
#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:161
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(t,...)
Definition: Validate.h:694
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:182
Describe a multidimensional execution window.
Definition: Window.h:39
float beta
The offset scalar value applied to the normalized tensor.
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
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.