Compute Library
 20.02.1
CLNormalizationLayerKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-2018 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 
33 #include "arm_compute/core/Utils.h"
35 
36 using namespace arm_compute;
37 
38 namespace
39 {
40 constexpr unsigned int num_elems_processed_per_iteration = 4;
41 Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, NormalizationLayerInfo norm_info)
42 {
47 
48  ARM_COMPUTE_RETURN_ERROR_ON_MSG(!(norm_info.norm_size() % 2), "Normalization size should be odd");
49 
50  // Checks performed when output is configured
51  if(output->total_size() != 0)
52  {
56  }
57 
58  return Status{};
59 }
60 
61 std::pair<Status, Window> validate_and_configure_window(ITensorInfo *input, ITensorInfo *output, NormalizationLayerInfo norm_info)
62 {
63  // Output tensor auto initialization if not yet initialized
64  auto_init_if_empty(*output, *input->clone());
65 
66  const unsigned int norm_idx = get_normalization_dimension_index(input->data_layout(), norm_info);
67  const bool is_norm_accross_width = norm_idx == 0;
68 
69  const unsigned int border_width = is_norm_accross_width ? num_elems_processed_per_iteration - 1 : 0;
70  const BorderSize border_size = BorderSize(0, border_width);
71 
73  bool window_changed = false;
74 
75  // We do not use a Rectangle window for IN_MAP_2D as we clamp the top and bottom accesses inside the kernel, avoiding padding
76  // Reads can occur within the valid region of the input
77  if(is_norm_accross_width)
78  {
79  AccessWindowStatic input_access(input, -border_size.left, 0, input->dimension(0) + border_size.right, 0);
80  window_changed = window_changed || update_window_and_padding(win, input_access);
81  }
82  else
83  {
85  window_changed = window_changed || update_window_and_padding(win, input_access);
86  }
87 
89  window_changed = window_changed || update_window_and_padding(win, output_access);
90  output_access.set_valid_region(win, input->valid_region());
91 
92  Status err = (window_changed) ? ARM_COMPUTE_CREATE_ERROR(ErrorCode::RUNTIME_ERROR, "Insufficient Padding!") : Status{};
93  return std::make_pair(err, win);
94 }
95 } // namespace
96 
98  : _input(nullptr), _output(nullptr), _border_size(0), _is_norm_across_width(false)
99 {
100 }
101 
103 {
104  return _border_size;
105 }
106 
108 {
110 
111  // Output tensor auto initialization if not yet initialized
112  auto_init_if_empty(*output->info(), *input->info()->clone());
113 
114  // Perform validation step
115  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), output->info(), norm_info));
116 
117  _input = input;
118  _output = output;
119 
120  const DataLayout data_layout = input->info()->data_layout();
121  const unsigned int norm_idx = get_normalization_dimension_index(data_layout, norm_info);
122  _is_norm_across_width = norm_idx == 0;
123  const unsigned int border_width = _is_norm_across_width ? num_elems_processed_per_iteration - 1 : 0;
124  _border_size = BorderSize(0, border_width);
125 
126  const bool is_in_map_2D = (norm_info.type() == NormType::IN_MAP_2D);
127 
128  // Set build options
129  CLBuildOptions build_opts;
130  build_opts.add_option(("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type())));
131  build_opts.add_option(("-DCOEFF=" + float_to_string_with_full_precision(norm_info.scale_coeff())));
132  build_opts.add_option(("-DBETA=" + float_to_string_with_full_precision(norm_info.beta())));
133  build_opts.add_option(("-DKAPPA=" + float_to_string_with_full_precision(norm_info.kappa())));
135  build_opts.add_option(("-DRADIUS=" + support::cpp11::to_string(norm_info.norm_size() / 2)));
136  build_opts.add_option(("-DNUM_SLICES=" + support::cpp11::to_string(input->info()->dimension(2))));
137  build_opts.add_option_if(is_in_map_2D, "-DIN_MAP_2D");
138  build_opts.add_option_if(norm_info.is_in_map() || (data_layout == DataLayout::NHWC && norm_info.is_cross_map()), "-DWIDTH_SIZE=" + support::cpp11::to_string(input->info()->dimension(0)));
139 
140  // Create kernel
141  std::string kernel_name;
142  if(norm_info.is_in_map())
143  {
144  kernel_name = "normalization_layer_in_map_" + lower_string(string_from_data_layout(data_layout));
145  }
146  else
147  {
149  {
150  kernel_name = "normalization_layer_cross_map";
151  }
152  else
153  {
154  // 1D Cross-Map normalization in NHWC is the same as 1D In-Map normalization in NCHW
155  kernel_name = "normalization_layer_in_map_nchw";
156  }
157  }
158  _kernel = static_cast<cl::Kernel>(CLKernelLibrary::get().create_kernel(kernel_name, build_opts.options()));
159 
160  // Configure kernel window
161  auto win_config = validate_and_configure_window(input->info(), output->info(), norm_info);
162  ARM_COMPUTE_ERROR_THROW_ON(win_config.first);
163  ICLKernel::configure_internal(win_config.second);
164 
165  // Set config_id for enabling LWS tuning
166  _config_id = "normalization_layer_";
167  _config_id += lower_string(string_from_data_type(input->info()->data_type()));
168  _config_id += "_";
169  _config_id += support::cpp11::to_string(static_cast<std::underlying_type<NormType>::type>(norm_info.type()));
170  _config_id += "_";
171  _config_id += support::cpp11::to_string(norm_info.norm_size());
172  _config_id += "_";
173  _config_id += support::cpp11::to_string(input->info()->dimension(0));
174  _config_id += "_";
175  _config_id += support::cpp11::to_string(input->info()->dimension(1));
176 }
177 
179 {
180  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, norm_info));
181  ARM_COMPUTE_RETURN_ON_ERROR(validate_and_configure_window(input->clone().get(), output->clone().get(), norm_info).first);
182 
183  return Status{};
184 }
185 
186 void CLNormalizationLayerKernel::run(const Window &window, cl::CommandQueue &queue)
187 {
190 
191  const int collapsed_dimension = _is_norm_across_width ? Window::DimZ : 4;
192  Window window_collapsed = window.collapse_if_possible(ICLKernel::window(), collapsed_dimension);
193  Window slice = window_collapsed.first_slice_window_3D();
194 
195  do
196  {
197  unsigned int idx = 0;
198  add_3D_tensor_argument(idx, _input, slice);
199  add_3D_tensor_argument(idx, _output, slice);
200  enqueue(queue, *this, slice, lws_hint());
201  }
202  while(window_collapsed.slide_window_slice_3D(slice));
203 }
float scale_coeff() const
Return the scaling factor of the normalization function.
Definition: Types.h:1741
#define ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(tensor)
Definition: CLValidate.h:34
void run(const Window &window, cl::CommandQueue &queue) override
Enqueue the OpenCL kernel to process the given window on the passed OpenCL command queue.
BorderSize border_size() const override
The size of the border for that kernel.
const Window & window() const
The maximum window the kernel can be executed on.
Definition: IKernel.cpp:28
const DataLayout data_layout
Definition: Im2Col.cpp:146
float kappa() const
Get the kappa value.
Definition: Types.h:1715
bool is_in_map() const
Check if normalization is not cross map.
Definition: Types.h:1730
Container for 2D border size.
Definition: Types.h:269
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:39
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(...)
Definition: Validate.h:494
const StringSet & options() const
Gets the current options list set.
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:545
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:247
uint32_t norm_size() const
Get the normalization size.
Definition: Types.h:1700
NormType type() const
Get the normalization type.
Definition: Types.h:1695
#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.
#define ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(t, c,...)
Definition: Validate.h:792
1 channel, 1 F32 per channel
Normalization Layer Information class.
Definition: Types.h:1677
bool is_cross_map() const
Check if normalization is cross map.
Definition: Types.h:1725
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
Status class.
Definition: Error.h:52
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:333
Window calculate_max_window(const ValidRegion &valid_region, const Steps &steps=Steps(), bool skip_border=false, BorderSize border_size=BorderSize())
Calculate the maximum window for a given tensor shape and border setting.
Definition: Helpers.cpp:28
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:158
Copyright (c) 2017-2020 ARM Limited.
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...
Definition: Helpers.inl:202
1 channel, 1 F16 per channel
Implementation of a static rectangular access pattern.
void add_option(std::string option)
Adds option to the existing build option list.
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:144
bool update_window_and_padding(Window &win, Ts &&... patterns)
Update window and padding size for each of the access patterns.
Definition: Helpers.h:402
Window collapse_if_possible(const Window &full_window, size_t first, size_t last, bool *has_collapsed=nullptr) const
Collapse the dimensions between first and last if possible.
Definition: Window.inl:68
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(...)
Definition: Validate.h:443
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1211
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
Implementation of a row access pattern.
std::string kernel_name
void configure(const ICLTensor *input, ICLTensor *output, NormalizationLayerInfo norm_info)
Set the input and output tensors.
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
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's metadata.
float beta() const
Get the beta value.
Definition: Types.h:1710
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
std::unique_ptr< Kernel > create_kernel()
Helper function to create and return a unique_ptr pointed to a CL/GLES kernel object.
Definition: Helpers.h:86
unsigned int left
left of the border
Definition: Types.h:352
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:333
unsigned int right
right of the border
Definition: Types.h:350
Num samples, channels, height, width.
#define ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(...)
Definition: Validate.h:163
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:161
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:132
virtual size_t total_size() const =0
Returns the total size of the tensor in bytes.
#define ARM_COMPUTE_CREATE_ERROR(error_code, msg)
Creates an error with a given message.
Definition: Error.h:159
static constexpr size_t DimZ
Alias for dimension 2 also known as Z dimension.
Definition: Window.h:47
static Status validate(const ITensorInfo *input, const ITensorInfo *output, NormalizationLayerInfo norm_info)
Static function to check if given info will lead to a valid configuration of CLNormalizationLayerKern...
Num samples, height, width, channels.
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_RETURN_ERROR_ON_DATA_LAYOUT_NOT_IN(t,...)
Definition: Validate.h:746
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:289
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:205
unsigned int get_normalization_dimension_index(DataLayout layout, const NormalizationLayerInfo &info)
Calculate the normalization dimension index for a given normalization type.
Definition: Helpers.h:726
DataLayout
[DataLayout enum definition]
Definition: Types.h:117
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(k)
Definition: Validate.h:941
Normalization applied within the same map in 2D region.
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)