forked from yashkant/quantized-nets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quantized_net.py
165 lines (122 loc) · 5.34 KB
/
quantized_net.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
from __future__ import print_function
import numpy as np
import sys
from functools import partial
seed = 1337
np.random.seed(seed)
import keras.backend as K
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, BatchNormalization, MaxPooling2D
from keras.layers import Flatten
from keras.optimizers import SGD, Adam, RMSprop
from keras.callbacks import LearningRateScheduler, Callback
from keras.utils import np_utils
from keras.activations import relu
from keras.callbacks import ModelCheckpoint
from quantize.quantized_layers import QuantizedConv2D, QuantizedDense
from quantize.quantized_ops import quantized_relu as quantized_relu_op
from quantize.quantized_ops import quantized_tanh as quantized_tanh_op
import mnist_data
import math
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-nb", "--num_bits", dest="num_bits",
help="Number of bits to quantize", default = 4)
args = parser.parse_args()
def mnist_process(x):
for j in range(len(x)):
x[j] = x[j]*2-1
if(len(x[j][0]) == 784):
x[j] = np.reshape(x[j], [-1, 28, 28, 1])
return x
class TestCallback(Callback):
def __init__(self, test_data):
self.test_data = test_data
def on_epoch_end(self, epoch, logs={}):
x, y = self.test_data
loss, acc = self.model.evaluate(x, y, verbose=0)
print('\nTesting loss: {}, acc: {}\n'.format(loss, acc))
H = 1.
kernel_lr_multiplier = 'Glorot'
# nn
batch_size = 128
epochs = 1000
channels = 1
img_rows = 28
img_cols = 28
filters = 32
kernel_size = (3, 3)
pool_size = (2, 2)
hidden_units = 128
classes = 10
use_bias = False
n_bits = int(args.num_bits)
# learning rate schedule
lr_start = 1e-3
lr_end = 1e-4
lr_decay = (lr_end / lr_start)**(1. / epochs)
# BN
epsilon = 1e-6
momentum = 0.9
def add_quant_conv_layer(model, conv_num_filters, conv_kernel_size, conv_strides, mpool_kernel_size, mpool_strides, n_bits):
model.add(QuantizedConv2D(conv_num_filters, kernel_size=(conv_kernel_size,conv_kernel_size), input_shape=( img_rows, img_cols, channels),
data_format='channels_last', strides=(conv_strides,conv_strides),
H=H, kernel_lr_multiplier=kernel_lr_multiplier,
padding='valid', use_bias=use_bias, nb = n_bits))
model.add(MaxPooling2D(pool_size=(mpool_kernel_size, mpool_kernel_size),strides = (mpool_strides,mpool_strides) ,padding='valid' , data_format='channels_last'))
model.add(BatchNormalization(epsilon=epsilon, momentum=momentum, axis=1))
model.add(Activation(partial(quantized_relu_op, nb = n_bits)))
return model
assert n_bits >= 2 , "Numer of bits should be at least 2 and atmost 32"
assert n_bits <= 32 , "Numer of bits should be at least 2 and atmost 32"
print("Quantize to bits: ", n_bits)
print(type(n_bits))
# -------------Model Architecture-----
model = Sequential()
conv_kernel_size = 5
conv_num_filters = 32
conv_strides = 2
mpool_kernel_size = 2
mpool_strides = 2
add_quant_conv_layer(model = model, conv_num_filters = conv_num_filters, conv_kernel_size = conv_kernel_size, conv_strides = conv_strides, mpool_kernel_size = mpool_kernel_size, mpool_strides = mpool_strides, n_bits=n_bits)
conv_kernel_size = 3
conv_num_filters = 64
conv_strides = 1
mpool_kernel_size = 2
mpool_strides = 2
add_quant_conv_layer(model = model, conv_num_filters = conv_num_filters, conv_kernel_size = conv_kernel_size, conv_strides = conv_strides, mpool_kernel_size = mpool_kernel_size, mpool_strides = mpool_strides, n_bits=n_bits)
model.add(Flatten())
# dense1
model.add(QuantizedDense(512, H=H, kernel_lr_multiplier=kernel_lr_multiplier, use_bias=use_bias, nb = n_bits))
model.add(BatchNormalization(epsilon=epsilon, momentum=momentum ))
model.add(Activation(partial(quantized_relu_op, nb = n_bits)))
# dense2
model.add(QuantizedDense(classes, H=H, kernel_lr_multiplier=kernel_lr_multiplier, use_bias=use_bias, nb = n_bits))
model.add(BatchNormalization(epsilon=epsilon, momentum=momentum, name='bn6'))
opt = Adam(lr=lr_start)
model.compile(loss='squared_hinge', optimizer=opt, metrics=['acc'])
model.summary()
# ---------------------------------
# ------------- MNIST Unpack and Augment Code------------
train_total_data, train_size, test_data, test_labels = mnist_data.prepare_MNIST_data(False)
train_data = train_total_data[:, :-10]
train_labels = train_total_data[:, -10:]
x = [train_data, train_labels, test_data, test_labels]
x_train, y_train, x_test, y_test = mnist_process(x)
print("X train: ", x_train.shape)
print("Y train: ", y_train.shape)
# --------------------------------------------------------
# -------- Train Loop----------------------
lr_scheduler = LearningRateScheduler(lambda e: lr_start * lr_decay ** e)
history = model.fit(x_train, y_train,
batch_size=batch_size, epochs=epochs,
verbose=1, validation_data=(x_test, y_test),
callbacks=[lr_scheduler, ModelCheckpoint('temp_network.h5',
monitor='val_acc', verbose=1,
save_best_only=True,
save_weights_only=True)])
score = model.evaluate(x_test, y_test, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])
# ---------------------------------------