This repository has been archived by the owner on Jul 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 303
/
train_multi.py
311 lines (263 loc) · 11.2 KB
/
train_multi.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
301
302
303
304
305
306
307
308
309
310
311
from __future__ import division
import argparse
import multiprocessing
import numpy as np
import PIL
import chainer
import chainer.functions as F
import chainer.links as L
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
import chainermn
from chainercv.chainer_experimental.datasets.sliceable import TransformDataset
from chainercv.chainer_experimental.training.extensions import make_shift
from chainercv.links.model.fpn.misc import scale_img
from chainercv import transforms
from chainercv.datasets import coco_instance_segmentation_label_names
from chainercv.datasets import COCOInstanceSegmentationDataset
from chainercv.links import MaskRCNNFPNResNet101
from chainercv.links import MaskRCNNFPNResNet50
from chainercv.datasets import coco_bbox_label_names
from chainercv.datasets import COCOBboxDataset
from chainercv.links import FasterRCNNFPNResNet101
from chainercv.links import FasterRCNNFPNResNet50
from chainercv.links.model.fpn import bbox_head_loss_post
from chainercv.links.model.fpn import bbox_head_loss_pre
from chainercv.links.model.fpn import mask_head_loss_post
from chainercv.links.model.fpn import mask_head_loss_pre
from chainercv.links.model.fpn import rpn_loss
# https://docs.chainer.org/en/stable/tips.html#my-training-process-gets-stuck-when-using-multiprocessiterator
try:
import cv2
cv2.setNumThreads(0)
except ImportError:
pass
class TrainChain(chainer.Chain):
def __init__(self, model):
super(TrainChain, self).__init__()
with self.init_scope():
self.model = model
def forward(self, imgs, bboxes, labels, masks=None):
B = len(imgs)
pad_size = np.array(
[im.shape[1:] for im in imgs]).max(axis=0)
pad_size = (
np.ceil(
pad_size / self.model.stride) * self.model.stride).astype(int)
x = np.zeros(
(len(imgs), 3, pad_size[0], pad_size[1]), dtype=np.float32)
for i, img in enumerate(imgs):
_, H, W = img.shape
x[i, :, :H, :W] = img
x = self.xp.array(x)
bboxes = [self.xp.array(bbox) for bbox in bboxes]
labels = [self.xp.array(label) for label in labels]
sizes = [img.shape[1:] for img in imgs]
with chainer.using_config('train', False):
hs = self.model.extractor(x)
rpn_locs, rpn_confs = self.model.rpn(hs)
anchors = self.model.rpn.anchors(h.shape[2:] for h in hs)
rpn_loc_loss, rpn_conf_loss = rpn_loss(
rpn_locs, rpn_confs, anchors, sizes, bboxes)
rois, roi_indices = self.model.rpn.decode(
rpn_locs, rpn_confs, anchors, x.shape)
rois = self.xp.vstack([rois] + bboxes)
roi_indices = self.xp.hstack(
[roi_indices]
+ [self.xp.array((i,) * len(bbox))
for i, bbox in enumerate(bboxes)])
rois, roi_indices = self.model.bbox_head.distribute(rois, roi_indices)
rois, roi_indices, head_gt_locs, head_gt_labels = bbox_head_loss_pre(
rois, roi_indices, self.model.bbox_head.std, bboxes, labels)
head_locs, head_confs = self.model.bbox_head(hs, rois, roi_indices)
head_loc_loss, head_conf_loss = bbox_head_loss_post(
head_locs, head_confs,
roi_indices, head_gt_locs, head_gt_labels, B)
mask_loss = 0
if masks is not None:
# For reducing unnecessary CPU/GPU copy, `masks` is kept in CPU.
pad_masks = [
np.zeros(
(mask.shape[0], pad_size[0], pad_size[1]), dtype=np.bool)
for mask in masks]
for i, mask in enumerate(masks):
_, H, W = mask.shape
pad_masks[i][:, :H, :W] = mask
masks = pad_masks
mask_rois, mask_roi_indices, gt_segms, gt_mask_labels =\
mask_head_loss_pre(
rois, roi_indices, masks, bboxes,
head_gt_labels, self.model.mask_head.segm_size)
n_roi = sum([len(roi) for roi in mask_rois])
if n_roi > 0:
segms = self.model.mask_head(hs, mask_rois, mask_roi_indices)
mask_loss = mask_head_loss_post(
segms, mask_roi_indices, gt_segms, gt_mask_labels, B)
else:
# Compute dummy variables to complete the computational graph
mask_rois[0] = self.xp.array([[0, 0, 1, 1]], dtype=np.float32)
mask_roi_indices[0] = self.xp.array([0], dtype=np.int32)
segms = self.model.mask_head(hs, mask_rois, mask_roi_indices)
mask_loss = 0 * F.sum(segms)
loss = (rpn_loc_loss + rpn_conf_loss +
head_loc_loss + head_conf_loss + mask_loss)
chainer.reporter.report({
'loss': loss,
'loss/rpn/loc': rpn_loc_loss, 'loss/rpn/conf': rpn_conf_loss,
'loss/bbox_head/loc': head_loc_loss,
'loss/bbox_head/conf': head_conf_loss,
'loss/mask_head': mask_loss},
self)
return loss
class Transform(object):
def __init__(self, min_size, max_size, mean):
self.min_size = min_size
self.max_size = max_size
self.mean = mean
def __call__(self, in_data):
if len(in_data) == 4:
img, mask, label, bbox = in_data
else:
img, bbox, label = in_data
# Flipping
img, params = transforms.random_flip(
img, x_random=True, return_param=True)
x_flip = params['x_flip']
bbox = transforms.flip_bbox(
bbox, img.shape[1:], x_flip=x_flip)
# Scaling and mean subtraction
img, scale = scale_img(
img, self.min_size, self.max_size)
img -= self.mean
bbox = bbox * scale
if len(in_data) == 4:
mask = transforms.flip(mask, x_flip=x_flip)
mask = transforms.resize(
mask.astype(np.float32),
img.shape[1:],
interpolation=PIL.Image.NEAREST).astype(np.bool)
return img, bbox, label, mask
else:
return img, bbox, label
def converter(batch, device=None):
# do not send data to gpu (device is ignored)
return tuple(list(v) for v in zip(*batch))
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model',
choices=('mask_rcnn_fpn_resnet50', 'mask_rcnn_fpn_resnet101',
'faster_rcnn_fpn_resnet50', 'faster_rcnn_fpn_resnet101'),
default='faster_rcnn_fpn_resnet50')
parser.add_argument('--batchsize', type=int, default=16)
parser.add_argument('--iteration', type=int, default=90000)
parser.add_argument('--step', type=int, nargs='*', default=[60000, 80000])
parser.add_argument('--out', default='result')
parser.add_argument('--resume')
args = parser.parse_args()
# https://docs.chainer.org/en/stable/chainermn/tutorial/tips_faqs.html#using-multiprocessiterator
if hasattr(multiprocessing, 'set_start_method'):
multiprocessing.set_start_method('forkserver')
p = multiprocessing.Process()
p.start()
p.join()
comm = chainermn.create_communicator('pure_nccl')
device = comm.intra_rank
if args.model == 'faster_rcnn_fpn_resnet50':
mode = 'bbox'
model = FasterRCNNFPNResNet50(
n_fg_class=len(coco_bbox_label_names),
pretrained_model='imagenet')
elif args.model == 'faster_rcnn_fpn_resnet101':
mode = 'bbox'
model = FasterRCNNFPNResNet101(
n_fg_class=len(coco_bbox_label_names),
pretrained_model='imagenet')
elif args.model == 'mask_rcnn_fpn_resnet50':
mode = 'instance_segmentation'
model = MaskRCNNFPNResNet50(
n_fg_class=len(coco_instance_segmentation_label_names),
pretrained_model='imagenet')
elif args.model == 'mask_rcnn_fpn_resnet101':
mode = 'instance_segmentation'
model = MaskRCNNFPNResNet101(
n_fg_class=len(coco_instance_segmentation_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = TrainChain(model)
chainer.cuda.get_device_from_id(device).use()
train_chain.to_gpu()
if mode == 'bbox':
train = TransformDataset(
COCOBboxDataset(year='2017', split='train'),
('img', 'bbox', 'label'),
Transform(800, 1333, model.extractor.mean))
elif mode == 'instance_segmentation':
train = TransformDataset(
COCOInstanceSegmentationDataset(split='train', return_bbox=True),
('img', 'bbox', 'label', 'mask'),
Transform(800, 1333, model.extractor.mean))
if comm.rank == 0:
indices = np.arange(len(train))
else:
indices = None
indices = chainermn.scatter_dataset(indices, comm, shuffle=True)
train = train.slice[indices]
train_iter = chainer.iterators.MultiprocessIterator(
train, args.batchsize // comm.size,
n_processes=args.batchsize // comm.size,
shared_mem=100 * 1000 * 1000 * 4)
optimizer = chainermn.create_multi_node_optimizer(
chainer.optimizers.MomentumSGD(), comm)
optimizer.setup(train_chain)
optimizer.add_hook(WeightDecay(0.0001))
model.extractor.base.conv1.disable_update()
model.extractor.base.res2.disable_update()
for link in model.links():
if isinstance(link, L.BatchNormalization):
link.disable_update()
n_iteration = args.iteration * 16 / args.batchsize
updater = training.updaters.StandardUpdater(
train_iter, optimizer, converter=converter, device=device)
trainer = training.Trainer(
updater, (n_iteration, 'iteration'), args.out)
@make_shift('lr')
def lr_schedule(trainer):
base_lr = 0.02 * args.batchsize / 16
warm_up_duration = 500
warm_up_rate = 1 / 3
iteration = trainer.updater.iteration
if iteration < warm_up_duration:
rate = warm_up_rate \
+ (1 - warm_up_rate) * iteration / warm_up_duration
else:
rate = 1
for step in args.step:
if iteration >= step * 16 / args.batchsize:
rate *= 0.1
return base_lr * rate
trainer.extend(lr_schedule)
if comm.rank == 0:
log_interval = 10, 'iteration'
trainer.extend(extensions.LogReport(trigger=log_interval))
trainer.extend(extensions.observe_lr(), trigger=log_interval)
trainer.extend(extensions.PrintReport(
['epoch', 'iteration', 'lr', 'main/loss',
'main/loss/rpn/loc', 'main/loss/rpn/conf',
'main/loss/bbox_head/loc', 'main/loss/bbox_head/conf',
'main/loss/mask_head'
]),
trigger=log_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(extensions.snapshot(), trigger=(10000, 'iteration'))
trainer.extend(
extensions.snapshot_object(
model, 'model_iter_{.updater.iteration}'),
trigger=(n_iteration, 'iteration'))
if args.resume:
serializers.load_npz(args.resume, trainer, strict=False)
trainer.run()
if __name__ == '__main__':
main()