-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
213 lines (173 loc) · 10.5 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
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
torch.autograd.set_detect_anomaly(True)
# from kitti.dataset import DataGenerator
from cadc.dataset import DataGenerator
import net
import utils
from evaluate import evaluate
def train(model, optimizer, dataloader, loss_fn, metric_fn, param, current_epoch):
model.train()
summary = []
for i, data in enumerate(dataloader):
img_batch = data['img']
depth_batch = data['depth']
# move to GPU if available
img_batch, depth_batch = img_batch.cuda(), depth_batch.cuda()
# compute model output
output_batch = model(img_batch)
# clear previous gradients, compute loss
optimizer.zero_grad()
loss = loss_fn(output_batch, depth_batch, param['mode'], img=img_batch)
loss.backward()
# performs updates using calculated gradients
optimizer.step()
if i % 10 == 0:
print('Train: epoch %d iter %d loss: %.3f' % (current_epoch, i, loss))
writer.add_scalar('training loss', loss, current_epoch * len(dataloader) + i)
output_batch, depth_batch = output_batch.cpu().detach().numpy(), depth_batch.cpu().detach().numpy()
pred_batch = net.depth_inference(output_batch, param['mode'])
metrics = metric_fn(pred_batch, depth_batch)
# for metric, value in metrics.items():
# print('Training epoch %d iter %d metric %s: %.3f' % (epoch, i, metric, value))
# writer.add_scalar(metric, value, epoch * len(dataloader) + i)
metrics['loss'] = loss.item()
summary.append(metrics)
if i % 100 == 0:
if param['mode'] in ['sord_ent_weighted', 'sord_weighted_minent']:
aux_map = net.local_entropy(depth_batch, kernel=16, mask=True)
elif param['mode'] == 'sord_min_local_ent':
aux_map = net.local_entropy(pred_batch, kernel=16)
elif param['mode'] == 'sord_align_grad':
aux_map = net.edge(pred_batch)
else:
aux_map = None
error_map = net.depth_error_map(pred_batch, depth_batch)
show_result_fig = utils.show_result(data, pred_batch, aux_map, error_map, param['batch_size'], shuffle=True)
writer.add_figure('Train Input_RGB Input_Depth Output_Depth_map', show_result_fig, current_epoch * len(dataloader) + i)
metrics_train = {metric: np.mean([x[metric] for x in summary]) for metric in summary[0]}
print('\n------ After training %d epochs, train set metrics mean: ------ \n%s\n' % (current_epoch, metrics_train))
def train_evaluate(model, optimizer, scheduler, dataloader_train, dataloader_val, loss_fn, metric_fn, model_dir, param):
best_SILog_val = float('inf')
epoch_start = param['current_epoch']
for epoch in range(epoch_start, param['epochs']):
print()
print('------ Epoch %d, Learning rate = %.2e ------' % (epoch, optimizer.param_groups[0]['lr']))
train(model, optimizer, dataloader_train, loss_fn, metric_fn, param, epoch)
# metrics_test = evaluate(model, dataloader_val, loss_fn, metric_fn, param, epoch, writer)
if isinstance(dataloader_val, dict):
metrics_val_current = evaluate(model, dataloader_val['current'], loss_fn, metric_fn, param, epoch, writer)
metrics_val_current = {k + '_val_current': v for k, v in metrics_val_current.items()}
print(
'\n------ After training %d epochs, current snowfall\'s validation set metrics mean: ------ \n%s\n' % (epoch, metrics_val_current))
for metric, value in metrics_val_current.items():
writer.add_scalar(metric, value, epoch)
metrics_val_all = evaluate(model, dataloader_val['all'], loss_fn, metric_fn, param, epoch, writer)
metrics_val_all = {k + '_val_all': v for k, v in metrics_val_all.items()}
print(
'\n------ After training %d epochs, all CADC validation set metrics mean: ------ \n%s\n' % (epoch, metrics_val_all))
for metric, value in metrics_val_all.items():
writer.add_scalar(metric, value, epoch)
metrics_val = {**metrics_val_current, **metrics_val_all}
SILog_val = metrics_val_current['SILog_val_current']
else:
metrics_val = evaluate(model, dataloader_val, loss_fn, metric_fn, param, epoch, writer)
print(
'\n------ After training %d epochs, validation set metrics mean: ------ \n%s\n' % (epoch, metrics_val))
for metric, value in metrics_val.items():
writer.add_scalar(metric, value, epoch)
SILog_val = metrics_val['SILog']
if scheduler is not None:
scheduler.step(SILog_val)
is_best = SILog_val <= best_SILog_val
# Save weights
save_dict = param.copy()
save_dict['current_epoch'] = epoch
save_dict['state_dict'] = model.state_dict()
save_dict['optim_dict'] = optimizer.state_dict()
if scheduler is not None:
save_dict['sched_dict'] = scheduler.state_dict()
experiments_dir = 'experiments/' + model_dir
utils.save_checkpoint(save_dict, is_best=is_best, folder_path=experiments_dir)
# If best_eval, best_save_path
if is_best:
best_SILog_val = SILog_val
# Save best val metrics in a json file in the model directory
best_json_path = os.path.join(experiments_dir, "metrics_test_best_weights.json")
utils.save_dict_to_json(metrics_val, best_json_path)
# Save latest val metrics in a json file in the model directory
last_json_path = os.path.join(experiments_dir, "metrics_test_last_weights.json")
utils.save_dict_to_json(metrics_val, last_json_path)
if __name__ == '__main__':
param = {
'phase': 'train',
'batch_size': 3,
'eval_n_crop': 4,
'learning_rate': 1e-3,
'momentum': 0.9,
'weight_decay': 0,
'epochs': 40,
'mode': 'sord_ent_weighted' # sord, sord_ent_weighted, sord_min_local_ent, sord_weighted_minent, sord_align_grad, classification, regression, reg_of_cls
}
restore_file = "experiments/train_lr_1e-03_momentum_0.9_wd_0_epoch_30_mode_sord_pretrained_DeepLabV3+_PascalVOC_crop_375*513/best.pth.tar"
model_dir = 'refine_CADC_depth_aggregated_new_sord_weighted_sigmoid_16x16_lr_1e-03_momentum_0.9_wd_0_epoch_30_mode_sord_pretrained_DeepLabV3+_Kitti_crop_513*513'
train_type = 'refine' # refine or continue
model = net.get_model(param['mode'])
model.cuda()
## Pretrained on Pascal semantic segmentation, retrain on Kitti depth estimation
# last_layer = ['classifier.classifier.4.weight', 'classifier.classifier.4.bias']
# last_layer_params = list(map(lambda x: x[1], list(filter(lambda kv: kv[0] in last_layer, model.named_parameters()))))
# base_params = list(map(lambda x: x[1], list(filter(lambda kv: kv[0] not in last_layer, model.named_parameters()))))
#
# optimizer = torch.optim.SGD([
# {'params': base_params, 'lr': param['learning_rate']},
# {'params': last_layer_params, 'lr': param['learning_rate'] * 10}
# ], momentum=param['momentum'], weight_decay=param['weight_decay'], nesterov=True)
# scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=1)
optimizer = torch.optim.SGD(params=model.parameters(), lr=param['learning_rate'], momentum=param['momentum'], weight_decay=param['weight_decay'], nesterov=True)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=2)
if restore_file is not None:
if train_type == 'refine':
load_dict = utils.load_checkpoint(restore_file, model, optimizer=None, scheduler=None)
param['current_epoch'] = 0
elif train_type == 'continue':
load_dict = utils.load_checkpoint(restore_file, model, optimizer=optimizer, scheduler=scheduler)
assert 'current_epoch' in load_dict, "current_epoch does not exist in restore file"
param['current_epoch'] = load_dict['current_epoch']+1
# if load model of "sord_ent_weighted" before 08/11, need to manually set model to "sord_ent_weighted"
# param['mode'] = 'sord_ent_weighted'
if param['mode'] == 'reg_of_cls':
utils.freeze_classification(model)
if model_dir is None:
if restore_file is not None:
model_dir = restore_file.split('/')[1].strip()
else:
model_dir = '%s_lr_%.2e_wd_%.2e_epoch_%d_mode_%s' % (param['phase'], param['learning_rate'], param['weight_decay'], param['epochs'], param['mode'])
writer = SummaryWriter('runs/' + model_dir)
# data_gen_train = DataGenerator('/home/datasets/Kitti/', phase=param['phase'])
data_gen_train = DataGenerator('/home/datasets/CADC/cadcd/', '/home/datasets_mod/CADC/cadcd/',
phase='train', cam=0, depth_mode='aggregated')
print('train data size:', len(data_gen_train.dataset))
dataloader_train = data_gen_train.create_data(batch_size=param['batch_size'])
data = next(iter(dataloader_train))
print('img shape:', data['img'].shape)
print('depth shape:', data['depth'].shape)
# data_gen_val = DataGenerator('/home/datasets/Kitti/', phase='test')
data_gen_val = DataGenerator('/home/datasets/CADC/cadcd/', '/home/datasets_mod/CADC/cadcd/',
phase='val', cam=0, depth_mode='aggregated')
print('val data size:', len(data_gen_val.dataset))
dataloader_val = data_gen_val.create_data(batch_size=param['batch_size'])
# # Eval on both current corresponding snowfall val set & all CADC val set
# data_gen_val_current = DataGenerator('/home/datasets/CADC/cadcd/', '/home/datasets_mod/CADC/cadcd/', phase='val', dror=True, cam=0, snow_level='light')
# print('current snowfall\'s val data size:', len(data_gen_val_current.dataset))
# dataloader_val_current = data_gen_val_current.create_data(batch_size=param['batch_size'])
#
# data_gen_val_all = DataGenerator('/home/datasets/CADC/cadcd/', '/home/datasets_mod/CADC/cadcd/', phase='val', dror=True, cam=0, snow_level=None)
# print('all CADC val data size:', len(data_gen_val_all.dataset))
# dataloader_val_all = data_gen_val_all.create_data(batch_size=param['batch_size'])
#
# dataloader_val = {'current': dataloader_val_current, 'all': dataloader_val_all}
train_evaluate(model, optimizer, scheduler, dataloader_train, dataloader_val, net.loss_fn, net.metric_fn, model_dir, param)