blob: e5bc88b875f14d79ffe2d5fbedcf4b673735439a [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
22import numpy as np
23
24
25def round_up(a, b):
26 return ((a + b - 1) // b) * b
27
28
29def round_up_divide(a, b):
30 return (a + b - 1) // b
31
32
33def round_up_to_int(v):
34 return int(math.ceil(v))
35
36
37def round_down_to_power_of_two(v):
38 assert v > 0
39 while v & (v - 1):
40 v &= v - 1
41
42 return v
43
44
45def round_up_to_power_of_two(v):
46 return round_down_to_power_of_two(2 * v - 1)
47
48
49def round_down_log2(v):
50 return int(math.floor(np.log2(v)))
51
52
53def round_up_log2(v):
54 return int(math.ceil(np.log2(v)))
55
56
57def round_to_int(v):
58 return np.rint(v).astype(np.int64)
59
60
61# Performs rounding away from zero.
62# n.b. This is identical to C++11 std::round()
63def round_away_zero(f):
64 r = -0.5 if (f < 0) else 0.5
65 return np.trunc(f + r)
66
67
68def quantise_float32(f, scale=1.0, zero_point=0):
69 return zero_point + int(round_away_zero(np.float32(f) / np.float32(scale)))
70
71
72def clamp_tanh(x):
73 if x <= -4:
74 y = -1.0
75 elif x >= 4:
76 y = 1.0
77 else:
78 y = math.tanh(x)
79 return y
80
81
82def clamp_sigmoid(x):
83 if x <= -8:
84 y = 0.0
85 elif x >= 8:
86 y = 1.0
87 else:
88 y = 1 / (1 + math.exp(-x))
89 return y