Compute Library
 21.11
ClActivationKernel.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2016-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 
29 #include "arm_compute/core/Utils.h"
30 #include "src/core/CL/CLValidate.h"
33 #include "support/Cast.h"
34 
35 #include "support/StringSupport.h"
36 
37 #include <set>
38 
39 namespace arm_compute
40 {
41 namespace opencl
42 {
43 namespace kernels
44 {
45 namespace
46 {
47 Status validate_arguments(const ITensorInfo *src, const ITensorInfo *dst, const ActivationLayerInfo &act_info)
48 {
51 
52  static std::set<ActivationLayerInfo::ActivationFunction> quantized_supported_activations =
53  {
61  };
62  const DataType data_type = src->data_type();
63  const QuantizationInfo &oq_info = (dst != nullptr) ? dst->quantization_info() : src->quantization_info();
64  const ActivationLayerInfo::ActivationFunction f_act = act_info.activation();
65 
66  ARM_COMPUTE_RETURN_ERROR_ON_MSG(is_data_type_quantized(data_type) && (quantized_supported_activations.count(f_act) == 0),
67  "For Quantized data type only hard swish, leaky relu, tanh, logistic, relu and lower/upper bounded relu are supported");
68 
69  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8 && (f_act == ActivationLayerInfo::ActivationFunction::TANH) && (oq_info != QuantizationInfo(1.f / 128.f, 128)));
70  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8 && (f_act == ActivationLayerInfo::ActivationFunction::LOGISTIC) && (oq_info != QuantizationInfo(1.f / 256.f, 0)));
71 
72  ARM_COMPUTE_RETURN_ERROR_ON(is_data_type_quantized_symmetric(data_type) && (f_act == ActivationLayerInfo::ActivationFunction::TANH) && (oq_info != QuantizationInfo(1.f / 32768.f, 0)));
73  ARM_COMPUTE_RETURN_ERROR_ON(is_data_type_quantized_symmetric(data_type) && (f_act == ActivationLayerInfo::ActivationFunction::LOGISTIC) && (oq_info != QuantizationInfo(1.f / 32768.f, 0)));
74 
75  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8_SIGNED && (f_act == ActivationLayerInfo::ActivationFunction::TANH) && (oq_info != QuantizationInfo(1.f / 128.f, 0)));
76  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8_SIGNED && (f_act == ActivationLayerInfo::ActivationFunction::LOGISTIC) && (oq_info != QuantizationInfo(1.f / 256.f, -128)));
77 
78  // Checks performed when destination is configured
79  if((dst != nullptr) && (dst->total_size() != 0))
80  {
83  }
84 
85  return Status{};
86 }
87 } // namespace
88 
90 {
92 }
93 
95 {
97 
98  auto padding_info = get_padding_info({ src, dst });
99 
100  _run_in_place = (dst == nullptr) || (dst == src);
101 
102  if(dst != nullptr)
103  {
104  // Destination auto inizialitation if not yet initialized
105  auto_init_if_empty(*dst, *src->clone());
106  }
107 
108  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, (dst != nullptr) ? dst : nullptr, act_info));
109 
110  const unsigned int num_elems_processed_per_iteration = adjust_vec_size(16 / src->element_size(), src->dimension(0));
111 
112  const DataType dt = src->data_type();
113  float a_const = act_info.a();
114  float b_const = act_info.b();
115 
116  const ActivationLayerInfo::ActivationFunction f_act = act_info.activation();
117  const bool is_quantized = is_data_type_quantized(dt);
118  const bool perform_activation_in_float =
123 
124  // Set build options
125  CLBuildOptions build_opts;
126  build_opts.add_option_if(perform_activation_in_float, "-DFLOAT_DOMAIN");
127  build_opts.add_option_if(_run_in_place, "-DIN_PLACE");
128  build_opts.add_option("-DACT=" + lower_string(string_from_activation_func(f_act)));
129  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(dt));
130  build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(num_elems_processed_per_iteration));
131  build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(src->dimension(0) % num_elems_processed_per_iteration));
132 
133  std::string kernel_name = std::string("activation_layer");
134 
135  // Set quantization info build options
136  if(is_quantized)
137  {
138  const UniformQuantizationInfo iq_info = src->quantization_info().uniform();
139 
140  if(!perform_activation_in_float)
141  {
142  int a_const_int = 0;
143  int b_const_int = 0;
144 
145  // Create quantized version of constants a, b if needed
146  switch(dt)
147  {
148  case DataType::QASYMM8:
149  {
150  a_const_int = quantize_qasymm8(a_const, iq_info);
151  b_const_int = quantize_qasymm8(b_const, iq_info);
152  }
153  break;
155  {
156  a_const_int = quantize_qasymm8_signed(a_const, iq_info);
157  b_const_int = quantize_qasymm8_signed(b_const, iq_info);
158  }
159  break;
160  case DataType::QSYMM16:
161  {
162  a_const_int = quantize_qsymm16(a_const, iq_info);
163  b_const_int = quantize_qsymm16(b_const, iq_info);
164  }
165  break;
166  default:
167  break;
168  }
169  build_opts.add_option(("-DA_VAL=" + support::cpp11::to_string(a_const_int)));
170  build_opts.add_option(("-DB_VAL=" + support::cpp11::to_string(b_const_int)));
171  }
172  else
173  {
174  build_opts.add_option(("-DA_VAL=" + float_to_string_with_full_precision(a_const)));
175  build_opts.add_option(("-DB_VAL=" + float_to_string_with_full_precision(b_const)));
176  }
177 
178  // Quantized value of 0 corresponds to the offset o1
179  build_opts.add_option(("-DCONST_0=" + (is_data_type_quantized_asymmetric(dt) ? support::cpp11::to_string(iq_info.offset) : "0")));
180  build_opts.add_option(("-DS1_VAL=" + float_to_string_with_full_precision(iq_info.scale)));
182 
183  // Set correct kernel name
184  kernel_name += perform_activation_in_float ? std::string("_quant_f32") : std::string("_quant");
185 
186  // Set scale and offset of the source and destination if they have different quantization info
187  if(dst != nullptr)
188  {
189  const UniformQuantizationInfo oq_info = dst->quantization_info().uniform();
190 
191  if(iq_info != oq_info)
192  {
193  build_opts.add_option(("-DS2_VAL=" + float_to_string_with_full_precision(oq_info.scale)));
195  }
196  }
197  }
198  else
199  {
200  // Set A, B constants in build options for float types
201  build_opts.add_option(("-DA_VAL=" + float_to_string_with_full_precision(a_const)));
202  build_opts.add_option(("-DB_VAL=" + float_to_string_with_full_precision(b_const)));
203  }
204 
205  // Create kernel
206  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
207 
208  // Configure kernel window
209  Window win = calculate_max_window(*src, Steps(num_elems_processed_per_iteration));
210  ICLKernel::configure_internal(win);
211 
212  // Set config_id for enabling LWS tuning
213  _config_id = "activation_layer_";
214  _config_id += lower_string(string_from_data_type(dt));
215  _config_id += "_";
216  _config_id += support::cpp11::to_string(src->dimension(0));
217  _config_id += "_";
218  _config_id += support::cpp11::to_string(src->dimension(1));
219 
221 }
222 
224 {
225  ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, dst, act_info));
226  return Status{};
227 }
228 
229 void ClActivationKernel::run_op(ITensorPack &tensors, const Window &window, ::cl::CommandQueue &queue)
230 {
233 
234  const auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC));
235  auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
236  ARM_COMPUTE_ERROR_ON(_run_in_place && src != dst);
237 
239  Window slice = collapsed.first_slice_window_3D();
240 
241  do
242  {
243  unsigned int idx = 0;
244  add_3D_tensor_argument(idx, src, slice);
245  if(!_run_in_place)
246  {
247  add_3D_tensor_argument(idx, dst, slice);
248  }
249  enqueue(queue, *this, slice, lws_hint());
250  }
251  while(collapsed.slide_window_slice_3D(slice));
252 }
253 } // namespace kernels
254 } // namespace opencl
255 } // namespace arm_compute
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:981
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
int16_t quantize_qsymm16(float value, const UniformQuantizationInfo &qinfo, RoundingPolicy rounding_policy=RoundingPolicy::TO_NEAREST_UP)
Quantize a value given a 16-bit symmetric quantization scheme.
quantized, symmetric fixed-point 16-bit number
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.
uint8_t quantize_qasymm8(float value, const INFO_TYPE &qinfo, RoundingPolicy rounding_policy=RoundingPolicy::TO_NEAREST_UP)
Quantize a value given an unsigned 8-bit asymmetric quantization scheme.
cl::NDRange lws_hint() const
Return the Local-Workgroup-Size hint.
Definition: ICLKernel.h:318
float a() const
Get the alpha value.
Definition: Types.h:1549
#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
#define ARM_COMPUTE_ERROR_THROW_ON(status)
Definition: Error.h:455
Quantization info when assuming per layer quantization.
Status class.
Definition: Error.h:52
std::string lower_string(const std::string &val)
Lower a given string.
Definition: Utils.cpp:326
bool is_data_type_quantized_symmetric(DataType dt)
Check if a given data type is of symmetric quantized type.
Definition: Utils.h:1039
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Activation Layer Information class.
Definition: Types.h:1509
void add_3D_tensor_argument(unsigned int &idx, const ICLTensor *tensor, 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: ICLKernel.h:214
SimpleTensor< float > src
Definition: DFT.cpp:155
Copyright (c) 2017-2021 Arm Limited.
ActivationFunction
Available activation functions.
Definition: Types.h:1513
1 channel, 1 F16 per channel
void add_option(std::string option)
Adds option to the existing build option list.
const DataType data_type
Definition: Im2Col.cpp:150
const ITensor * get_const_tensor(int id) const
Get constant tensor of a given id.
Definition: ITensorPack.cpp:54
void configure(const ClCompileContext &compile_context, ITensorInfo *src, ITensorInfo *dst, ActivationLayerInfo act_info)
Configure kernel for a given list of arguments.
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
const std::string & string_from_data_type(DataType dt)
Convert a data type identity into a string.
Definition: Utils.cpp:135
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
std::string float_to_string_with_full_precision(float val)
Create a string with the float in full precision.
Definition: Utils.h:1075
int8_t quantize_qasymm8_signed(float value, const INFO_TYPE &qinfo, RoundingPolicy rounding_policy=RoundingPolicy::TO_NEAREST_UP)
Quantize a value given a signed 8-bit asymmetric quantization scheme.
quantized, asymmetric fixed-point 8-bit number unsigned
Class to describe a number of elements in each dimension.
Definition: Steps.h:40
unsigned int num_elems_processed_per_iteration
UniformQuantizationInfo uniform() const
Return per layer quantization info.
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.
static Status validate(const ITensorInfo *src, const ITensorInfo *dst, const ActivationLayerInfo &act_info)
Static function to check if given info will lead to a valid configuration.
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 run_op(ITensorPack &tensors, const Window &window, ::cl::CommandQueue &queue) override
Elementeise CL kernel type.
Definition: CLTypes.h:84
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:335
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
#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.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1003
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:64
#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
#define ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(...)
Definition: Validate.h:541
#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_RETURN_ERROR_ON_MSG(cond, msg)
If the condition is true, an error is returned.
Definition: Error.h:244
Tensor packing service.
Definition: ITensorPack.h:39
#define ARM_COMPUTE_ERROR_ON_NULLPTR(...)
Definition: Validate.h:157
unsigned int adjust_vec_size(unsigned int vec_size, size_t dim0)
Returns the adjusted vector size in case it is less than the input&#39;s first dimension, getting rounded down to its closest valid vector size.
Definition: Utils.h:1171
ActivationFunction activation() const
Get the type of activation function.
Definition: Types.h:1544
float b() const
Get the beta value.
Definition: Types.h:1554
quantized, asymmetric fixed-point 8-bit number signed
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
std::string kernel_name
DataType
Available data types.
Definition: Types.h:79
Describe a multidimensional execution window.
Definition: Window.h:39
#define ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(f, s)
Definition: Validate.h:201
SimpleTensor< T > slice(const SimpleTensor< T > &src, Coordinates starts, Coordinates ends)