blob: eb008639b1f12504e7425b951a1fc7cdf8131b74 [file] [log] [blame]
Chunosovd621bca2017-11-03 17:33:15 +07001/*
Pablo Tello4e66d702022-03-07 18:20:12 +00002 * Copyright (c) 2017-2022 Arm Limited.
Chunosovd621bca2017-11-03 17:33:15 +07003 *
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 */
24#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
Michele Di Giorgiodf4cf572019-10-09 15:32:39 +010025#include "arm_compute/core/Helpers.h"
Matthew Bentham758b5ba2020-03-05 23:37:48 +000026#include "support/ToolchainSupport.h"
Chunosovd621bca2017-11-03 17:33:15 +070027
28#include <cmath>
29#include <limits>
30#include <numeric>
31
Michele Di Giorgiod87a7b22019-09-10 10:42:27 +010032namespace arm_compute
33{
34namespace quantization
35{
Michalis Spyrou299fdd32019-05-01 13:03:59 +010036constexpr int64_t fixed_point_one_Q0 = (1LL << 31);
Gian Marco Iodice3139f032018-11-05 14:26:32 +000037constexpr float epsilon = 0.00001f;
Chunosovf450caa2017-11-08 16:09:35 +070038
Sang-Hoon Park30b46a62020-04-18 01:40:57 +010039Status calculate_quantized_multiplier(float multiplier, int32_t *quant_multiplier, int32_t *shift, bool ignore_epsilon)
Manuel Bottini07263982019-10-17 18:37:26 +010040{
Michele Di Giorgio35c37942019-12-03 19:34:30 +000041 if(multiplier >= 1.f)
Manuel Bottini07263982019-10-17 18:37:26 +010042 {
43 Status status = calculate_quantized_multiplier_greater_than_one(multiplier, quant_multiplier, shift);
44 *shift *= -1;
45 return status;
46 }
47 else
48 {
Sang-Hoon Park30b46a62020-04-18 01:40:57 +010049 return calculate_quantized_multiplier_less_than_one(multiplier, quant_multiplier, shift, ignore_epsilon);
Manuel Bottini07263982019-10-17 18:37:26 +010050 }
51}
52
Michalis Spyroue7be8a02019-12-12 16:16:09 +000053Status calculate_quantized_multiplier_less_than_one(float multiplier,
54 int32_t *quant_multiplier,
Sang-Hoon Park30b46a62020-04-18 01:40:57 +010055 int32_t *right_shift,
56 bool ignore_epsilon)
Chunosovd621bca2017-11-03 17:33:15 +070057{
Sang-Hoon Park30b46a62020-04-18 01:40:57 +010058 const float internal_epsilon = ignore_epsilon ? 0.0f : epsilon;
59
Chunosovd621bca2017-11-03 17:33:15 +070060 ARM_COMPUTE_RETURN_ERROR_ON(quant_multiplier == nullptr);
61 ARM_COMPUTE_RETURN_ERROR_ON(right_shift == nullptr);
Sang-Hoon Park30b46a62020-04-18 01:40:57 +010062 ARM_COMPUTE_RETURN_ERROR_ON(multiplier < -internal_epsilon);
63 ARM_COMPUTE_RETURN_ERROR_ON(multiplier > 1.0f + internal_epsilon);
Gian Marco Iodice3139f032018-11-05 14:26:32 +000064
Michalis Spyroue7be8a02019-12-12 16:16:09 +000065 int shift_exp = 0;
66 const double q = std::frexp(multiplier, &shift_exp);
67 *right_shift = -1 * shift_exp;
68 auto q_fixed = static_cast<int64_t>(support::cpp11::round(q * fixed_point_one_Q0));
Chunosovf450caa2017-11-08 16:09:35 +070069 ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > fixed_point_one_Q0);
70 if(q_fixed == fixed_point_one_Q0)
Chunosovd621bca2017-11-03 17:33:15 +070071 {
72 q_fixed /= 2;
73 --*right_shift;
74 }
Sang-Hoon Park30b46a62020-04-18 01:40:57 +010075
76 if(ignore_epsilon && *right_shift > 31)
77 {
78 *right_shift = 0;
79 q_fixed = 0;
80 }
81
Chunosovd621bca2017-11-03 17:33:15 +070082 ARM_COMPUTE_RETURN_ERROR_ON(*right_shift < 0);
83 ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > std::numeric_limits<int32_t>::max());
Chunosovf450caa2017-11-08 16:09:35 +070084 *quant_multiplier = static_cast<int32_t>(q_fixed);
Chunosovd621bca2017-11-03 17:33:15 +070085
Michele Di Giorgiod87a7b22019-09-10 10:42:27 +010086 return Status{};
Chunosovf450caa2017-11-08 16:09:35 +070087}
88
Michalis Spyroue7be8a02019-12-12 16:16:09 +000089Status calculate_quantized_multiplier_greater_than_one(float multiplier,
90 int32_t *quantized_multiplier,
91 int32_t *left_shift)
Chunosovf450caa2017-11-08 16:09:35 +070092{
93 ARM_COMPUTE_RETURN_ERROR_ON(quantized_multiplier == nullptr);
94 ARM_COMPUTE_RETURN_ERROR_ON(left_shift == nullptr);
95 ARM_COMPUTE_RETURN_ERROR_ON(multiplier < 1.f);
Michalis Spyroue7be8a02019-12-12 16:16:09 +000096
97 int shift_exp = 0;
98 const double q = std::frexp(multiplier, &shift_exp);
99 *left_shift = shift_exp;
100 auto q_fixed = static_cast<int64_t>(support::cpp11::round(q * fixed_point_one_Q0));
Chunosovf450caa2017-11-08 16:09:35 +0700101 ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > fixed_point_one_Q0);
102 if(q_fixed == fixed_point_one_Q0)
103 {
104 q_fixed /= 2;
105 ++*left_shift;
106 }
107 ARM_COMPUTE_RETURN_ERROR_ON(*left_shift < 0);
108 ARM_COMPUTE_RETURN_ERROR_ON(q_fixed > std::numeric_limits<int32_t>::max());
109 *quantized_multiplier = static_cast<int32_t>(q_fixed);
110
Michele Di Giorgiod87a7b22019-09-10 10:42:27 +0100111 return Status{};
Chunosovf450caa2017-11-08 16:09:35 +0700112}
Georgios Pinitasdbdea0d2019-10-16 19:21:40 +0100113
Michele Di Giorgiof29d1b72019-10-29 10:58:13 +0000114arm_compute::Status calculate_quantized_multipliers(const QuantizationInfo &iq_info,
115 const QuantizationInfo &wq_info,
116 const QuantizationInfo &oq_info,
117 GEMMLowpOutputStageInfo &stage_info)
Georgios Pinitasdbdea0d2019-10-16 19:21:40 +0100118{
119 ARM_COMPUTE_RETURN_ERROR_ON(iq_info.scale().empty());
120 ARM_COMPUTE_RETURN_ERROR_ON(wq_info.scale().empty());
121 ARM_COMPUTE_RETURN_ERROR_ON(oq_info.scale().empty());
122
123 const unsigned int size = wq_info.scale().size();
124
125 auto &quant_multipliers = stage_info.gemmlowp_multipliers;
126 auto &quant_shifts = stage_info.gemmlowp_shifts;
127 quant_multipliers.resize(size);
128 quant_shifts.resize(size);
129
130 const auto &w_scales = wq_info.scale();
131 const float i_scale = iq_info.scale().at(0);
132 const float o_scale = oq_info.scale().at(0);
133
134 for(unsigned int i = 0; i < size; ++i)
135 {
136 const float multiplier = i_scale * w_scales[i] / o_scale;
Michalis Spyroue7be8a02019-12-12 16:16:09 +0000137 int32_t quant_multiplier = 0;
138 int32_t quant_shift = 0;
Michele Di Giorgiof29d1b72019-10-29 10:58:13 +0000139 ARM_COMPUTE_RETURN_ON_ERROR(calculate_quantized_multiplier(multiplier, &quant_multiplier, &quant_shift));
Georgios Pinitasdbdea0d2019-10-16 19:21:40 +0100140 quant_multipliers[i] = quant_multiplier;
141 quant_shifts[i] = quant_shift;
142 }
143
144 // Legacy part
145 stage_info.gemmlowp_shift = quant_shifts[0];
146 stage_info.gemmlowp_multiplier = quant_multipliers[0];
147
148 return Status{};
149}
150
Michele Di Giorgiod87a7b22019-09-10 10:42:27 +0100151std::pair<int, int> get_min_max_values_from_quantized_data_type(DataType data_type)
152{
153 int min_quant_val = 0;
154 int max_quant_val = 0;
155 switch(data_type)
156 {
157 case DataType::QASYMM8:
158 min_quant_val = std::numeric_limits<uint8_t>::min();
159 max_quant_val = std::numeric_limits<uint8_t>::max();
160 break;
161 case DataType::QSYMM8:
Manuel Bottini8481d832019-12-10 15:28:40 +0000162 case DataType::QASYMM8_SIGNED:
Michele Di Giorgiod87a7b22019-09-10 10:42:27 +0100163 min_quant_val = std::numeric_limits<int8_t>::min();
164 max_quant_val = std::numeric_limits<int8_t>::max();
165 break;
166 case DataType::QASYMM16:
167 min_quant_val = std::numeric_limits<uint16_t>::min();
168 max_quant_val = std::numeric_limits<uint16_t>::max();
169 break;
170 case DataType::QSYMM16:
171 min_quant_val = std::numeric_limits<int16_t>::min();
172 max_quant_val = std::numeric_limits<int16_t>::max();
173 break;
174 default:
175 ARM_COMPUTE_ERROR("Unsupported data type");
176 }
177 return std::make_pair(min_quant_val, max_quant_val);
178}
Vidhya Sudhan Loganathan951b8a42019-11-04 14:42:08 +0000179void compute_quantized_multipliers_and_shifts(const ITensorInfo *input,
180 const ITensorInfo *weights,
181 const ITensorInfo *output,
Vidhya Sudhan Loganathan951b8a42019-11-04 14:42:08 +0000182 int32_t *output_multipliers_ptr,
183 int32_t *output_shifts_ptr)
Michele Di Giorgiodf4cf572019-10-09 15:32:39 +0100184{
Vidhya Sudhan Loganathan951b8a42019-11-04 14:42:08 +0000185 const UniformQuantizationInfo iq_info = input->quantization_info().uniform();
186 const QuantizationInfo wq_info = weights->quantization_info();
187 const UniformQuantizationInfo oq_info = output->quantization_info().uniform();
Michele Di Giorgiodf4cf572019-10-09 15:32:39 +0100188
Michele Di Giorgiod02d5ed2021-01-22 09:47:04 +0000189 const unsigned int num_filters = wq_info.scale().size();
190
Michele Di Giorgiodf4cf572019-10-09 15:32:39 +0100191 for(unsigned int i = 0; i < num_filters; ++i)
192 {
Michalis Spyroue7be8a02019-12-12 16:16:09 +0000193 int32_t output_multiplier = 0;
194 int32_t output_shift = 0;
Michele Di Giorgiodf4cf572019-10-09 15:32:39 +0100195 const float multiplier = iq_info.scale * wq_info.scale()[i] / oq_info.scale;
Michele Di Giorgio14cbfb22019-10-23 10:53:10 +0100196 calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift);
Michele Di Giorgiodf4cf572019-10-09 15:32:39 +0100197
198 output_multipliers_ptr[i] = output_multiplier;
199 output_shifts_ptr[i] = output_shift;
200 }
201}
Sang-Hoon Park396cb952020-03-26 14:02:37 +0000202
203int32_t saturating_rounding_doubling_highmul(int32_t a, int32_t b)
204{
205 bool overflow = a == b && a == std::numeric_limits<int32_t>::min();
206 int64_t a_64(a);
207 int64_t b_64(b);
Sang-Hoon Park0d008f72020-03-13 14:56:05 +0000208 int64_t ab_64 = a_64 * b_64;
Pablo Tello4e66d702022-03-07 18:20:12 +0000209 const bool is_positive_or_zero =
210 a == 0 || b == 0 ||
211 (std::signbit(static_cast<double>(a)) == std::signbit(static_cast<double>(b)));
Sang-Hoon Park0d008f72020-03-13 14:56:05 +0000212 int32_t nudge = is_positive_or_zero ? (1 << 30) : (1 - (1 << 30));
213 int32_t ab_x2_high32 = static_cast<int32_t>((ab_64 + nudge) / (1ll << 31));
Sang-Hoon Park396cb952020-03-26 14:02:37 +0000214 return overflow ? std::numeric_limits<int32_t>::max() : ab_x2_high32;
215}
216
217inline int32_t rounding_divide_by_pow2(int32_t x, int exponent)
218{
219 const int32_t mask = (1 << exponent) - 1;
220 const int32_t threshold = (mask >> 1) + (x < 0 ? 1 : 0);
221 return (x >> exponent) + ((x & mask) > threshold ? 1 : 0);
222}
223
Sang-Hoon Park0d008f72020-03-13 14:56:05 +0000224int32_t multiply_by_quantized_multiplier(int32_t input, int32_t qmul, int32_t shift)
Sang-Hoon Park396cb952020-03-26 14:02:37 +0000225{
226 const auto left_shift = shift > 0 ? shift : 0;
227 const auto right_shift = shift > 0 ? 0 : -shift;
228 return rounding_divide_by_pow2(saturating_rounding_doubling_highmul(input * (1 << left_shift), qmul), right_shift);
229}
230
231int32_t saturating_rounding_multiply_by_pow2(int32_t exponent, int32_t v)
232{
233 if(exponent == 0)
234 {
235 return v;
236 }
237 else if(exponent < 0)
238 {
239 return rounding_divide_by_pow2(v, -exponent);
240 }
241 else
242 {
243 constexpr auto min = std::numeric_limits<int32_t>::min();
244 constexpr auto max = std::numeric_limits<int32_t>::max();
245 const auto width = sizeof(int32_t) * 8;
246
247 const int32_t threshold = ((1 << (width - 1 - exponent)) - 1);
248 bool pos_mask = v > threshold;
249 bool neg_mask = v < -threshold;
250 int32_t result = v << exponent;
251 result = pos_mask ? max : result;
252 result = neg_mask ? min : result;
253 return result;
254 }
255}
Sang-Hoon Park0d008f72020-03-13 14:56:05 +0000256
257void get_invsqrt_quantized_multiplier_exp(int32_t input, int32_t reverse_shift, int32_t &output_inv_sqrt, int32_t &output_shift)
258{
259 ARM_COMPUTE_ERROR_ON(input < 0);
260
261 if(input <= 1)
262 {
263 // dealing the inputs (0 and 1) separately to avoid overflow
264 output_inv_sqrt = std::numeric_limits<std::int32_t>::max();
265 output_shift = 0;
266 return;
267 }
268
269 // prepare input for fixed point operation and compute shift value
270 output_shift = 11;
271 while(input >= (1 << 29))
272 {
273 input /= 4;
274 ++output_shift;
275 }
276
277 const uint32_t max_left_shift_bits = __builtin_clz(static_cast<uint32_t>(input)) - 1;
278 const uint32_t max_left_shift_bits_pairs = max_left_shift_bits / 2;
279 const uint32_t left_shift_bit_pairs = max_left_shift_bits_pairs - 1;
280 output_shift -= left_shift_bit_pairs;
281 input <<= 2 * left_shift_bit_pairs;
282
283 // Calculation in fixed point domain with 3 integer bits.
284 using FixedPointRawType = int32_t;
285 constexpr uint32_t fixedpoint_position = 3;
286 constexpr uint32_t fixedpoint_int_position = sizeof(FixedPointRawType) * 8 - 1 - fixedpoint_position;
287 using FixedPoint3 = FixedPointRawType;
288 using FixedPoint0 = FixedPointRawType;
289
290 // fixed point representation of input divided by 2 and 1.5 for Newton-Raphson iteration
291 const FixedPoint3 fixedpoint_input = (input >> 1);
292 const FixedPoint3 fixedpoint_half_input = rounding_divide_by_pow2(fixedpoint_input, 1);
293 const FixedPoint3 fixedpoint_half_three = (0x1 << fixedpoint_int_position) + (0x1 << (fixedpoint_int_position - 1));
294
295 // initial guess (1) in fixed point representation
296 FixedPoint3 x = 0x1 << fixedpoint_int_position;
297
298 // multiplication of two fixed point numbers, defined for readability
299 auto fixed_point_mul = [](FixedPointRawType a, FixedPointRawType b) -> FixedPointRawType
300 {
301 return saturating_rounding_doubling_highmul(a, b);
302 };
303
304 // rescaling of fixed point to have dst_bit integer bits, defined for readability
305 auto fixed_point_rescale = [](FixedPointRawType a, uint32_t src_bit, uint32_t dst_bit) -> FixedPointRawType
306 {
307 const uint32_t exponent = src_bit - dst_bit;
308 return saturating_rounding_multiply_by_pow2(exponent, a);
309 };
310
311 // 5 iterations of Newton-Raphson method for inverse square root - 1.5 * x_n = input/2 * (x_n)^3
312 constexpr int32_t num_iteration = 5;
313 for(int32_t i = 0; i < num_iteration; ++i)
314 {
315 const auto x3 = fixed_point_rescale(fixed_point_mul(fixed_point_mul(x, x), x), 9, fixedpoint_position);
316 x = fixed_point_rescale(fixed_point_mul(fixedpoint_half_three, x) - fixed_point_mul(fixedpoint_half_input, x3), 6, fixedpoint_position);
317 }
318
319 // fixed point representation of sqrt(1/2)
320 const FixedPoint0 fixedpoint_half_sqrt_2 = 1518500250;
321 x = fixed_point_mul(fixedpoint_half_sqrt_2, x);
322 output_inv_sqrt = x;
323 if(output_shift < 0)
324 {
325 output_inv_sqrt <<= -output_shift;
326 output_shift = 0;
327 }
328 // convert right shift to left shift
329 output_shift *= reverse_shift;
330}
Michele Di Giorgiod87a7b22019-09-10 10:42:27 +0100331} // quantization
332} // arm_compute