-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathconvert_darknet_torch.py
executable file
·141 lines (123 loc) · 5.51 KB
/
convert_darknet_torch.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
"""
Copyright (C) 2017, 申瑞珉 (Ruimin Shen)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import argparse
import configparser
import logging
import logging.config
import struct
import collections
import shutil
import hashlib
import yaml
import numpy as np
import torch
import humanize
import model
import utils.train
def transpose_weight(weight, num_anchors):
_, channels_in, ksize1, ksize2 = weight.size()
weight = weight.view(num_anchors, -1, channels_in, ksize1, ksize2)
x = weight[:, 0:1, :, :, :]
y = weight[:, 1:2, :, :, :]
w = weight[:, 2:3, :, :, :]
h = weight[:, 3:4, :, :, :]
iou = weight[:, 4:5, :, :, :]
cls = weight[:, 5:, :, :, :]
return torch.cat([iou, y, x, h, w, cls], 1).view(-1, channels_in, ksize1, ksize2)
def transpose_bias(bias, num_anchors):
bias = bias.view([num_anchors, -1])
x = bias[:, 0:1]
y = bias[:, 1:2]
w = bias[:, 2:3]
h = bias[:, 3:4]
iou = bias[:, 4:5]
cls = bias[:, 5:]
return torch.cat([iou, y, x, h, w, cls], 1).view(-1)
def group_state(state_dict):
grouped_dict = collections.OrderedDict()
for key, var in state_dict.items():
layer, suffix1, suffix2 = key.rsplit('.', 2)
suffix = suffix1 + '.' + suffix2
if layer in grouped_dict:
grouped_dict[layer][suffix] = var
else:
grouped_dict[layer] = {suffix: var}
return grouped_dict
def main():
args = make_args()
config = configparser.ConfigParser()
utils.load_config(config, args.config)
for cmd in args.modify:
utils.modify_config(config, cmd)
with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
logging.config.dictConfig(yaml.load(f))
cache_dir = utils.get_cache_dir(config)
model_dir = utils.get_model_dir(config)
category = utils.get_category(config, cache_dir if os.path.exists(cache_dir) else None)
anchors = utils.get_anchors(config)
anchors = torch.from_numpy(anchors).contiguous()
dnn = utils.parse_attr(config.get('model', 'dnn'))(model.ConfigChannels(config), anchors, len(category))
dnn.eval()
logging.info(humanize.naturalsize(sum(var.cpu().numpy().nbytes for var in dnn.state_dict().values())))
state_dict = dnn.state_dict()
grouped_dict = group_state(state_dict)
try:
layers = []
with open(os.path.expanduser(os.path.expandvars(args.file)), 'rb') as f:
major, minor, revision, seen = struct.unpack('4i', f.read(16))
logging.info('major=%d, minor=%d, revision=%d, seen=%d' % (major, minor, revision, seen))
total = 0
filesize = os.fstat(f.fileno()).st_size
for layer in grouped_dict:
group = grouped_dict[layer]
for suffix in ['conv.bias', 'bn.bias', 'bn.weight', 'bn.running_mean', 'bn.running_var', 'conv.weight']:
if suffix in group:
var = group[suffix]
size = var.size()
cnt = np.multiply.reduce(size)
total += cnt
key = layer + '.' + suffix
val = np.array(struct.unpack('%df' % cnt, f.read(cnt * 4)), np.float32)
val = np.reshape(val, size)
remaining = filesize - f.tell()
logging.info('%s.%s: %s=%f (%s), remaining=%d' % (layer, suffix, 'x'.join(list(map(str, size))), utils.abs_mean(val), hashlib.md5(val.tostring()).hexdigest(), remaining))
layers.append([key, torch.from_numpy(val)])
logging.info('%d parameters assigned' % total)
layers[-1][1] = transpose_weight(layers[-1][1], len(anchors))
layers[-2][1] = transpose_bias(layers[-2][1], len(anchors))
finally:
if remaining > 0:
logging.warning('%d bytes remaining' % remaining)
state_dict = collections.OrderedDict(layers)
if args.delete:
logging.warning('delete model directory: ' + model_dir)
shutil.rmtree(model_dir, ignore_errors=True)
saver = utils.train.Saver(model_dir, config.getint('save', 'keep'), logger=None)
path = saver(state_dict, 0, 0) + saver.ext
if args.copy is not None:
_path = os.path.expandvars(os.path.expanduser(args.copy))
logging.info('copy %s to %s' % (path, _path))
shutil.copy(path, _path)
def make_args():
parser = argparse.ArgumentParser()
parser.add_argument('file', help='Darknet .weights file')
parser.add_argument('-c', '--config', nargs='+', default=['config.ini'], help='config file')
parser.add_argument('-m', '--modify', nargs='+', default=[], help='modify config')
parser.add_argument('-d', '--delete', action='store_true', help='delete logdir')
parser.add_argument('--copy', help='copy model')
parser.add_argument('--logging', default='logging.yml', help='logging config')
return parser.parse_args()
if __name__ == '__main__':
main()