Bugfix for NumPyBinLoader with SubTensor output. (#345)
[platform/upstream/armcl.git] / src / core / CL / cl_kernels / asymm_helper.h
1 /*
2  * Copyright (c) 2017 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  */
24 #ifndef ARM_COMPUTE_ASYMM_HELPER_H
25 #define ARM_COMPUTE_ASYMM_HELPER_H
26
27 // Algoriths for these functions were taken from
28 // https://github.com/google/gemmlowp/blob/master/fixedpoint/fixedpoint.h
29 // and adapted to operate on integer vectors.
30
31 /** For each element of input vector, the corresponding bits of the result item are set
32  * if the input item is zero.
33  *
34  * @param[in] a Input vector whose zero bits define which corresponding bits in result will be set.
35  *
36  * @returns Output vector with bits set when corresponding bit in @p a is zero.
37  */
38 inline int16 asymm_mask_if_zero(int16 a)
39 {
40     const int16 all_zeros = 0;
41     const int16 all_ones  = ~0;
42     return select(all_zeros, all_ones, a == 0);
43 }
44
45 /** For each element of input vector, the corresponding bits of the result item are set
46  * if the input item is non-zero.
47  *
48  * @param[in] a Input vector whose non-zero bits define which corresponding bits in result will be set.
49  *
50  * @returns Output vector with bits set when corresponding bit in @p a is non zero.
51  */
52 inline int16 asymm_mask_if_non_zero(int16 a)
53 {
54     const int16 all_zeros = 0;
55     const int16 all_ones  = ~0;
56     return select(all_zeros, all_ones, a != 0);
57 }
58
59 /** Each bit of the result is set to the corresponding bit of either then_val or
60  * else_val depending on whether the corresponding bit of if_mask is set.
61  * Equivalent to the VBSL instruction in ARM NEON.
62  *
63  * @param[in] if_mask  Mask defines will bit be taken from @p then_val or @p else_val depending on corresponding bit in mask is set or not.
64  * @param[in] then_val Value whose bit will be used for result when corresponding bit in @p if_mask is set.
65  * @param[in] else_val Value whose bit will be used for result when corresponding bit in @p if_mask is not set.
66  *
67  * @returns Result contaning bits from @p then_val or from @p else_val depending on corresponding bit in @p if_mask is set or not.
68  */
69 inline int16 asymm_select_using_mask(int16 if_mask, int16 then_val, int16 else_val)
70 {
71     return (if_mask & then_val) ^ (~if_mask & else_val);
72 }
73
74 /** Correctly rounded to nearest division by a power of two.
75  * Also known as a rounding arithmetic right shift.
76  *
77  * @param[in] x        Value needed to be divided by power of two.
78  * @param[in] exponent Power of two, must be positive number.
79  *
80  * @return Arithmetic right shift.
81  */
82 inline int16 asymm_rounding_divide_by_pow2(int16 x, int exponent)
83 {
84     int16       mask      = (1 << exponent) - 1;
85     const int16 zero      = 0;
86     const int16 one       = 1;
87     int16       threshold = (mask >> 1) + select(zero, one, x < 0);
88     return (x >> exponent) + select(zero, one, (x & mask) > threshold);
89 }
90
91 /** Calculates the product of a integer value by a power of two, with either a positive exponent
92  * (equivalent to an arithmetic left shift, saturating) or a negative exponent
93  * (equivalent to an arithmetic right shift, rounding to nearest).
94  *
95  * @param[in] x        Value needed to be multiplied or divided by power of two depending on sign of @p exponent.
96  * @param[in] exponent Power of two, can be positive or negative number.
97  *
98  * @return Arithmetic left or right shift.
99  */
100 inline int16 asymm_saturating_rounding_mult_by_pow2(int16 x, int exponent)
101 {
102     if(exponent < 0)
103     {
104         return asymm_rounding_divide_by_pow2(x, -exponent);
105     }
106
107     const int16 min           = INT_MIN;
108     const int16 max           = INT_MAX;
109     int         threshold     = ((1 << (31 - exponent)) - 1);
110     int16       positive_mask = asymm_mask_if_non_zero(x > threshold);
111     int16       negative_mask = asymm_mask_if_non_zero(x < -threshold);
112     int16       result        = x << exponent;
113     result                    = asymm_select_using_mask(positive_mask, max, result);
114     result                    = asymm_select_using_mask(negative_mask, min, result);
115     return result;
116 }
117
118 /** Calculates (a+b)/2, rounded to the nearest integer.
119  * Equivalent to VRHADD in the ARM NEON instruction set.
120  *
121  * @param[in] a First term of half-sum.
122  * @param[in] b Second term of half-sum.
123  *
124  * @return (a+b)/2, rounded to the nearest integer.
125  */
126 inline int16 asymm_rounding_half_sum(int16 a, int16 b)
127 {
128     long16       a64       = convert_long16(a);
129     long16       b64       = convert_long16(b);
130     long16       sum       = a64 + b64;
131     const long16 one       = 1;
132     const long16 minus_one = -1;
133     long16       sign      = select(minus_one, one, sum >= 0);
134     return convert_int16((sum + sign) / 2);
135 }
136
137 /** Product of two numbers, interpreting them as fixed-point values in the interval [-1, 1),
138  * rounding to the nearest value, and saturating -1 * -1 to the maximum value.
139  * This is equivalent to the VQRDMULH instruction in ARM NEON.
140  *
141  * @param[in] a First term of product.
142  * @param[in] b Second term of product.
143  *
144  * @return Product of two numbers.
145  */
146 inline int16 asymm_saturating_rounding_doubling_high_mul(int16 a, int16 b)
147 {
148     int16  overflow     = (a == b) && (a == INT_MIN);
149     long16 a_64         = convert_long16(a);
150     long16 b_64         = convert_long16(b);
151     long16 ab_64        = a_64 * b_64;
152     long16 mask1        = 1 << 30;
153     long16 mask2        = 1 - (1 << 30);
154     long16 nudge        = select(mask2, mask1, ab_64 >= 0);
155     long16 mask         = 1ll << 31;
156     int16  ab_x2_high32 = convert_int16((ab_64 + nudge) / mask);
157     return select(ab_x2_high32, INT_MAX, overflow);
158 }
159
160 /** Fixed-point multiplication.
161  *
162  * @param[in] a Argument 1 in fixed-point format Q(a).
163  * @param[in] b Argument 2 in fixed-point format Q(b).
164  *
165  * @return Result in fixed-point format Q(a+b).
166  */
167 inline int16 asymm_mult(int16 a, int16 b)
168 {
169     return asymm_saturating_rounding_doubling_high_mul(a, b);
170 }
171
172 /** Calculates \f$ exp(x) \f$ for x in [-1/4, 0).
173  *
174  * @param[in] a Argument in fixed-point format Q0.
175  *
176  * @return Result in fixed-point format Q0.
177  */
178 inline int16 asymm_exp_on_interval_between_negative_one_quarter_and_0_excl(int16 a)
179 {
180     const int16 constant_term                            = 1895147668;
181     const int16 constant_1_over_3                        = 715827883;
182     const int   k_fractional_bits                        = 31;
183     int16       x                                        = a + (1 << (k_fractional_bits - 3));
184     int16       x2                                       = asymm_mult(x, x);
185     int16       x3                                       = asymm_mult(x2, x);
186     int16       x4                                       = asymm_mult(x2, x2);
187     int16       x4_over_4                                = asymm_rounding_divide_by_pow2(x4, 2);
188     int16       x4_over_24_plus_x3_over_6_plus_x2        = asymm_mult((x4_over_4 + x3), constant_1_over_3) + x2;
189     int16       x4_over_24_plus_x3_over_6_plus_x2_over_2 = asymm_rounding_divide_by_pow2(x4_over_24_plus_x3_over_6_plus_x2, 1);
190     return constant_term + asymm_mult(constant_term, x + x4_over_24_plus_x3_over_6_plus_x2_over_2);
191 }
192
193 /** Calculates \f$ exp(x) \f$ for x < 0.
194  *
195  * @param[in] a              Argument in fixed-point format Q(k_integer_bits).
196  * @param[in] k_integer_bits Number of integer bit in argument.
197  *
198  * @return Result in fixed-point format Q0.
199  */
200 inline int16 asymm_exp_on_negative_values(int16 a, int k_integer_bits)
201 {
202     const int k_fractional_bits                      = 31 - k_integer_bits;
203     int16     k_one_quarter                          = 1 << (k_fractional_bits - 2);
204     int16     mask                                   = k_one_quarter - 1;
205     int16     a_mod_quarter_minus_one_quarter        = (a & mask) - k_one_quarter;
206     int16     a_mod_quarter_minus_one_quarter_scaled = a_mod_quarter_minus_one_quarter << k_integer_bits;
207     int16     result                                 = asymm_exp_on_interval_between_negative_one_quarter_and_0_excl(a_mod_quarter_minus_one_quarter_scaled);
208     int16     remainder                              = a_mod_quarter_minus_one_quarter - a;
209
210 #define EXP_BARREL_SHIFTER(Exponent, FixedPointMultiplier)                                       \
211     if(k_integer_bits > Exponent)                                                                \
212     {                                                                                            \
213         const int k_shift_amount = k_integer_bits > Exponent ? k_fractional_bits + Exponent : 0; \
214         result                   = asymm_select_using_mask(                                      \
215                                                                                                  asymm_mask_if_non_zero(remainder & (1 << k_shift_amount)),                           \
216                                                                                                  asymm_mult(result, FixedPointMultiplier), result);                                   \
217     }
218     EXP_BARREL_SHIFTER(-2, 1672461947);
219     EXP_BARREL_SHIFTER(-1, 1302514674);
220     EXP_BARREL_SHIFTER(+0, 790015084);
221     EXP_BARREL_SHIFTER(+1, 290630308);
222     EXP_BARREL_SHIFTER(+2, 39332535);
223     EXP_BARREL_SHIFTER(+3, 720401);
224     EXP_BARREL_SHIFTER(+4, 242);
225 #undef EXP_BARREL_SHIFTER
226
227     if(k_integer_bits > 5)
228     {
229         const int16 clamp = -(1 << (k_fractional_bits + 5));
230         result            = asymm_select_using_mask(asymm_mask_if_non_zero(a < clamp), 0, result);
231     }
232
233     const int16 Q0_one = INT_MAX;
234     return asymm_select_using_mask(asymm_mask_if_zero(a), Q0_one, result);
235 }
236
237 /** Calculates \f$ 1 / (1 + x) \f$ for x in (0, 1).
238  *
239  * @param[in] a Argument in fixed-point format Q0.
240  *
241  * @return Result in fixed-point format Q0.
242  */
243 inline int16 asymm_one_over_one_plus_x_for_x_in_0_1(int16 a)
244 {
245     const int16 Q0_one            = INT_MAX;
246     const int16 Q2_one            = 1 << (31 - 2);
247     int16       half_denominator  = asymm_rounding_half_sum(a, Q0_one);
248     const int16 Q2_48_over_17     = 1515870810;
249     const int16 Q2_neg_32_over_17 = -1010580540;
250     int16       x                 = Q2_48_over_17 + asymm_mult(half_denominator, Q2_neg_32_over_17);
251     for(int i = 0; i < 3; i++)
252     {
253         int16 half_denominator_times_x           = asymm_mult(half_denominator, x);
254         int16 one_minus_half_denominator_times_x = Q2_one - half_denominator_times_x;
255         int16 tmp                                = asymm_mult(x, one_minus_half_denominator_times_x);
256         x                                        = x + asymm_saturating_rounding_mult_by_pow2(tmp, 2);
257     }
258     return asymm_saturating_rounding_mult_by_pow2(x, 1);
259 }
260
261 /** Considering the integer value as fixed-point, change the number of integer bits and update value accordingly.
262  *
263  * @param[in] value            Value to be rescaled.
264  * @param[in] src_integer_bits Old number of integer bits.
265  * @param[in] dst_integer_bits New number of integer bits.
266  *
267  * @return Rescaled value.
268  */
269 inline int16 asymm_rescale(int16 value, int src_integer_bits, int dst_integer_bits)
270 {
271     int exponent = src_integer_bits - dst_integer_bits;
272     return asymm_saturating_rounding_mult_by_pow2(value, exponent);
273 }
274
275 #endif // ARM_COMPUTE_ASYMM_HELPER_H