Compute Library
 21.05
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 
30 #include "arm_compute/core/Utils.h"
31 #include "src/core/CL/CLValidate.h"
34 #include "support/Cast.h"
35 
36 #include "support/StringSupport.h"
37 
38 #include <set>
39 
40 namespace arm_compute
41 {
42 namespace opencl
43 {
44 namespace kernels
45 {
46 namespace
47 {
48 Status validate_arguments(const ITensorInfo *src, const ITensorInfo *dst, const ActivationLayerInfo &act_info)
49 {
52 
53  static std::set<ActivationLayerInfo::ActivationFunction> quantized_supported_activations =
54  {
62  };
63  const DataType data_type = src->data_type();
64  const QuantizationInfo &oq_info = (dst != nullptr) ? dst->quantization_info() : src->quantization_info();
65  const ActivationLayerInfo::ActivationFunction f_act = act_info.activation();
66 
67  ARM_COMPUTE_RETURN_ERROR_ON_MSG(is_data_type_quantized(data_type) && (quantized_supported_activations.count(f_act) == 0),
68  "For Quantized data type only hard swish, leaky relu, tanh, logistic, relu and lower/upper bounded relu are supported");
69 
70  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8 && (f_act == ActivationLayerInfo::ActivationFunction::TANH) && (oq_info != QuantizationInfo(1.f / 128.f, 128)));
71  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8 && (f_act == ActivationLayerInfo::ActivationFunction::LOGISTIC) && (oq_info != QuantizationInfo(1.f / 256.f, 0)));
72 
73  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)));
75 
76  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8_SIGNED && (f_act == ActivationLayerInfo::ActivationFunction::TANH) && (oq_info != QuantizationInfo(1.f / 128.f, 0)));
77  ARM_COMPUTE_RETURN_ERROR_ON(data_type == DataType::QASYMM8_SIGNED && (f_act == ActivationLayerInfo::ActivationFunction::LOGISTIC) && (oq_info != QuantizationInfo(1.f / 256.f, -128)));
78 
79  // Checks performed when destination is configured
80  if((dst != nullptr) && (dst->total_size() != 0))
81  {
84  }
85 
86  return Status{};
87 }
88 } // namespace
89 
91  : _run_in_place(false)
92 {
93 }
94 
96 {
98 
99  auto padding_info = get_padding_info({ src, dst });
100 
101  _run_in_place = (dst == nullptr) || (dst == src);
102 
103  if(dst != nullptr)
104  {
105  // Destination auto inizialitation if not yet initialized
106  auto_init_if_empty(*dst, *src->clone());
107  }
108 
109  ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, (dst != nullptr) ? dst : nullptr, act_info));
110 
111  const unsigned int num_elems_processed_per_iteration = adjust_vec_size(16 / src->element_size(), src->dimension(0));
112 
113  const DataType dt = src->data_type();
114  float a_const = act_info.a();
115  float b_const = act_info.b();
116 
117  const ActivationLayerInfo::ActivationFunction f_act = act_info.activation();
118  const bool is_quantized = is_data_type_quantized(dt);
119  const bool perform_activation_in_float =
124 
125  // Set build options
126  CLBuildOptions build_opts;
127  build_opts.add_option_if(perform_activation_in_float, "-DFLOAT_DOMAIN");
128  build_opts.add_option_if(_run_in_place, "-DIN_PLACE");
129  build_opts.add_option("-DACT=" + lower_string(string_from_activation_func(f_act)));
130  build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(dt));
132  build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(src->dimension(0) % num_elems_processed_per_iteration));
133 
134  std::string kernel_name = std::string("activation_layer");
135 
136  // Set quantization info build options
137  if(is_quantized)
138  {
139  const UniformQuantizationInfo iq_info = src->quantization_info().uniform();
140 
141  if(!perform_activation_in_float)
142  {
143  int a_const_int = 0;
144  int b_const_int = 0;
145 
146  // Create quantized version of constants a, b if needed
147  switch(dt)
148  {
149  case DataType::QASYMM8:
150  {
151  a_const_int = quantize_qasymm8(a_const, iq_info);
152  b_const_int = quantize_qasymm8(b_const, iq_info);
153  }
154  break;
156  {
157  a_const_int = quantize_qasymm8_signed(a_const, iq_info);
158  b_const_int = quantize_qasymm8_signed(b_const, iq_info);
159  }
160  break;
161  case DataType::QSYMM16:
162  {
163  a_const_int = quantize_qsymm16(a_const, iq_info);
164  b_const_int = quantize_qsymm16(b_const, iq_info);
165  }
166  break;
167  default:
168  break;
169  }
170  build_opts.add_option(("-DA_VAL=" + support::cpp11::to_string(a_const_int)));
171  build_opts.add_option(("-DB_VAL=" + support::cpp11::to_string(b_const_int)));
172  }
173  else
174  {
175  build_opts.add_option(("-DA_VAL=" + float_to_string_with_full_precision(a_const)));
176  build_opts.add_option(("-DB_VAL=" + float_to_string_with_full_precision(b_const)));
177  }
178 
179  // Quantized value of 0 corresponds to the offset o1
180  build_opts.add_option(("-DCONST_0=" + (is_data_type_quantized_asymmetric(dt) ? support::cpp11::to_string(iq_info.offset) : "0")));
181  build_opts.add_option(("-DS1_VAL=" + float_to_string_with_full_precision(iq_info.scale)));
183 
184  // Set correct kernel name
185  kernel_name += perform_activation_in_float ? std::string("_quant_f32") : std::string("_quant");
186 
187  // Set scale and offset of the source and destination if they have different quantization info
188  if(dst != nullptr)
189  {
190  const UniformQuantizationInfo oq_info = dst->quantization_info().uniform();
191 
192  if(iq_info != oq_info)
193  {
194  build_opts.add_option(("-DS2_VAL=" + float_to_string_with_full_precision(oq_info.scale)));
196  }
197  }
198  }
199  else
200  {
201  // Set A, B constants in build options for float types
202  build_opts.add_option(("-DA_VAL=" + float_to_string_with_full_precision(a_const)));
203  build_opts.add_option(("-DB_VAL=" + float_to_string_with_full_precision(b_const)));
204  }
205 
206  // Create kernel
207  _kernel = create_kernel(compile_context, kernel_name, build_opts.options());
208 
209  // Configure kernel window
211  ICLKernel::configure_internal(win);
212 
213  // Set config_id for enabling LWS tuning
214  _config_id = "activation_layer_";
215  _config_id += lower_string(string_from_data_type(dt));
216  _config_id += "_";
217  _config_id += support::cpp11::to_string(src->dimension(0));
218  _config_id += "_";
219  _config_id += support::cpp11::to_string(src->dimension(1));
220 
222 }
223 
225 {
227  return Status{};
228 }
229 
230 void ClActivationKernel::run_op(ITensorPack &tensors, const Window &window, ::cl::CommandQueue &queue)
231 {
234 
235  const auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC));
236  auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
237  ARM_COMPUTE_ERROR_ON(_run_in_place && src != dst);
238 
240  Window slice = collapsed.first_slice_window_3D();
241 
242  do
243  {
244  unsigned int idx = 0;
246  if(!_run_in_place)
247  {
249  }
250  enqueue(queue, *this, slice, lws_hint());
251  }
252  while(collapsed.slide_window_slice_3D(slice));
253 }
254 } // namespace kernels
255 } // namespace opencl
256 } // namespace arm_compute
bool is_data_type_quantized(DataType dt)
Check if a given data type is of quantized type.
Definition: Utils.h:967
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
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:489
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:276
float a() const
Get the alpha value.
Definition: Types.h:1518
#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.
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'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:1025
#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:1478
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:172
SimpleTensor< float > src
Definition: DFT.cpp:155
Copyright (c) 2017-2021 Arm Limited.
ActivationFunction
Available activation functions.
Definition: Types.h:1482
1 channel, 1 F16 per channel
DataType dt
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:45
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:403
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:1061
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
std::string kernel_name
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...
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 of ClActivationKernel.
void add_option_if(bool cond, std::string option)
Adds option if a given condition is true;.
void run_op(ITensorPack &tensors, const Window &window, ::cl::CommandQueue &queue) override
bool slide_window_slice_3D(Window &slice) const
Slide the passed 3D window slice.
Definition: Window.h:335
#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:504
CLCompileContext class.
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:989
ITensor * get_tensor(int id)
Get tensor of a given id from the pac.
Definition: ITensorPack.cpp:55
#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
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
Tensor packing service.
Definition: ITensorPack.h:37
#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's first dimension,...
Definition: Utils.h:1157
ActivationFunction activation() const
Get the type of activation function.
Definition: Types.h:1513
float b() const
Get the beta value.
Definition: Types.h:1523
quantized, asymmetric fixed-point 8-bit number signed
Window first_slice_window_3D() const
First 3D slice of the window.
Definition: Window.h:291
DataType
Available data types.
Definition: Types.h:77
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)