-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocalLayers.py
220 lines (156 loc) · 7.07 KB
/
localLayers.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
from __future__ import print_function
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# supress annoying TF messages at the beginning
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras import backend as KB
import numpy as np
from localFunctions import heconstant, activate, magnitude
import QFunctions
def KernelInitializer(initializer, p1):
if initializer == 'normal':
ki = tf.compat.v1.keras.initializers.RandomNormal(mean=0.0, stddev=0.01)
if initializer == 'glorot':
ki = tf.compat.v1.keras.initializers.glorot_normal()
if initializer == 'he':
ki = tf.compat.v1.keras.initializers.he_normal()
if initializer == "heconstant":
ki = heconstant(p1)
return ki
def quantize_activations(nbits):
if nbits == 1:
return QFunctions.qrelu1
if nbits == 2:
return QFunctions.qrelu2
if nbits == 4:
return QFunctions.qrelu4
if nbits == 8:
return QFunctions.qrelu8
if nbits == 16:
return QFunctions.qrelu16
if nbits == 32:
return QFunctions.qrelu32
return tf.identity
def quantize_weights(nbits):
if nbits == 1:
return QFunctions.q1
if nbits == 2:
return QFunctions.q2
if nbits == 4:
return QFunctions.q4
if nbits == 8:
return QFunctions.q8
if nbits == 16:
return QFunctions.q16
if nbits == 32:
return QFunctions.q32
return tf.identity
def get_kernel_biases(name, kernel, bias):
k = KB.eval(kernel)
if bias is not None:
b = KB.eval(bias)
print("Layer {}".format(name))
print(" total number of weights: {:7d} | unique: {:7d}".format(k.size, np.unique(k).size))
print(" krnl: min | max | mean | std: {:.13f} | {:.13f} | {:.13f} | {:.13f}".format(np.min(k), np.max(k), np.mean(k), np.std(k)))
if bias is not None:
print(" total number of biases: {:7d} | unique: {:7d}".format(b.size, np.unique(b).size))
print(" bias: min | max | mean | std: {:.13f} | {:.13f} | {:.13f} | {:.13f}".format(np.min(b), np.max(b), np.mean(b), np.std(b)))
return k
class QuantizedConv2D(Layer):
def __init__(self, filters, ksize, activation, initializer, stride, config, **kwargs):
self.filters = filters
self.ksize = ksize
self.stride = stride
self.initializer = initializer
self.addbias = config["addbias"]
self.wbits = config["wbits"]
self.abits = config["abits"]
self.activation = activation
# quantization functions
self.wqnt = quantize_weights(self.wbits)
self.aqnt = quantize_activations(self.abits)
if stride is not None:
self.stride = stride
super(QuantizedConv2D, self).__init__(**kwargs)
def build(self, input_shape):
bias_shape = (self.filters,)
krnl_shape = list((self.ksize, self.ksize)) + [input_shape.as_list()[-1], self.filters]
kernel_initializer = KernelInitializer(self.initializer, 0.5)
if self.addbias:
a = np.sqrt(2 / np.prod(bias_shape[:-1]))
ashape = (1,)
self.x_bias = self.add_weight(name='x_bias', shape=bias_shape, initializer=kernel_initializer, trainable=True)
self.s_bias = self.add_weight(name='s_bias', shape=ashape, initializer=magnitude(a), trainable=True)
self.bias = tf.abs(self.s_bias) * self.wqnt(self.x_bias)
a = np.sqrt(2 / np.prod(krnl_shape[:-1]))
ashape = (1,)
self.x_weights = self.add_weight(name='x_weights', shape=krnl_shape, initializer=kernel_initializer, trainable=True)
self.a_weights = self.add_weight(name='s_weights', shape=ashape, initializer=magnitude(a), trainable=True)
self.kernel = tf.abs(self.a_weights) * self.wqnt(self.x_weights)
super(QuantizedConv2D, self).build(input_shape)
def call(self, x):
y = KB.conv2d(x, self.kernel, strides=(self.stride, self.stride), padding='same')
if self.addbias:
y += self.bias
if self.activation is not None:
if self.abits != 0:
y = tf.clip_by_value(y, 0, (2 ** self.abits) - 1)
return self.aqnt(y)
else:
return y
def compute_output_shape(self, input_shape):
return (input_shape.as_list()[1], self.output_dim)
def get_weights(self):
return super(QuantizedConv2D, self).get_weights()
def set_weights(self, weights):
super(QuantizedConv2D, self).set_weights(weights)
def get_kernel(self):
return get_kernel_biases(self.name, self.kernel, self.bias)
class QuantizedDense(Layer):
def __init__(self, output_dim, activation, initializer, config, **kwargs):
self.output_dim = output_dim
self.initializer = initializer
self.addbias = config["addbias"]
self.wbits = config["wbits"]
self.abits = config["abits"]
self.activation = activation
# quantization functions
self.wqnt = quantize_weights(self.wbits)
self.aqnt = quantize_activations(self.abits)
super(QuantizedDense, self).__init__(**kwargs)
def build(self, input_shape):
bias_shape = (self.output_dim,)
krnl_shape = (input_shape.as_list()[1], self.output_dim)
kernel_initializer = KernelInitializer(self.initializer, 0.5)
if self.addbias:
a = np.sqrt(2 / np.prod(bias_shape[:-1]))
ashape = (1,)
self.x_bias = self.add_weight(name='x_bias', shape=bias_shape, initializer=kernel_initializer, trainable=True)
self.a_bias = self.add_weight(name='a_bias', shape=ashape, initializer=magnitude(a), trainable=True)
self.bias = tf.abs(self.a_bias) * self.wqnt(self.x_bias)
a = np.sqrt(2 / np.prod(krnl_shape[:-1]))
ashape = (1,)
self.x_weights = self.add_weight(name='x_weights', shape=krnl_shape, initializer=kernel_initializer, trainable=True)
self.a_weights = self.add_weight(name='a_weights', shape=ashape, initializer=magnitude(a), trainable=True)
self.kernel = tf.abs(self.a_weights) * self.wqnt(self.x_weights)
super(QuantizedDense, self).build(input_shape)
def call(self, x):
y = KB.dot(x, self.kernel)
if self.addbias:
y += self.bias
if self.activation != "softmax":
y = tf.clip_by_value(y, 0, (2 ** self.abits) - 1)
act = self.aqnt(y)
else:
act = activate(y, self.activation)
return act
def compute_output_shape(self, input_shape):
return input_shape.as_list()[1], self.output_dim
def get_weights(self):
return super(QuantizedDense, self).get_weights()
def set_weights(self, weights):
super(QuantizedDense, self).set_weights(weights)
def get_kernel(self):
return get_kernel_biases(self.name, self.kernel, self.bias)