-
Notifications
You must be signed in to change notification settings - Fork 276
/
caffe2darknet.py
300 lines (282 loc) · 11.4 KB
/
caffe2darknet.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
221
222
223
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from collections import OrderedDict
from cfg import *
from prototxt import *
import numpy as np
try:
import caffe_pb2
except:
print 'caffe_pb2.py not found. Try:'
print ' protoc caffe.proto --python_out=.'
exit()
def parse_caffemodel(caffemodel):
model = caffe_pb2.NetParameter()
print 'Loading caffemodel: ', caffemodel
with open(caffemodel, 'rb') as fp:
model.ParseFromString(fp.read())
return model
def caffe2darknet(protofile, caffemodel):
model = parse_caffemodel(caffemodel)
layers = model.layer
if len(layers) == 0:
print 'Using V1LayerParameter'
layers = model.layers
lmap = {}
for l in layers:
lmap[l.name] = l
net_info = parse_prototxt(protofile)
props = net_info['props']
wdata = []
blocks = []
block = OrderedDict()
block['type'] = 'net'
block['batch'] = props['input_dim'][0]
block['channels'] = props['input_dim'][1]
block['height'] = props['input_dim'][2]
block['width'] = props['input_dim'][3]
blocks.append(block)
layers = net_info['layers']
layer_num = len(layers)
i = 0 # layer id
layer_id = dict()
layer_id[props['input']] = 0
while i < layer_num:
layer = layers[i]
print i,layer['name'], layer['type']
if layer['type'] == 'Convolution':
if layer_id[layer['bottom']] != len(blocks)-1:
block = OrderedDict()
block['type'] = 'route'
block['layers'] = str(layer_id[layer['bottom']] - len(blocks))
blocks.append(block)
#assert(i+1 < layer_num and layers[i+1]['type'] == 'BatchNorm')
#assert(i+2 < layer_num and layers[i+2]['type'] == 'Scale')
conv_layer = layers[i]
block = OrderedDict()
block['type'] = 'convolutional'
block['filters'] = conv_layer['convolution_param']['num_output']
block['size'] = conv_layer['convolution_param']['kernel_size']
block['stride'] = conv_layer['convolution_param']['stride']
block['pad'] = '1'
last_layer = conv_layer
m_conv_layer = lmap[conv_layer['name']]
if i+2 < layer_num and layers[i+1]['type'] == 'BatchNorm' and layers[i+2]['type'] == 'Scale':
block['batch_normalize'] = '1'
bn_layer = layers[i+1]
scale_layer = layers[i+2]
last_layer = scale_layer
m_scale_layer = lmap[scale_layer['name']]
m_bn_layer = lmap[bn_layer['name']]
wdata += list(m_scale_layer.blobs[1].data) ## conv_bias <- sc_beta
wdata += list(m_scale_layer.blobs[0].data) ## bn_scale <- sc_alpha
wdata += (np.array(m_bn_layer.blobs[0].data) / m_bn_layer.blobs[2].data[0]).tolist() ## bn_mean <- bn_mean/bn_scale
wdata += (np.array(m_bn_layer.blobs[1].data) / m_bn_layer.blobs[2].data[0]).tolist() ## bn_var <- bn_var/bn_scale
i = i + 2
else:
wdata += list(m_conv_layer.blobs[1].data) ## conv_bias
wdata += list(m_conv_layer.blobs[0].data) ## conv_weights
if i+1 < layer_num and layers[i+1]['type'] == 'ReLU':
act_layer = layers[i+1]
block['activation'] = 'relu'
top = act_layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 2
else:
block['activation'] = 'linear'
top = last_layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
elif layer['type'] == 'Pooling':
assert(layer_id[layer['bottom']] == len(blocks)-1)
block = OrderedDict()
if layer['pooling_param']['pool'] == 'AVE':
block['type'] = 'avgpool'
elif layer['pooling_param']['pool'] == 'MAX':
block['type'] = 'maxpool'
block['size'] = layer['pooling_param']['kernel_size']
block['stride'] = layer['pooling_param']['stride']
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
elif layer['type'] == 'Eltwise':
bottoms = layer['bottom']
bottom1 = layer_id[bottoms[0]] - len(blocks)
bottom2 = layer_id[bottoms[1]] - len(blocks)
assert(bottom1 == -1 or bottom2 == -1)
from_id = bottom2 if bottom1 == -1 else bottom1
block = OrderedDict()
block['type'] = 'shortcut'
block['from'] = str(from_id)
assert(i+1 < layer_num and layers[i+1]['type'] == 'ReLU')
block['activation'] = 'relu'
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 2
elif layer['type'] == 'InnerProduct':
assert(layer_id[layer['bottom']] == len(blocks)-1)
block = OrderedDict()
block['type'] = 'connected'
block['output'] = layer['inner_product_param']['num_output']
m_fc_layer = lmap[layer['name']]
wdata += list(m_fc_layer.blobs[1].data) ## fc_bias
wdata += list(m_fc_layer.blobs[0].data) ## fc_weights
if i+1 < layer_num and layers[i+1]['type'] == 'ReLU':
act_layer = layers[i+1]
block['activation'] = 'relu'
top = act_layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 2
else:
block['activation'] = 'linear'
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
elif layer['type'] == 'Softmax':
assert(layer_id[layer['bottom']] == len(blocks)-1)
block = OrderedDict()
block['type'] = 'softmax'
block['groups'] = 1
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
print 'done'
return blocks, np.array(wdata)
def prototxt2cfg(protofile):
net_info = parse_prototxt(protofile)
props = net_info['props']
blocks = []
block = OrderedDict()
block['type'] = 'net'
block['batch'] = props['input_dim'][0]
block['channels'] = props['input_dim'][1]
block['height'] = props['input_dim'][2]
block['width'] = props['input_dim'][3]
blocks.append(block)
layers = net_info['layers']
layer_num = len(layers)
i = 0 # layer id
layer_id = dict()
layer_id[props['input']] = 0
while i < layer_num:
layer = layers[i]
if layer['type'] == 'Convolution':
if layer_id[layer['bottom']] != len(blocks)-1:
block = OrderedDict()
block['type'] = 'route'
block['layers'] = str(layer_id[layer['bottom']] - len(blocks))
blocks.append(block)
assert(i+1 < layer_num and layers[i+1]['type'] == 'BatchNorm')
assert(i+2 < layer_num and layers[i+2]['type'] == 'Scale')
conv_layer = layers[i]
bn_layer = layers[i+1]
scale_layer = layers[i+2]
block = OrderedDict()
block['type'] = 'convolutional'
block['batch_normalize'] = '1'
block['filters'] = conv_layer['convolution_param']['num_output']
block['size'] = conv_layer['convolution_param']['kernel_size']
block['stride'] = conv_layer['convolution_param']['stride']
block['pad'] = '1'
if i+3 < layer_num and layers[i+3]['type'] == 'ReLU':
act_layer = layers[i+3]
block['activation'] = 'relu'
top = act_layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 4
else:
block['activation'] = 'linear'
top = scale_layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 3
elif layer['type'] == 'Pooling':
assert(layer_id[layer['bottom']] == len(blocks)-1)
block = OrderedDict()
if layer['pooling_param']['pool'] == 'AVE':
block['type'] = 'avgpool'
elif layer['pooling_param']['pool'] == 'MAX':
block['type'] = 'maxpool'
block['size'] = layer['pooling_param']['kernel_size']
block['stride'] = layer['pooling_param']['stride']
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
elif layer['type'] == 'Eltwise':
bottoms = layer['bottom']
bottom1 = layer_id[bottoms[0]] - len(blocks)
bottom2 = layer_id[bottoms[1]] - len(blocks)
assert(bottom1 == -1 or bottom2 == -1)
from_id = bottom2 if bottom1 == -1 else bottom1
block = OrderedDict()
block['type'] = 'shortcut'
block['from'] = str(from_id)
assert(i+1 < layer_num and layers[i+1]['type'] == 'ReLU')
block['activation'] = 'relu'
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 2
elif layer['type'] == 'InnerProduct':
assert(layer_id[layer['bottom']] == len(blocks)-1)
block = OrderedDict()
block['type'] = 'connected'
block['output'] = layer['inner_product_param']['num_output']
if i+1 < layer_num and layers[i+1]['type'] == 'ReLU':
act_layer = layers[i+1]
block['activation'] = 'relu'
top = act_layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 2
else:
block['activation'] = 'linear'
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
elif layer['type'] == 'Softmax':
assert(layer_id[layer['bottom']] == len(blocks)-1)
block = OrderedDict()
block['type'] = 'softmax'
block['groups'] = 1
top = layer['top']
layer_id[top] = len(blocks)
blocks.append(block)
i = i + 1
return blocks
def save_weights(data, weightfile):
print 'Save to ', weightfile
wsize = data.size
weights = np.zeros((wsize+4,), dtype=np.int32)
## write info
weights[0] = 0
weights[1] = 1
weights[2] = 0 ## revision
weights[3] = 0 ## net.seen
weights.tofile(weightfile)
weights = np.fromfile(weightfile, dtype=np.float32)
weights[4:] = data
weights.tofile(weightfile)
if __name__ == '__main__':
import sys
if len(sys.argv) != 5:
print('try:')
print(' python caffe2darknet.py ResNet-50-deploy.prototxt ResNet-50-model.caffemodel ResNet-50-model.cfg ResNet-50-model.weights')
exit()
protofile = sys.argv[1]
caffemodel = sys.argv[2]
cfgfile = sys.argv[3]
weightfile = sys.argv[4]
blocks, data = caffe2darknet(protofile, caffemodel)
save_weights(data, weightfile)
save_cfg(blocks, cfgfile)
print_cfg(blocks)
print_cfg_nicely(blocks)