blob: 4e61b4c5f4311380e71ee0e2b85bc8aadee47027 [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17
18# Description:
19# Numerical utilities for various types of rounding etc.
20
21import math
Diego Russoea6111a2020-04-14 18:41:58 +010022
Tim Hall79d07d22020-04-27 18:20:16 +010023import numpy as np
24
25
26def round_up(a, b):
27 return ((a + b - 1) // b) * b
28
29
30def round_up_divide(a, b):
31 return (a + b - 1) // b
32
33
34def round_up_to_int(v):
35 return int(math.ceil(v))
36
37
38def round_down_to_power_of_two(v):
39 assert v > 0
40 while v & (v - 1):
41 v &= v - 1
42
43 return v
44
45
46def round_up_to_power_of_two(v):
47 return round_down_to_power_of_two(2 * v - 1)
48
49
50def round_down_log2(v):
51 return int(math.floor(np.log2(v)))
52
53
54def round_up_log2(v):
55 return int(math.ceil(np.log2(v)))
56
57
58def round_to_int(v):
59 return np.rint(v).astype(np.int64)
60
61
62# Performs rounding away from zero.
63# n.b. This is identical to C++11 std::round()
64def round_away_zero(f):
65 r = -0.5 if (f < 0) else 0.5
66 return np.trunc(f + r)
67
68
69def quantise_float32(f, scale=1.0, zero_point=0):
70 return zero_point + int(round_away_zero(np.float32(f) / np.float32(scale)))
71
72
73def clamp_tanh(x):
74 if x <= -4:
75 y = -1.0
76 elif x >= 4:
77 y = 1.0
78 else:
79 y = math.tanh(x)
80 return y
81
82
83def clamp_sigmoid(x):
84 if x <= -8:
85 y = 0.0
86 elif x >= 8:
87 y = 1.0
88 else:
89 y = 1 / (1 + math.exp(-x))
90 return y