-
Notifications
You must be signed in to change notification settings - Fork 16
/
train.py
200 lines (150 loc) · 6.81 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
# coding: utf-8
import argparse
import os
import datetime
from tqdm import tqdm
import torch
from torch import nn
from torch import optim
from torch.backends import cudnn
from torch.utils.data import DataLoader
from model import DM2FNet
from tools.config import TRAIN_ITS_ROOT, TEST_SOTS_ROOT
from datasets import ItsDataset, SotsDataset
from tools.utils import AvgMeter, check_mkdir
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
def parse_args():
parser = argparse.ArgumentParser(description='Train a DM2FNet')
parser.add_argument(
'--gpus', type=str, default='0', help='gpus to use ')
parser.add_argument('--ckpt-path', default='./ckpt', help='checkpoint path')
parser.add_argument(
'--exp-name',
default='RESIDE_ITS',
help='experiment name.')
args = parser.parse_args()
return args
cfgs = {
'use_physical': True,
'iter_num': 40000,
'train_batch_size': 16,
'last_iter': 0,
'lr': 5e-4,
'lr_decay': 0.9,
'weight_decay': 0,
'momentum': 0.9,
'snapshot': '',
'val_freq': 5000,
'crop_size': 256
}
def main():
net = DM2FNet().cuda().train()
# net = nn.DataParallel(net)
optimizer = optim.Adam([
{'params': [param for name, param in net.named_parameters()
if name[-4:] == 'bias' and param.requires_grad],
'lr': 2 * cfgs['lr']},
{'params': [param for name, param in net.named_parameters()
if name[-4:] != 'bias' and param.requires_grad],
'lr': cfgs['lr'], 'weight_decay': cfgs['weight_decay']}
])
if len(cfgs['snapshot']) > 0:
print('training resumes from \'%s\'' % cfgs['snapshot'])
net.load_state_dict(torch.load(os.path.join(args.ckpt_path,
args.exp_name, cfgs['snapshot'] + '.pth')))
optimizer.load_state_dict(torch.load(os.path.join(args.ckpt_path,
args.exp_name, cfgs['snapshot'] + '_optim.pth')))
optimizer.param_groups[0]['lr'] = 2 * cfgs['lr']
optimizer.param_groups[1]['lr'] = cfgs['lr']
check_mkdir(args.ckpt_path)
check_mkdir(os.path.join(args.ckpt_path, args.exp_name))
open(log_path, 'w').write(str(cfgs) + '\n\n')
train(net, optimizer)
def train(net, optimizer):
curr_iter = cfgs['last_iter']
while curr_iter <= cfgs['iter_num']:
train_loss_record = AvgMeter()
loss_x_jf_record, loss_x_j0_record = AvgMeter(), AvgMeter()
loss_x_j1_record, loss_x_j2_record = AvgMeter(), AvgMeter()
loss_x_j3_record, loss_x_j4_record = AvgMeter(), AvgMeter()
loss_t_record, loss_a_record = AvgMeter(), AvgMeter()
for data in train_loader:
optimizer.param_groups[0]['lr'] = 2 * cfgs['lr'] * (1 - float(curr_iter) / cfgs['iter_num']) \
** cfgs['lr_decay']
optimizer.param_groups[1]['lr'] = cfgs['lr'] * (1 - float(curr_iter) / cfgs['iter_num']) \
** cfgs['lr_decay']
haze, gt_trans_map, gt_ato, gt, _ = data
batch_size = haze.size(0)
haze = haze.cuda()
gt_trans_map = gt_trans_map.cuda()
gt_ato = gt_ato.cuda()
gt = gt.cuda()
optimizer.zero_grad()
x_jf, x_j0, x_j1, x_j2, x_j3, x_j4, t, a = net(haze)
loss_x_jf = criterion(x_jf, gt)
loss_x_j0 = criterion(x_j0, gt)
loss_x_j1 = criterion(x_j1, gt)
loss_x_j2 = criterion(x_j2, gt)
loss_x_j3 = criterion(x_j3, gt)
loss_x_j4 = criterion(x_j4, gt)
loss_t = criterion(t, gt_trans_map)
loss_a = criterion(a, gt_ato)
loss = loss_x_jf + loss_x_j0 + loss_x_j1 + loss_x_j2 + loss_x_j3 + loss_x_j4 \
+ 10 * loss_t + loss_a
loss.backward()
optimizer.step()
# update recorder
train_loss_record.update(loss.item(), batch_size)
loss_x_jf_record.update(loss_x_jf.item(), batch_size)
loss_x_j0_record.update(loss_x_j0.item(), batch_size)
loss_x_j1_record.update(loss_x_j1.item(), batch_size)
loss_x_j2_record.update(loss_x_j2.item(), batch_size)
loss_x_j3_record.update(loss_x_j3.item(), batch_size)
loss_x_j4_record.update(loss_x_j4.item(), batch_size)
loss_t_record.update(loss_t.item(), batch_size)
loss_a_record.update(loss_a.item(), batch_size)
curr_iter += 1
log = '[iter %d], [train loss %.5f], [loss_x_fusion %.5f], [loss_x_phy %.5f], [loss_x_j1 %.5f], ' \
'[loss_x_j2 %.5f], [loss_x_j3 %.5f], [loss_x_j4 %.5f], [loss_t %.5f], [loss_a %.5f], ' \
'[lr %.13f]' % \
(curr_iter, train_loss_record.avg, loss_x_jf_record.avg, loss_x_j0_record.avg,
loss_x_j1_record.avg, loss_x_j2_record.avg, loss_x_j3_record.avg, loss_x_j4_record.avg,
loss_t_record.avg, loss_a_record.avg, optimizer.param_groups[1]['lr'])
print(log)
open(log_path, 'a').write(log + '\n')
if (curr_iter + 1) % cfgs['val_freq'] == 0:
validate(net, curr_iter, optimizer)
if curr_iter > cfgs['iter_num']:
break
def validate(net, curr_iter, optimizer):
print('validating...')
net.eval()
loss_record = AvgMeter()
with torch.no_grad():
for data in tqdm(val_loader):
haze, gt, _ = data
haze = haze.cuda()
gt = gt.cuda()
dehaze = net(haze)
loss = criterion(dehaze, gt)
loss_record.update(loss.item(), haze.size(0))
snapshot_name = 'iter_%d_loss_%.5f_lr_%.6f' % (curr_iter + 1, loss_record.avg, optimizer.param_groups[1]['lr'])
print('[validate]: [iter %d], [loss %.5f]' % (curr_iter + 1, loss_record.avg))
torch.save(net.state_dict(),
os.path.join(args.ckpt_path, args.exp_name, snapshot_name + '.pth'))
torch.save(optimizer.state_dict(),
os.path.join(args.ckpt_path, args.exp_name, snapshot_name + '_optim.pth'))
net.train()
if __name__ == '__main__':
args = parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus
cudnn.benchmark = True
torch.cuda.set_device(int(args.gpus))
train_dataset = ItsDataset(TRAIN_ITS_ROOT, True, cfgs['crop_size'])
train_loader = DataLoader(train_dataset, batch_size=cfgs['train_batch_size'], num_workers=4,
shuffle=True, drop_last=True)
val_dataset = SotsDataset(TEST_SOTS_ROOT)
val_loader = DataLoader(val_dataset, batch_size=8)
criterion = nn.L1Loss().cuda()
log_path = os.path.join(args.ckpt_path, args.exp_name, str(datetime.datetime.now()) + '.txt')
main()