This repository has been archived by the owner on Jun 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 146
/
train.py
executable file
·219 lines (180 loc) · 7.69 KB
/
train.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
from __future__ import division
from utils.utils import *
from utils.cocoapi_evaluator import COCOAPIEvaluator
from utils.parse_yolo_weights import parse_yolo_weights
from models.yolov3 import *
from dataset.cocodataset import *
import os
import argparse
import yaml
import random
import torch
from torch.autograd import Variable
import torch.optim as optim
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', type=str, default='config/yolov3_default.cfg',
help='config file. see readme')
parser.add_argument('--weights_path', type=str,
default=None, help='darknet weights file')
parser.add_argument('--n_cpu', type=int, default=0,
help='number of workers')
parser.add_argument('--checkpoint_interval', type=int,
default=1000, help='interval between saving checkpoints')
parser.add_argument('--eval_interval', type=int,
default=4000, help='interval between evaluations')
parser.add_argument('--checkpoint', type=str,
help='pytorch checkpoint file path')
parser.add_argument('--checkpoint_dir', type=str,
default='checkpoints',
help='directory where checkpoint files are saved')
parser.add_argument('--use_cuda', type=bool, default=True)
parser.add_argument('--debug', action='store_true', default=False,
help='debug mode where only one image is trained')
parser.add_argument(
'--tfboard', help='tensorboard path for logging', type=str, default=None)
return parser.parse_args()
def main():
"""
YOLOv3 trainer. See README for details.
"""
args = parse_args()
print("Setting Arguments.. : ", args)
cuda = torch.cuda.is_available() and args.use_cuda
os.makedirs(args.checkpoint_dir, exist_ok=True)
# Parse config settings
with open(args.cfg, 'r') as f:
cfg = yaml.load(f)
print("successfully loaded config file: ", cfg)
lr = cfg['TRAIN']['LR']
momentum = cfg['TRAIN']['MOMENTUM']
decay = cfg['TRAIN']['DECAY']
burn_in = cfg['TRAIN']['BURN_IN']
iter_size = cfg['TRAIN']['MAXITER']
steps = eval(cfg['TRAIN']['STEPS'])
batch_size = cfg['TRAIN']['BATCHSIZE']
subdivision = cfg['TRAIN']['SUBDIVISION']
ignore_thre = cfg['TRAIN']['IGNORETHRE']
random_resize = cfg['AUGMENTATION']['RANDRESIZE']
print('effective_batch_size = batch_size * iter_size = %d * %d' %
(batch_size, subdivision))
# Learning rate setup
base_lr = lr
# Initiate model
model = YOLOv3(cfg['MODEL'], ignore_thre=ignore_thre)
if args.weights_path:
print("loading darknet weights....", args.weights_path)
parse_yolo_weights(model, args.weights_path)
elif args.checkpoint:
print("loading pytorch ckpt...", args.checkpoint)
state = torch.load(args.checkpoint)
if 'model_state_dict' in state.keys():
model.load_state_dict(state['model_state_dict'])
else:
model.load_state_dict(state)
if cuda:
print("using cuda")
model = model.cuda()
if args.tfboard:
print("using tfboard")
from tensorboardX import SummaryWriter
tblogger = SummaryWriter(args.tfboard)
model.train()
imgsize = cfg['TRAIN']['IMGSIZE']
dataset = COCODataset(model_type=cfg['MODEL']['TYPE'],
data_dir='COCO/',
img_size=imgsize,
augmentation=cfg['AUGMENTATION'],
debug=args.debug)
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=True, num_workers=args.n_cpu)
dataiterator = iter(dataloader)
evaluator = COCOAPIEvaluator(model_type=cfg['MODEL']['TYPE'],
data_dir='COCO/',
img_size=cfg['TEST']['IMGSIZE'],
confthre=cfg['TEST']['CONFTHRE'],
nmsthre=cfg['TEST']['NMSTHRE'])
dtype = torch.cuda.FloatTensor if cuda else torch.FloatTensor
# optimizer setup
# set weight decay only on conv.weight
params_dict = dict(model.named_parameters())
params = []
for key, value in params_dict.items():
if 'conv.weight' in key:
params += [{'params':value, 'weight_decay':decay * batch_size * subdivision}]
else:
params += [{'params':value, 'weight_decay':0.0}]
optimizer = optim.SGD(params, lr=base_lr, momentum=momentum,
dampening=0, weight_decay=decay * batch_size * subdivision)
iter_state = 0
if args.checkpoint:
if 'optimizer_state_dict' in state.keys():
optimizer.load_state_dict(state['optimizer_state_dict'])
iter_state = state['iter'] + 1
# TODO: replace the following scheduler with the PyTorch's official one
tmp_lr = base_lr
def set_lr(tmp_lr):
for param_group in optimizer.param_groups:
param_group['lr'] = tmp_lr / batch_size / subdivision
# start training loop
for iter_i in range(iter_state, iter_size + 1):
# COCO evaluation
if iter_i % args.eval_interval == 0 and iter_i > 0:
ap50_95, ap50 = evaluator.evaluate(model)
model.train()
if args.tfboard:
tblogger.add_scalar('val/COCOAP50', ap50, iter_i)
tblogger.add_scalar('val/COCOAP50_95', ap50_95, iter_i)
# learning rate scheduling
if iter_i < burn_in:
tmp_lr = base_lr * pow(iter_i / burn_in, 4)
set_lr(tmp_lr)
elif iter_i == burn_in:
tmp_lr = base_lr
set_lr(tmp_lr)
elif iter_i in steps:
tmp_lr = tmp_lr * 0.1
set_lr(tmp_lr)
# subdivision loop
optimizer.zero_grad()
for inner_iter_i in range(subdivision):
try:
imgs, targets, _, _ = next(dataiterator) # load a batch
except StopIteration:
dataiterator = iter(dataloader)
imgs, targets, _, _ = next(dataiterator) # load a batch
imgs = Variable(imgs.type(dtype))
targets = Variable(targets.type(dtype), requires_grad=False)
loss = model(imgs, targets)
loss.backward()
optimizer.step()
if iter_i % 10 == 0:
# logging
print('[Iter %d/%d] [lr %f] '
'[Losses: xy %f, wh %f, conf %f, cls %f, total %f, imgsize %d]'
% (iter_i, iter_size, tmp_lr,
model.loss_dict['xy'], model.loss_dict['wh'],
model.loss_dict['conf'], model.loss_dict['cls'],
model.loss_dict['l2'], imgsize),
flush=True)
if args.tfboard:
tblogger.add_scalar('train/total_loss', model.loss_dict['l2'], iter_i)
# random resizing
if random_resize:
imgsize = (random.randint(0, 9) % 10 + 10) * 32
dataset.img_shape = (imgsize, imgsize)
dataset.img_size = imgsize
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=True, num_workers=args.n_cpu)
dataiterator = iter(dataloader)
# save checkpoint
if iter_i > 0 and (iter_i % args.checkpoint_interval == 0):
torch.save({'iter': iter_i,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
},
os.path.join(args.checkpoint_dir, "snapshot"+str(iter_i)+".ckpt"))
if args.tfboard:
tblogger.close()
if __name__ == '__main__':
main()