CNNCreator_Alexnet.py 13.4 KB
Newer Older
1
from caffe2.python import workspace, core, model_helper, brew, optimizer
2
3
4
5
from caffe2.python.predictor import mobile_exporter
from caffe2.proto import caffe2_pb2
import numpy as np

6
import logging
7
import os
8
import sys
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#import shutil
#import cv2

class CNNCreator_Alexnet:

    module = None
    _data_dir_ = "data/Alexnet/"
    _model_dir_ = "model/Alexnet/"
    _model_prefix_ = "Alexnet"
    _input_names_ = ['data']
    _input_shapes_ = [(3,224,224)]
    _output_names_ = ['predictions_label']


23
24
25
    CURRENT_DIR = os.path.join('./')
    DATA_DIR    = os.path.join(CURRENT_DIR, 'data', 'Alexnet')
    MODEL_DIR   = os.path.join(CURRENT_DIR, 'model', 'Alexnet')
26

27
28
    INIT_NET    = os.path.join(MODEL_DIR, 'init_net.pb')
    PREDICT_NET = os.path.join(MODEL_DIR, 'predict_net.pb')
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

    def add_input(self, model, batch_size, db, db_type, device_opts):
        with core.DeviceScope(device_opts):
            # load the data
            data_uint8, label = brew.db_input(
                model,
                blobs_out=["data_uint8", "label"],
                batch_size=batch_size,
                db=db,
                db_type=db_type,
            )
            # cast the data to float
            data = model.Cast(data_uint8, "data", to=core.DataType.FLOAT)

            # scale data from [0,255] down to [0,1]
            data = model.Scale(data, data, scale=float(1./256))

            # don't need the gradient for the backward pass
            data = model.StopGradient(data, data)
            return data, label

    def create_model(self, model, data, device_opts):
    	with core.DeviceScope(device_opts):

    		data = data
    		# data, output shape: {[3,224,224]}
55
      		conv1_ = brew.conv(model, data, 'conv1_', dim_in=3, dim_out=96, kernel=11, stride=4)
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
    		# conv1_, output shape: {[96,55,55]}
    		lrn1_ = mx.symbol.LRN(data=conv1_,
    		    alpha=0.0001,
    		    beta=0.75,
    		    knorm=2,
    		    nsize=5,
    		    name="lrn1_")
    		pool1_ = brew.max_pool(model, lrn1_, 'pool1_', kernel=3, stride=2)
    		# pool1_, output shape: {[96,27,27]}
    		relu1_ = brew.relu(model, pool1_, pool1_)
    		split1_ = mx.symbol.split(data=relu1_,
    		    num_outputs=2,
    		    axis=1,
    		    name="split1_")
    		# split1_, output shape: {[48,27,27][48,27,27]}
    		get2_1_ = split1_[0]
      		conv2_1_ = brew.conv(model, get2_1_, 'conv2_1_', dim_in=48, dim_out=128, kernel=5, stride=1)
    		# conv2_1_, output shape: {[128,27,27]}
    		lrn2_1_ = mx.symbol.LRN(data=conv2_1_,
    		    alpha=0.0001,
    		    beta=0.75,
    		    knorm=2,
    		    nsize=5,
    		    name="lrn2_1_")
    		pool2_1_ = brew.max_pool(model, lrn2_1_, 'pool2_1_', kernel=3, stride=2)
    		# pool2_1_, output shape: {[128,13,13]}
    		relu2_1_ = brew.relu(model, pool2_1_, pool2_1_)
    		get2_2_ = split1_[1]
      		conv2_2_ = brew.conv(model, get2_2_, 'conv2_2_', dim_in=48, dim_out=128, kernel=5, stride=1)
    		# conv2_2_, output shape: {[128,27,27]}
    		lrn2_2_ = mx.symbol.LRN(data=conv2_2_,
    		    alpha=0.0001,
    		    beta=0.75,
    		    knorm=2,
    		    nsize=5,
    		    name="lrn2_2_")
    		pool2_2_ = brew.max_pool(model, lrn2_2_, 'pool2_2_', kernel=3, stride=2)
    		# pool2_2_, output shape: {[128,13,13]}
    		relu2_2_ = brew.relu(model, pool2_2_, pool2_2_)
    		concatenate3_ = mx.symbol.concat(relu2_1_, relu2_2_,
    		    dim=1,
    		    name="concatenate3_")
    		# concatenate3_, output shape: {[256,13,13]}
      		conv3_ = brew.conv(model, concatenate3_, 'conv3_', dim_in=256, dim_out=384, kernel=3, stride=1)
    		# conv3_, output shape: {[384,13,13]}
    		relu3_ = brew.relu(model, conv3_, conv3_)
    		split3_ = mx.symbol.split(data=relu3_,
    		    num_outputs=2,
    		    axis=1,
    		    name="split3_")
    		# split3_, output shape: {[192,13,13][192,13,13]}
    		get4_1_ = split3_[0]
      		conv4_1_ = brew.conv(model, get4_1_, 'conv4_1_', dim_in=192, dim_out=192, kernel=3, stride=1)
    		# conv4_1_, output shape: {[192,13,13]}
    		relu4_1_ = brew.relu(model, conv4_1_, conv4_1_)
      		conv5_1_ = brew.conv(model, relu4_1_, 'conv5_1_', dim_in=192, dim_out=128, kernel=3, stride=1)
    		# conv5_1_, output shape: {[128,13,13]}
    		pool5_1_ = brew.max_pool(model, conv5_1_, 'pool5_1_', kernel=3, stride=2)
    		# pool5_1_, output shape: {[128,6,6]}
    		relu5_1_ = brew.relu(model, pool5_1_, pool5_1_)
    		get4_2_ = split3_[1]
      		conv4_2_ = brew.conv(model, get4_2_, 'conv4_2_', dim_in=192, dim_out=192, kernel=3, stride=1)
    		# conv4_2_, output shape: {[192,13,13]}
    		relu4_2_ = brew.relu(model, conv4_2_, conv4_2_)
      		conv5_2_ = brew.conv(model, relu4_2_, 'conv5_2_', dim_in=192, dim_out=128, kernel=3, stride=1)
    		# conv5_2_, output shape: {[128,13,13]}
    		pool5_2_ = brew.max_pool(model, conv5_2_, 'pool5_2_', kernel=3, stride=2)
    		# pool5_2_, output shape: {[128,6,6]}
    		relu5_2_ = brew.relu(model, pool5_2_, pool5_2_)
    		concatenate6_ = mx.symbol.concat(relu5_1_, relu5_2_,
    		    dim=1,
    		    name="concatenate6_")
    		# concatenate6_, output shape: {[256,6,6]}
    		fc6_ = brew.fc(model, concatenate6_, 'fc6_', dim_in=256 * 6 * 6, dim_out=4096)
    		# fc6_, output shape: {[4096,1,1]}
    		relu6_ = brew.relu(model, fc6_, fc6_)
    		dropout6_ = mx.symbol.Dropout(data=relu6_,
    		    p=0.5,
    		    name="dropout6_")
    		fc7_ = brew.fc(model, dropout6_, 'fc7_', dim_in=4096, dim_out=4096)
    		# fc7_, output shape: {[4096,1,1]}
    		relu7_ = brew.relu(model, fc7_, fc7_)
    		dropout7_ = mx.symbol.Dropout(data=relu7_,
    		    p=0.5,
    		    name="dropout7_")
    		fc8_ = brew.fc(model, dropout7_, 'fc8_', dim_in=4096, dim_out=10)
    		# fc8_, output shape: {[10,1,1]}
    		predictions = brew.softmax(model, fc8_, 'predictions')

    		return predictions

    # this adds the loss and optimizer
    def add_training_operators(self, model, output, label, device_opts, opt_type, base_learning_rate, policy, stepsize, epsilon, beta1, beta2, gamma, momentum) :
    	with core.DeviceScope(device_opts):
    		xent = model.LabelCrossEntropy([output, label], 'xent')
    		loss = model.AveragedLoss(xent, "loss")

    		model.AddGradientOperators([loss])

    		if opt_type == 'adam':
    		    if policy == 'step':
    		        opt = optimizer.build_adam(model, base_learning_rate=base_learning_rate, policy=policy, stepsize=stepsize, beta1=beta1, beta2=beta2, epsilon=epsilon)
    		    elif policy == 'fixed' or policy == 'inv':
    		        opt = optimizer.build_adam(model, base_learning_rate=base_learning_rate, policy=policy, beta1=beta1, beta2=beta2, epsilon=epsilon)
    		    print("adam optimizer selected")
    		elif opt_type == 'sgd':
    		    if policy == 'step':
    		        opt = optimizer.build_sgd(model, base_learning_rate=base_learning_rate, policy=policy, stepsize=stepsize, gamma=gamma, momentum=momentum)
    		    elif policy == 'fixed' or policy == 'inv':
    		        opt = optimizer.build_sgd(model, base_learning_rate=base_learning_rate, policy=policy, gamma=gamma, momentum=momentum)
    		    print("sgd optimizer selected")
    		elif opt_type == 'rmsprop':
    		    if policy == 'step':
    		        opt = optimizer.build_rms_prop(model, base_learning_rate=base_learning_rate, policy=policy, stepsize=stepsize, decay=gamma, momentum=momentum, epsilon=epsilon)
    		    elif policy == 'fixed' or policy == 'inv':
    		        opt = optimizer.build_rms_prop(model, base_learning_rate=base_learning_rate, policy=policy, decay=gamma, momentum=momentum, epsilon=epsilon)
    		    print("rmsprop optimizer selected")
    		elif opt_type == 'adagrad':
    		    if policy == 'step':
    		        opt = optimizer.build_adagrad(model, base_learning_rate=base_learning_rate, policy=policy, stepsize=stepsize, decay=gamma, epsilon=epsilon)
    		    elif policy == 'fixed' or policy == 'inv':
    		        opt = optimizer.build_adagrad(model, base_learning_rate=base_learning_rate, policy=policy, decay=gamma, epsilon=epsilon)
    		    print("adagrad optimizer selected")

    def add_accuracy(self, model, output, label, device_opts, eval_metric):
        with core.DeviceScope(device_opts):
            if eval_metric == 'accuracy':
                accuracy = brew.accuracy(model, [output, label], "accuracy")
            elif eval_metric == 'top_k_accuracy':
                accuracy = brew.accuracy(model, [output, label], "accuracy", top_k=3)
            return accuracy

188
189
    def train(self, num_epoch=1000, batch_size=64, context='gpu', eval_metric='accuracy', opt_type='adam', base_learning_rate=0.001, weight_decay=0.001, policy='fixed', stepsize=1, epsilon=1E-8, beta1=0.9, beta2=0.999, gamma=0.999, momentum=0.9) :
        if context == 'cpu':
190
191
            device_opts = core.DeviceOption(caffe2_pb2.CPU, 0)
            print("CPU mode selected")
192
        elif context == 'gpu':
193
194
195
            device_opts = core.DeviceOption(caffe2_pb2.CUDA, 0)
            print("GPU mode selected")

196
    	workspace.ResetWorkspace(self.MODEL_DIR)
197
198
199
200

    	arg_scope = {"order": "NCHW"}
    	# == Training model ==
    	train_model= model_helper.ModelHelper(name="train_net", arg_scope=arg_scope)
201
    	data, label = self.add_input(train_model, batch_size=batch_size, db=os.path.join(self.DATA_DIR, 'mnist-train-nchw-lmdb'), db_type='lmdb', device_opts=device_opts)
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    	predictions = self.create_model(train_model, data, device_opts=device_opts)
    	self.add_training_operators(train_model, predictions, label, device_opts, opt_type, base_learning_rate, policy, stepsize, epsilon, beta1, beta2, gamma, momentum)
    	self.add_accuracy(train_model, predictions, label, device_opts, eval_metric)
    	with core.DeviceScope(device_opts):
    		brew.add_weight_decay(train_model, weight_decay)

    	# Initialize and create the training network
    	workspace.RunNetOnce(train_model.param_init_net)
    	workspace.CreateNet(train_model.net, overwrite=True)

    	# Main Training Loop
    	print("== Starting Training for " + str(num_epoch) + " num_epoch ==")
    	for j in range(0, num_epoch):
    		workspace.RunNet(train_model.net)
    		if j % 50 == 0:
    			print 'Iter: ' + str(j) + ': ' + 'Loss ' + str(workspace.FetchBlob("loss")) + ' - ' + 'Accuracy ' + str(workspace.FetchBlob('accuracy'))
    	print("Training done")

    	print("== Running Test model ==")
    	# == Testing model. ==
    	test_model= model_helper.ModelHelper(name="test_net", arg_scope=arg_scope, init_params=False)
223
    	data, label = self.add_input(test_model, batch_size=100, db=os.path.join(self.DATA_DIR, 'mnist-test-nchw-lmdb'), db_type='lmdb', device_opts=device_opts)
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    	predictions = self.create_model(test_model, data, device_opts=device_opts)
    	self.add_accuracy(test_model, predictions, label, device_opts, eval_metric)
    	workspace.RunNetOnce(test_model.param_init_net)
    	workspace.CreateNet(test_model.net, overwrite=True)

    	# Main Testing Loop
    	# batch size:        100
    	# iteration:         100
    	# total test images: 10000
    	test_accuracy = np.zeros(100)
    	for i in range(100):
    		# Run a forward pass of the net on the current batch
    		workspace.RunNet(test_model.net)
    		# Collect the batch accuracy from the workspace
    		test_accuracy[i] = workspace.FetchBlob('accuracy')

    	print('Test_accuracy: {:.4f}'.format(test_accuracy.mean()))

    	# == Deployment model. ==
    	# We simply need the main AddModel part.
    	deploy_model = model_helper.ModelHelper(name="deploy_net", arg_scope=arg_scope, init_params=False)
    	self.create_model(deploy_model, "data", device_opts)

    	print("Saving deploy model")
    	self.save_net(self.INIT_NET, self.PREDICT_NET, deploy_model)

    def save_net(self, init_net_path, predict_net_path, model):

    	init_net, predict_net = mobile_exporter.Export(
    		workspace,
    		model.net,
    		model.params
    	)

258
259
260
261
262
263
        try:
            os.makedirs(self.MODEL_DIR)
        except OSError:
            if not os.path.isdir(self.MODEL_DIR):
                raise

264
    	print("Save the model to init_net.pb and predict_net.pb")
265
    	with open(predict_net_path, 'wb') as f:
266
    		f.write(model.net._net.SerializeToString())
267
    	with open(init_net_path, 'wb') as f:
268
269
270
    		f.write(init_net.SerializeToString())

    	print("Save the model to init_net.pbtxt and predict_net.pbtxt")
271
272

    	with open(init_net_path.replace('.pb','.pbtxt'), 'w') as f:
273
    		f.write(str(init_net))
274
    	with open(predict_net_path.replace('.pb','.pbtxt'), 'w') as f:
275
276
277
278
    		f.write(str(predict_net))
    	print("== Saved init_net and predict_net ==")

    def load_net(self, init_net_path, predict_net_path, device_opts):
279
280
281
282
283
284
285
286
287
288
        #TODO: Verify that paths ends in '.pb' and not in '.pbtxt'. The extension '.pbtxt' is not supported at the moment.
        if not os.path.isfile(init_net_path):
            logging.error("Network loading failure. File '" + os.path.abspath(init_net_path) + "' does not exist.")
            sys.exit(1)
        elif not os.path.isfile(predict_net_path):
            logging.error("Network loading failure. File '" + os.path.abspath(predict_net_path) + "' does not exist.")
            sys.exit(1)

        init_def = caffe2_pb2.NetDef()
    	with open(init_net_path, 'rb') as f:
289
290
291
292
293
    		init_def.ParseFromString(f.read())
    		init_def.device_option.CopyFrom(device_opts)
    		workspace.RunNetOnce(init_def.SerializeToString())

    	net_def = caffe2_pb2.NetDef()
294
    	with open(predict_net_path, 'rb') as f:
295
296
297
    		net_def.ParseFromString(f.read())
    		net_def.device_option.CopyFrom(device_opts)
    		workspace.CreateNet(net_def.SerializeToString(), overwrite=True)
298
    	print("== Loaded init_net and predict_net ==")