blob: 70209fba0f4b7f14f2feee7318f77d7e3396f0e6 [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.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Numerical utilities for various types of rounding etc.
Tim Hall79d07d22020-04-27 18:20:16 +010018import math
Diego Russoea6111a2020-04-14 18:41:58 +010019
Tim Hall79d07d22020-04-27 18:20:16 +010020import numpy as np
21
22
23def round_up(a, b):
24 return ((a + b - 1) // b) * b
25
26
27def round_up_divide(a, b):
28 return (a + b - 1) // b
29
30
31def round_up_to_int(v):
32 return int(math.ceil(v))
33
34
35def round_down_to_power_of_two(v):
36 assert v > 0
37 while v & (v - 1):
38 v &= v - 1
39
40 return v
41
42
43def round_up_to_power_of_two(v):
44 return round_down_to_power_of_two(2 * v - 1)
45
46
47def round_down_log2(v):
48 return int(math.floor(np.log2(v)))
49
50
51def round_up_log2(v):
52 return int(math.ceil(np.log2(v)))
53
54
55def round_to_int(v):
56 return np.rint(v).astype(np.int64)
57
58
59# Performs rounding away from zero.
60# n.b. This is identical to C++11 std::round()
61def round_away_zero(f):
62 r = -0.5 if (f < 0) else 0.5
63 return np.trunc(f + r)
64
65
66def quantise_float32(f, scale=1.0, zero_point=0):
67 return zero_point + int(round_away_zero(np.float32(f) / np.float32(scale)))
68
69
70def clamp_tanh(x):
71 if x <= -4:
72 y = -1.0
73 elif x >= 4:
74 y = 1.0
75 else:
76 y = math.tanh(x)
77 return y
78
79
80def clamp_sigmoid(x):
81 if x <= -8:
82 y = 0.0
83 elif x >= 8:
84 y = 1.0
85 else:
86 y = 1 / (1 + math.exp(-x))
87 return y
Charles Xu3e9c4342020-04-22 08:31:43 +020088
Tim Hallc30f4952020-06-15 20:47:35 +010089
Charles Xu3e9c4342020-04-22 08:31:43 +020090def full_shape(dim, shape, fill):
Tim Hallc30f4952020-06-15 20:47:35 +010091 return ([fill] * (dim - len(shape))) + shape