-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQFunctions.py
145 lines (90 loc) · 2.11 KB
/
QFunctions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import tensorflow as tf
def ggrad(dy):
return dy
def qrelu(x, bits):
n = (2 ** bits) - 1
denom = tf.math.reduce_max(x)
y0_1 = tf.keras.activations.relu(tf.math.ceil(n * x / denom) / n)
y = denom * y0_1
return y
@tf.custom_gradient
def qrelu1(x):
bits = 1
y = qrelu(x, bits)
def grad(dy):
return dy
return y, grad
@tf.custom_gradient
def qrelu2(x):
bits = 2
y = qrelu(x, bits)
def grad(dy):
return dy
return y, grad
@tf.custom_gradient
def qrelu4(x):
bits = 4
y = qrelu(x, bits)
def grad(dy):
return dy
return y, grad
@tf.custom_gradient
def qrelu8(x):
bits = 8
y = qrelu(x, bits)
def grad(dy):
return dy
return y, grad
@tf.custom_gradient
def qrelu16(x):
bits = 16
y = qrelu(x, bits)
def grad(dy):
return dy
return y, grad
@tf.custom_gradient
def qrelu32(x):
bits = 32
y = qrelu(x, bits)
def grad(dy):
return dy
return y, grad
def ladder(x, bits):
n = 2 ** (bits - 1)
denom = tf.math.reduce_max(tf.abs(x))
y = tf.math.round(n * x / denom) / n
return y
def broken_ladder(x, bits):
n = 2 ** (bits - 1)
denom = tf.reduce_max(tf.abs(x))
y1 = tf.keras.activations.relu(tf.ceil(n * x / denom) / n)
y2 = tf.keras.activations.relu(-tf.floor(n * x / denom) / n) * tf.sign(x)
y = y1 + y2
return y
def quantization(x, bits):
return broken_ladder(x, bits)
# return ladder(x, bits)
@tf.custom_gradient
def q1(x):
y = quantization(x, 1)
return y, ggrad
@tf.custom_gradient
def q2(x):
y = quantization(x, 2)
return y, ggrad
@tf.custom_gradient
def q4(x):
y = quantization(x, 4)
return y, ggrad
@tf.custom_gradient
def q8(x):
y = quantization(x, 8)
return y, ggrad
@tf.custom_gradient
def q16(x):
y = quantization(x, 16)
return y, ggrad
@tf.custom_gradient
def q32(x):
y = quantization(x, 32)
return y, ggrad