-
Notifications
You must be signed in to change notification settings - Fork 18
/
dltrainer.py
361 lines (303 loc) · 15.8 KB
/
dltrainer.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
from __future__ import print_function
import os, sys, gc
import time
import torch
import torch.nn.functional as F
import numpy as np
from torchvision import transforms
from torch.utils.data import DataLoader
from net_builder import build_net
from dataloader.SceneFlowLoader import SceneFlowDataset
from dataloader.SIRSLoader import SIRSDataset
from dataloader.SintelLoader import SintelDataset
from utils.AverageMeter import AverageMeter
from utils.common import logger
from losses.multiscaleloss import EPE
from losses.normalloss import angle_diff_angle, angle_diff_norm
from utils.preprocess import scale_disp, scale_norm, scale_angle
import skimage
class DisparityTrainer(object):
def __init__(self, net_name, lr, devices, dataset, trainlist, vallist, datapath, batch_size, maxdisp, pretrain=None):
super(DisparityTrainer, self).__init__()
self.net_name = net_name
self.lr = lr
self.current_lr = lr
self.devices = devices
self.devices = [int(item) for item in devices.split(',')]
ngpu = len(devices)
self.ngpu = ngpu
self.trainlist = trainlist
self.vallist = vallist
self.dataset = dataset
self.datapath = datapath
self.batch_size = batch_size
self.pretrain = pretrain
self.maxdisp = maxdisp
#self.criterion = criterion
self.criterion = None
self.epe = EPE
self.initialize()
def _prepare_dataset(self):
if self.net_name in ["dispnormnet"]:
self.disp_on = True
self.norm_on = True
self.angle_on = False
else:
self.disp_on = True
self.norm_on = False
self.angle_on = False
if self.dataset == 'irs':
train_dataset = SIRSDataset(txt_file = self.trainlist, root_dir = self.datapath, phase='train', load_disp = self.disp_on, load_norm = self.norm_on, to_angle = self.angle_on)
test_dataset = SIRSDataset(txt_file = self.vallist, root_dir = self.datapath, phase='test', load_disp = self.disp_on, load_norm = self.norm_on, to_angle=self.angle_on)
if self.dataset == 'sceneflow':
train_dataset = SceneFlowDataset(txt_file = self.trainlist, root_dir = self.datapath, phase='train')
test_dataset = SceneFlowDataset(txt_file = self.vallist, root_dir = self.datapath, phase='test')
if self.dataset == 'sintel':
train_dataset = SintelDataset(txt_file = self.trainlist, root_dir = self.datapath, phase='train')
test_dataset = SintelDataset(txt_file = self.vallist, root_dir = self.datapath, phase='test')
self.fx, self.fy = train_dataset.get_focal_length()
self.img_height, self.img_width = train_dataset.get_img_size()
self.scale_height, self.scale_width = test_dataset.get_scale_size()
datathread=4
if os.environ.get('datathread') is not None:
datathread = int(os.environ.get('datathread'))
logger.info("Use %d processes to load data..." % datathread)
self.train_loader = DataLoader(train_dataset, batch_size = self.batch_size, \
shuffle = True, num_workers = datathread, \
pin_memory = True)
self.test_loader = DataLoader(test_dataset, batch_size = self.batch_size / 4, \
shuffle = False, num_workers = datathread, \
pin_memory = True)
self.num_batches_per_epoch = len(self.train_loader)
def _build_net(self):
# build net according to the net name
if self.net_name in ["normnetc"]:
self.net = build_net(self.net_name)()
else:
self.net = build_net(self.net_name)(batchNorm=False, lastRelu=True, maxdisp=self.maxdisp)
# set predicted target
if self.net_name in ["dispnormnet"]:
self.net.set_focal_length(self.fx, self.fy)
self.is_pretrain = False
if self.ngpu > 1:
self.net = torch.nn.DataParallel(self.net, device_ids=self.devices).cuda()
else:
self.net.cuda()
if self.pretrain == '':
logger.info('Initial a new model...')
else:
if os.path.isfile(self.pretrain):
model_data = torch.load(self.pretrain)
logger.info('Load pretrain model: %s', self.pretrain)
if 'state_dict' in model_data.keys():
self.net.load_state_dict(model_data['state_dict'])
else:
self.net.load_state_dict(model_data)
self.is_pretrain = True
else:
logger.warning('Can not find the specific model %s, initial a new model...', self.pretrain)
def _build_optimizer(self):
beta = 0.999
momentum = 0.9
self.optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.net.parameters()), self.lr,
betas=(momentum, beta), amsgrad=True)
def initialize(self):
self._prepare_dataset()
self._build_net()
self._build_optimizer()
def adjust_learning_rate(self, epoch):
cur_lr = self.lr / (2**(epoch// 10))
for param_group in self.optimizer.param_groups:
param_group['lr'] = cur_lr
self.current_lr = cur_lr
return cur_lr
def set_criterion(self, criterion):
self.criterion = criterion
def train_one_epoch(self, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
flow2_EPEs = AverageMeter()
norm_EPEs = AverageMeter()
angle_EPEs = AverageMeter()
# switch to train mode
self.net.train()
end = time.time()
cur_lr = self.adjust_learning_rate(epoch)
logger.info("learning rate of epoch %d: %f." % (epoch, cur_lr))
for i_batch, sample_batched in enumerate(self.train_loader):
left_input = torch.autograd.Variable(sample_batched['img_left'].cuda(), requires_grad=False)
right_input = torch.autograd.Variable(sample_batched['img_right'].cuda(), requires_grad=False)
input = torch.cat((left_input, right_input), 1)
if self.disp_on:
target_disp = sample_batched['gt_disp']
target_disp = target_disp.cuda()
target_disp = torch.autograd.Variable(target_disp, requires_grad=False)
if self.norm_on:
if self.angle_on:
target_angle = sample_batched['gt_angle']
target_angle = target_angle.cuda()
target_angle = torch.autograd.Variable(target_angle, requires_grad=False)
else:
target_norm = sample_batched['gt_norm']
target_norm = target_norm.cuda()
target_norm = torch.autograd.Variable(target_norm, requires_grad=False)
input_var = torch.autograd.Variable(input, requires_grad=False)
data_time.update(time.time() - end)
self.optimizer.zero_grad()
if self.net_name in ["dispnormnet"]:
disp_norm = self.net(input_var)
disps = disp_norm[0]
normal = disp_norm[1]
loss_disp = self.criterion(disps, target_disp)
valid_norm_idx = (target_norm >= -1.0) & (target_norm <= 1.0)
loss_norm = F.mse_loss(normal[valid_norm_idx], target_norm[valid_norm_idx], size_average=True) * 3.0
loss = loss_disp + loss_norm
final_disp = disps[0]
flow2_EPE = self.epe(final_disp, target_disp)
norm_EPE = loss_norm
elif self.net_name == "dispnetcres":
output_net1, output_net2 = self.net(input_var)
loss_net1 = self.criterion(output_net1, target_disp)
loss_net2 = self.criterion(output_net2, target_disp)
loss = loss_net1 + loss_net2
output_net2_final = output_net2[0]
flow2_EPE = self.epe(output_net2_final, target_disp)
elif self.net_name == "dispnetcss":
output_net1, output_net2, output_net3 = self.net(input_var)
loss_net1 = self.criterion(output_net1, target_disp)
loss_net2 = self.criterion(output_net2, target_disp)
loss_net3 = self.criterion(output_net3, target_disp)
loss = loss_net1 + loss_net2 + loss_net3
output_net3_final = output_net3[0]
flow2_EPE = self.epe(output_net3_final, target_disp)
else:
output = self.net(input_var)
loss = self.criterion(output, target_disp)
if type(loss) is list or type(loss) is tuple:
loss = np.sum(loss)
if type(output) is list or type(output) is tuple:
flow2_EPE = self.epe(output[0], target_disp)
else:
flow2_EPE = self.epe(output, target_disp)
# record loss and EPE
losses.update(loss.data.item(), input_var.size(0))
if self.disp_on:
flow2_EPEs.update(flow2_EPE.data.item(), input_var.size(0))
if self.norm_on:
if self.angle_on:
angle_EPEs.update(angle_EPE.data.item(), input_var.size(0))
else:
norm_EPEs.update(norm_EPE.data.item(), input_var.size(0))
# compute gradient and do SGD step
loss.backward()
self.optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i_batch % 10 == 0:
logger.info('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.3f} ({loss.avg:.3f})\t'
'EPE {flow2_EPE.val:.3f} ({flow2_EPE.avg:.3f})\t'
'norm_EPE {norm_EPE.val:.3f} ({norm_EPE.avg:.3f})\t'
'angle_EPE {angle_EPE.val:.3f} ({angle_EPE.avg:.3f})'.format(
epoch, i_batch, self.num_batches_per_epoch, batch_time=batch_time,
data_time=data_time, loss=losses, flow2_EPE=flow2_EPEs, norm_EPE=norm_EPEs, angle_EPE=angle_EPEs))
return losses.avg, flow2_EPEs.avg
def validate(self):
batch_time = AverageMeter()
flow2_EPEs = AverageMeter()
norm_EPEs = AverageMeter()
angle_EPEs = AverageMeter()
losses = AverageMeter()
# switch to evaluate mode
self.net.eval()
end = time.time()
for i, sample_batched in enumerate(self.test_loader):
left_input = torch.autograd.Variable(sample_batched['img_left'].cuda(), requires_grad=False)
right_input = torch.autograd.Variable(sample_batched['img_right'].cuda(), requires_grad=False)
input = torch.cat((left_input, right_input), 1)
input_var = torch.autograd.Variable(input, requires_grad=False)
if self.disp_on:
target_disp = sample_batched['gt_disp']
target_disp = target_disp.cuda()
target_disp = torch.autograd.Variable(target_disp, requires_grad=False)
if self.norm_on:
if self.angle_on:
target_angle = sample_batched['gt_angle']
target_angle = target_angle.cuda()
target_angle = torch.autograd.Variable(target_angle, requires_grad=False)
else:
target_norm = sample_batched['gt_norm']
target_norm = target_norm.cuda()
target_norm = torch.autograd.Variable(target_norm, requires_grad=False)
if self.net_name in ["dispnormnet"]:
disp, normal = self.net(input_var)
size = disp.size()
# scale the result
disp_norm = torch.cat((normal, disp), 1)
disp_norm = scale_norm(disp_norm, (size[0], 4, self.img_height, self.img_width), True)
disp = disp_norm[:, 3, :, :].unsqueeze(1)
normal = disp_norm[:, :3, :, :]
# normalize the surface normal
#normal = normal / torch.norm(normal, 2, dim=1, keepdim=True)
valid_norm_idx = (target_norm >= -1.0) & (target_norm <= 1.0)
norm_EPE = F.mse_loss(normal[valid_norm_idx], target_norm[valid_norm_idx], size_average=True) * 3.0
flow2_EPE = self.epe(disp, target_disp)
norm_angle = angle_diff_norm(normal, target_norm).squeeze()
valid_angle_idx = valid_norm_idx[:,0,:,:] & valid_norm_idx[:,1,:,:] & valid_norm_idx[:,2,:,:]
valid_angle_idx = valid_angle_idx.squeeze()
angle_EPE = torch.mean(norm_angle[valid_angle_idx])
loss = norm_EPE + flow2_EPE
elif self.net_name == 'dispnetcres':
output_net1, output_net2 = self.net(input_var)
output_net1 = scale_disp(output_net1, (output_net1.size()[0], 540, 960))
output_net2 = scale_disp(output_net2, (output_net2.size()[0], 540, 960))
loss_net1 = self.epe(output_net1, target_disp)
loss_net2 = self.epe(output_net2, target_disp)
loss = loss_net1 + loss_net2
flow2_EPE = self.epe(output_net2, target_disp)
elif self.net_name == 'dispnetcss':
output_net1, output_net2, output_net3 = self.net(input_var)
output_net1 = scale_disp(output_net1, (output_net1.size()[0], 540, 960))
output_net2 = scale_disp(output_net2, (output_net2.size()[0], 540, 960))
output_net3 = scale_disp(output_net3, (output_net3.size()[0], 540, 960))
loss_net1 = self.epe(output_net1, target_disp)
loss_net2 = self.epe(output_net2, target_disp)
loss_net3 = self.epe(output_net3, target_disp)
loss = loss_net1 + loss_net2 + loss_net3
flow2_EPE = self.epe(output_net3, target_disp)
else:
output = self.net(input_var)
output_net1 = output[0]
output_net1 = scale_disp(output_net1, (output_net1.size()[0], self.img_height, self.img_width))
loss = self.epe(output_net1, target_disp)
flow2_EPE = self.epe(output_net1, target_disp)
# record loss and EPE
if loss.data.item() == loss.data.item():
losses.update(loss.data.item(), input_var.size(0))
if self.disp_on and (flow2_EPE.data.item() == flow2_EPE.data.item()):
flow2_EPEs.update(flow2_EPE.data.item(), input_var.size(0))
if self.norm_on:
if self.angle_on:
if (angle_EPE.data.item() == angle_EPE.data.item()):
angle_EPEs.update(angle_EPE.data.item(), input_var.size(0))
else:
if (norm_EPE.data.item() == norm_EPE.data.item()):
norm_EPEs.update(norm_EPE.data.item(), input_var.size(0))
if (angle_EPE.data.item() == angle_EPE.data.item()):
angle_EPEs.update(angle_EPE.data.item(), input_var.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % 10 == 0:
logger.info('Test: [{0}/{1}]\t Time {2}\t EPE {3}\t norm_EPE {4}\t angle_EPE {5}'
.format(i, len(self.test_loader), batch_time.val, flow2_EPEs.val, norm_EPEs.val, angle_EPEs.val))
logger.info(' * EPE {:.3f}'.format(flow2_EPEs.avg))
logger.info(' * normal EPE {:.3f}'.format(norm_EPEs.avg))
logger.info(' * angle EPE {:.3f}'.format(angle_EPEs.avg))
return flow2_EPEs.avg
def get_model(self):
return self.net.state_dict()