Compute Library
 21.08
AsymmHelpers.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-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  */
27 
28 #include <cmath>
29 #include <limits>
30 #include <numeric>
31 
32 namespace arm_compute
33 {
34 namespace quantization
35 {
36 constexpr int64_t fixed_point_one_Q0 = (1LL << 31);
37 constexpr float epsilon = 0.00001f;
38 
39 Status calculate_quantized_multiplier(float multiplier, int32_t *quant_multiplier, int32_t *shift, bool ignore_epsilon)
40 {
41  if(multiplier >= 1.f)
42  {
43  Status status = calculate_quantized_multiplier_greater_than_one(multiplier, quant_multiplier, shift);
44  *shift *= -1;
45  return status;
46  }
47  else
48  {
49  return calculate_quantized_multiplier_less_than_one(multiplier, quant_multiplier, shift, ignore_epsilon);
50  }
51 }
52 
54  int32_t *quant_multiplier,
55  int32_t *right_shift,
56  bool ignore_epsilon)
57 {
58  const float internal_epsilon = ignore_epsilon ? 0.0f : epsilon;
59 
60  ARM_COMPUTE_RETURN_ERROR_ON(quant_multiplier == nullptr);
61  ARM_COMPUTE_RETURN_ERROR_ON(right_shift == nullptr);
62  ARM_COMPUTE_RETURN_ERROR_ON(multiplier < -internal_epsilon);
63  ARM_COMPUTE_RETURN_ERROR_ON(multiplier > 1.0f + internal_epsilon);
64  if(std::fabs(0.0f - multiplier) < internal_epsilon)
65  {
66  *quant_multiplier = 0;
67  *right_shift = 0;
68  return Status{};
69  }
70 
71  int shift_exp = 0;
72  const double q = std::frexp(multiplier, &shift_exp);
73  *right_shift = -1 * shift_exp;
74  auto q_fixed = static_cast<int64_t>(support::cpp11::round(q * fixed_point_one_Q0));
75  ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > fixed_point_one_Q0);
76  if(q_fixed == fixed_point_one_Q0)
77  {
78  q_fixed /= 2;
79  --*right_shift;
80  }
81 
82  if(ignore_epsilon && *right_shift > 31)
83  {
84  *right_shift = 0;
85  q_fixed = 0;
86  }
87 
88  ARM_COMPUTE_RETURN_ERROR_ON(*right_shift < 0);
89  ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > std::numeric_limits<int32_t>::max());
90  *quant_multiplier = static_cast<int32_t>(q_fixed);
91 
92  return Status{};
93 }
94 
96  int32_t *quantized_multiplier,
97  int32_t *left_shift)
98 {
99  ARM_COMPUTE_RETURN_ERROR_ON(quantized_multiplier == nullptr);
100  ARM_COMPUTE_RETURN_ERROR_ON(left_shift == nullptr);
101  ARM_COMPUTE_RETURN_ERROR_ON(multiplier < 1.f);
102 
103  int shift_exp = 0;
104  const double q = std::frexp(multiplier, &shift_exp);
105  *left_shift = shift_exp;
106  auto q_fixed = static_cast<int64_t>(support::cpp11::round(q * fixed_point_one_Q0));
107  ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > fixed_point_one_Q0);
108  if(q_fixed == fixed_point_one_Q0)
109  {
110  q_fixed /= 2;
111  ++*left_shift;
112  }
113  ARM_COMPUTE_RETURN_ERROR_ON(*left_shift < 0);
114  ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > std::numeric_limits<int32_t>::max());
115  *quantized_multiplier = static_cast<int32_t>(q_fixed);
116 
117  return Status{};
118 }
119 
121  const QuantizationInfo &wq_info,
122  const QuantizationInfo &oq_info,
123  GEMMLowpOutputStageInfo &stage_info)
124 {
125  ARM_COMPUTE_RETURN_ERROR_ON(iq_info.scale().empty());
126  ARM_COMPUTE_RETURN_ERROR_ON(wq_info.scale().empty());
127  ARM_COMPUTE_RETURN_ERROR_ON(oq_info.scale().empty());
128 
129  const unsigned int size = wq_info.scale().size();
130 
131  auto &quant_multipliers = stage_info.gemmlowp_multipliers;
132  auto &quant_shifts = stage_info.gemmlowp_shifts;
133  quant_multipliers.resize(size);
134  quant_shifts.resize(size);
135 
136  const auto &w_scales = wq_info.scale();
137  const float i_scale = iq_info.scale().at(0);
138  const float o_scale = oq_info.scale().at(0);
139 
140  for(unsigned int i = 0; i < size; ++i)
141  {
142  const float multiplier = i_scale * w_scales[i] / o_scale;
143  int32_t quant_multiplier = 0;
144  int32_t quant_shift = 0;
145  ARM_COMPUTE_RETURN_ON_ERROR(calculate_quantized_multiplier(multiplier, &quant_multiplier, &quant_shift));
146  quant_multipliers[i] = quant_multiplier;
147  quant_shifts[i] = quant_shift;
148  }
149 
150  // Legacy part
151  stage_info.gemmlowp_shift = quant_shifts[0];
152  stage_info.gemmlowp_multiplier = quant_multipliers[0];
153 
154  return Status{};
155 }
156 
158 {
159  int min_quant_val = 0;
160  int max_quant_val = 0;
161  switch(data_type)
162  {
163  case DataType::QASYMM8:
164  min_quant_val = std::numeric_limits<uint8_t>::min();
165  max_quant_val = std::numeric_limits<uint8_t>::max();
166  break;
167  case DataType::QSYMM8:
169  min_quant_val = std::numeric_limits<int8_t>::min();
170  max_quant_val = std::numeric_limits<int8_t>::max();
171  break;
172  case DataType::QASYMM16:
173  min_quant_val = std::numeric_limits<uint16_t>::min();
174  max_quant_val = std::numeric_limits<uint16_t>::max();
175  break;
176  case DataType::QSYMM16:
177  min_quant_val = std::numeric_limits<int16_t>::min();
178  max_quant_val = std::numeric_limits<int16_t>::max();
179  break;
180  default:
181  ARM_COMPUTE_ERROR("Unsupported data type");
182  }
183  return std::make_pair(min_quant_val, max_quant_val);
184 }
186  const ITensorInfo *weights,
187  const ITensorInfo *output,
188  int32_t *output_multipliers_ptr,
189  int32_t *output_shifts_ptr)
190 {
191  const UniformQuantizationInfo iq_info = input->quantization_info().uniform();
192  const QuantizationInfo wq_info = weights->quantization_info();
193  const UniformQuantizationInfo oq_info = output->quantization_info().uniform();
194 
195  const unsigned int num_filters = wq_info.scale().size();
196 
197  for(unsigned int i = 0; i < num_filters; ++i)
198  {
199  int32_t output_multiplier = 0;
200  int32_t output_shift = 0;
201  const float multiplier = iq_info.scale * wq_info.scale()[i] / oq_info.scale;
202  calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift);
203 
204  output_multipliers_ptr[i] = output_multiplier;
205  output_shifts_ptr[i] = output_shift;
206  }
207 }
208 
209 int32_t saturating_rounding_doubling_highmul(int32_t a, int32_t b)
210 {
211  bool overflow = a == b && a == std::numeric_limits<int32_t>::min();
212  int64_t a_64(a);
213  int64_t b_64(b);
214  int64_t ab_64 = a_64 * b_64;
215  bool is_positive_or_zero = a == 0 || b == 0 || (std::signbit(a) == std::signbit(b));
216  int32_t nudge = is_positive_or_zero ? (1 << 30) : (1 - (1 << 30));
217  int32_t ab_x2_high32 = static_cast<int32_t>((ab_64 + nudge) / (1ll << 31));
218  return overflow ? std::numeric_limits<int32_t>::max() : ab_x2_high32;
219 }
220 
221 inline int32_t rounding_divide_by_pow2(int32_t x, int exponent)
222 {
223  const int32_t mask = (1 << exponent) - 1;
224  const int32_t threshold = (mask >> 1) + (x < 0 ? 1 : 0);
225  return (x >> exponent) + ((x & mask) > threshold ? 1 : 0);
226 }
227 
228 int32_t multiply_by_quantized_multiplier(int32_t input, int32_t qmul, int32_t shift)
229 {
230  const auto left_shift = shift > 0 ? shift : 0;
231  const auto right_shift = shift > 0 ? 0 : -shift;
232  return rounding_divide_by_pow2(saturating_rounding_doubling_highmul(input * (1 << left_shift), qmul), right_shift);
233 }
234 
235 int32_t saturating_rounding_multiply_by_pow2(int32_t exponent, int32_t v)
236 {
237  if(exponent == 0)
238  {
239  return v;
240  }
241  else if(exponent < 0)
242  {
243  return rounding_divide_by_pow2(v, -exponent);
244  }
245  else
246  {
247  constexpr auto min = std::numeric_limits<int32_t>::min();
248  constexpr auto max = std::numeric_limits<int32_t>::max();
249  const auto width = sizeof(int32_t) * 8;
250 
251  const int32_t threshold = ((1 << (width - 1 - exponent)) - 1);
252  bool pos_mask = v > threshold;
253  bool neg_mask = v < -threshold;
254  int32_t result = v << exponent;
255  result = pos_mask ? max : result;
256  result = neg_mask ? min : result;
257  return result;
258  }
259 }
260 
261 void get_invsqrt_quantized_multiplier_exp(int32_t input, int32_t reverse_shift, int32_t &output_inv_sqrt, int32_t &output_shift)
262 {
263  ARM_COMPUTE_ERROR_ON(input < 0);
264 
265  if(input <= 1)
266  {
267  // dealing the inputs (0 and 1) separately to avoid overflow
268  output_inv_sqrt = std::numeric_limits<std::int32_t>::max();
269  output_shift = 0;
270  return;
271  }
272 
273  // prepare input for fixed point operation and compute shift value
274  output_shift = 11;
275  while(input >= (1 << 29))
276  {
277  input /= 4;
278  ++output_shift;
279  }
280 
281  const uint32_t max_left_shift_bits = __builtin_clz(static_cast<uint32_t>(input)) - 1;
282  const uint32_t max_left_shift_bits_pairs = max_left_shift_bits / 2;
283  const uint32_t left_shift_bit_pairs = max_left_shift_bits_pairs - 1;
284  output_shift -= left_shift_bit_pairs;
285  input <<= 2 * left_shift_bit_pairs;
286 
287  // Calculation in fixed point domain with 3 integer bits.
288  using FixedPointRawType = int32_t;
289  constexpr uint32_t fixedpoint_position = 3;
290  constexpr uint32_t fixedpoint_int_position = sizeof(FixedPointRawType) * 8 - 1 - fixedpoint_position;
291  using FixedPoint3 = FixedPointRawType;
292  using FixedPoint0 = FixedPointRawType;
293 
294  // fixed point representation of input divided by 2 and 1.5 for Newton-Raphson iteration
295  const FixedPoint3 fixedpoint_input = (input >> 1);
296  const FixedPoint3 fixedpoint_half_input = rounding_divide_by_pow2(fixedpoint_input, 1);
297  const FixedPoint3 fixedpoint_half_three = (0x1 << fixedpoint_int_position) + (0x1 << (fixedpoint_int_position - 1));
298 
299  // initial guess (1) in fixed point representation
300  FixedPoint3 x = 0x1 << fixedpoint_int_position;
301 
302  // multiplication of two fixed point numbers, defined for readability
303  auto fixed_point_mul = [](FixedPointRawType a, FixedPointRawType b) -> FixedPointRawType
304  {
306  };
307 
308  // rescaling of fixed point to have dst_bit integer bits, defined for readability
309  auto fixed_point_rescale = [](FixedPointRawType a, uint32_t src_bit, uint32_t dst_bit) -> FixedPointRawType
310  {
311  const uint32_t exponent = src_bit - dst_bit;
312  return saturating_rounding_multiply_by_pow2(exponent, a);
313  };
314 
315  // 5 iterations of Newton-Raphson method for inverse square root - 1.5 * x_n = input/2 * (x_n)^3
316  constexpr int32_t num_iteration = 5;
317  for(int32_t i = 0; i < num_iteration; ++i)
318  {
319  const auto x3 = fixed_point_rescale(fixed_point_mul(fixed_point_mul(x, x), x), 9, fixedpoint_position);
320  x = fixed_point_rescale(fixed_point_mul(fixedpoint_half_three, x) - fixed_point_mul(fixedpoint_half_input, x3), 6, fixedpoint_position);
321  }
322 
323  // fixed point representation of sqrt(1/2)
324  const FixedPoint0 fixedpoint_half_sqrt_2 = 1518500250;
325  x = fixed_point_mul(fixedpoint_half_sqrt_2, x);
326  output_inv_sqrt = x;
327  if(output_shift < 0)
328  {
329  output_inv_sqrt <<= -output_shift;
330  output_shift = 0;
331  }
332  // convert right shift to left shift
333  output_shift *= reverse_shift;
334 }
335 } // quantization
336 } // arm_compute
int32_t gemmlowp_multiplier
GEMMLowp output stage multiplier used for quantizing to QASYMM8.
Definition: Types.h:1892
quantized, symmetric fixed-point 16-bit number
SimpleTensor< float > b
Definition: DFT.cpp:157
#define ARM_COMPUTE_ERROR(msg)
Print the given message then throw an std::runtime_error.
Definition: Error.h:352
#define ARM_COMPUTE_RETURN_ON_ERROR(status)
Checks if a status contains an error and returns it.
Definition: Error.h:204
#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&#39;s metadata.
Definition: ITensorInfo.h:40
Quantization info when assuming per layer quantization.
quantized, asymmetric fixed-point 16-bit number
Status calculate_quantized_multiplier(float multiplier, int32_t *quant_multiplier, int32_t *shift, bool ignore_epsilon=false)
Calculate quantized representation of multiplier.
Status class.
Definition: Error.h:52
Status calculate_quantized_multiplier_greater_than_one(float multiplier, int32_t *quantized_multiplier, int32_t *left_shift)
Calculate quantized representation of multiplier having value greater than one.
#define ARM_COMPUTE_RETURN_ERROR_ON(cond)
If the condition is true, an error is returned.
Definition: Error.h:296
Copyright (c) 2017-2021 Arm Limited.
std::vector< int32_t > gemmlowp_shifts
GEMMLowp output stage multiplier used for quantizing to QASYMM8.
Definition: Types.h:1897
const DataType data_type
Definition: Im2Col.cpp:150
Quantization information.
std::pair< int, int > get_min_max_values_from_quantized_data_type(DataType data_type)
Get minimum and maximum values for the input quantized data type.
void get_invsqrt_quantized_multiplier_exp(int32_t input, int32_t reverse_shift, int32_t &output_inv_sqrt, int32_t &output_shift)
Compute quantized multiplier and shift for the inverse square root of input.
int32_t saturating_rounding_doubling_highmul(int32_t a, int32_t b)
Compute multiplication of two integers.
Status calculate_quantized_multipliers(const QuantizationInfo &iq_info, const QuantizationInfo &wq_info, const QuantizationInfo &oq_info, GEMMLowpOutputStageInfo &stage_info)
Calculate quantized representation of per-channel multipliers.
int32_t multiply_by_quantized_multiplier(int32_t input, int32_t qmul, int32_t shift)
Compute the value multiplied by given quantized multiplier and shift.
quantized, asymmetric fixed-point 8-bit number unsigned
std::vector< int32_t > gemmlowp_multipliers
GEMMLowp output stage multiplier used for quantizing to QASYMM8.
Definition: Types.h:1896
UniformQuantizationInfo uniform() const
Return per layer quantization info.
GEMMLowp output stage info.
Definition: Types.h:1888
const std::vector< float > & scale() const
Scale vector accessor.
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
quantized, symmetric fixed-point 8-bit number
int32_t rounding_divide_by_pow2(int32_t x, int exponent)
Round to the nearest division by a power-of-two using exponent, copied from NEMath.
int32_t gemmlowp_shift
GEMMLowp output stage shift used for quantizing to uint8.
Definition: Types.h:1893
void compute_quantized_multipliers_and_shifts(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *output, int32_t *output_multipliers_ptr, int32_t *output_shifts_ptr)
Compute quantized per-channel multipliers and shifts.
constexpr int64_t fixed_point_one_Q0
T round(T value)
Round floating-point value with half value rounding away from zero.
int32_t saturating_rounding_multiply_by_pow2(int32_t exponent, int32_t v)
Compute the value multiplied the power-of-two.
quantized, asymmetric fixed-point 8-bit number signed
Status calculate_quantized_multiplier_less_than_one(float multiplier, int32_t *quant_multiplier, int32_t *right_shift, bool ignore_epsilon=false)
Calculate quantized representation of multiplier with value less than one.
DataType
Available data types.
Definition: Types.h:77