-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
266 lines (210 loc) · 9.25 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
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
# modified from: https://github.com/yinboc/liif
import argparse
import os
import random
import numpy as np
import yaml
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import MultiStepLR
import datasets
import models
import utils
from test import eval_psnr
def make_data_loader(spec, tag=''):
if spec is None:
return None
dataset = datasets.make(spec['dataset'])
dataset = datasets.make(spec['wrapper'], args={'dataset': dataset})
log('{} dataset: size={}'.format(tag, len(dataset)))
for k, v in dataset[0].items():
log(' {}: shape={}'.format(k, tuple(v.shape)))
loader = DataLoader(dataset, batch_size=spec['batch_size'],
shuffle=(tag == 'train'), num_workers=8, pin_memory=True,collate_fn=dataset.collate_fn)
return loader
def make_data_loaders():
train_loader = make_data_loader(config.get('train_dataset'), tag='train')
val_loader = make_data_loader(config.get('val_dataset'), tag='val')
return train_loader, val_loader
def prepare_training():
# if config.get('resume') is not None:
if os.path.exists(config.get('resume')):
sv_file = torch.load(config['resume'])
model = models.make(sv_file['model'], load_sd=True).cuda()
optimizer = utils.make_optimizer(
model.parameters(), sv_file['optimizer'], load_sd=True)
epoch_start = sv_file['epoch'] + 1
if config.get('multi_step_lr') is None:
lr_scheduler = None
else:
lr_scheduler = MultiStepLR(optimizer, **config['multi_step_lr'])
for _ in range(epoch_start - 1):
lr_scheduler.step()
else:
model = models.make(config['model']).cuda()
optimizer = utils.make_optimizer(
model.parameters(), config['optimizer'])
epoch_start = 1
if config.get('multi_step_lr') is None:
lr_scheduler = None
else:
lr_scheduler = MultiStepLR(optimizer, **config['multi_step_lr'])
log('model: #params={}'.format(utils.compute_num_params(model, text=True)))
return model, optimizer, epoch_start, lr_scheduler
def train(train_loader, model, optimizer, \
epoch):
model.train()
loss_fn = nn.L1Loss()
train_loss = utils.Averager()
metric_fn = utils.calc_psnr
data_norm = config['data_norm']
t = data_norm['inp']
inp_sub = torch.FloatTensor(t['sub']).view(1, -1, 1, 1).cuda()
inp_div = torch.FloatTensor(t['div']).view(1, -1, 1, 1).cuda()
t = data_norm['gt']
gt_sub = torch.FloatTensor(t['sub']).view(1, 1, -1).cuda()
gt_div = torch.FloatTensor(t['div']).view(1, 1, -1).cuda()
num_dataset = 800 # DIV2K
iter_per_epoch = int(num_dataset / config.get('train_dataset')['batch_size'] \
* config.get('train_dataset')['dataset']['args']['repeat'])
iteration = 0
for batch in tqdm(train_loader, leave=False, desc='train'):
for k, v in batch.items():
batch[k] = v.cuda()
bs = batch['inp'].shape[0]
inp = (batch['inp'] - inp_sub) / inp_div
sample_coord = batch['sample_coord']
cell = batch['cell']
# curriculum learning
if epoch > 500:
bs = batch['inp_s8'].shape[0]
inp = (batch['inp_s8'] - inp_sub) / inp_div
sample_coord = batch['sample_coord_s8']
cell = batch['cell_s8']
elif epoch > 250:
bs = batch['inp_s6'].shape[0]
inp = (batch['inp_s6'] - inp_sub) / inp_div
sample_coord = batch['sample_coord_s6']
cell = batch['cell_s6']
pred = model(inp, sample_coord, cell)
sample_coord = sample_coord.unsqueeze(2)
gt = F.grid_sample((batch['gt'] - gt_sub) / gt_div, sample_coord.flip(-1), \
mode='nearest', align_corners=False).permute(0, 2, 3, 1)
gt = gt.reshape(bs, -1, 3)
if epoch > 500:
gt = F.grid_sample((batch['gt_s8'] - gt_sub) / gt_div, sample_coord.flip(-1), \
mode='nearest', align_corners=False).permute(0, 2, 3, 1)
gt = gt.reshape(bs, -1, 3)
elif epoch > 250:
gt = F.grid_sample((batch['gt_s6'] - gt_sub) / gt_div, sample_coord.flip(-1), \
mode='nearest', align_corners=False).permute(0, 2, 3, 1)
gt = gt.reshape(bs, -1, 3)
loss = loss_fn(pred, gt)
psnr = metric_fn(pred, gt)
# tensorboard
writer.add_scalars('loss', {'train': loss.item()}, (epoch-1)*iter_per_epoch + iteration)
writer.add_scalars('psnr', {'train': psnr}, (epoch-1)*iter_per_epoch + iteration)
iteration += 1
train_loss.add(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
pred = None; loss = None
return train_loss.item()
def main(config_, save_path):
global config, log, writer
config = config_
log, writer = utils.set_save_path(save_path, remove=False)
with open(os.path.join(save_path, 'config.yaml'), 'w') as f:
yaml.dump(config, f, sort_keys=False)
train_loader, val_loader = make_data_loaders()
if config.get('data_norm') is None:
config['data_norm'] = {
'inp': {'sub': [0], 'div': [1]},
'gt': {'sub': [0], 'div': [1]}
}
model, optimizer, epoch_start, lr_scheduler = prepare_training()
n_gpus = len(os.environ['CUDA_VISIBLE_DEVICES'].split(','))
if n_gpus > 1:
model = nn.parallel.DataParallel(model)
epoch_max = config['epoch_max']
epoch_val = config.get('epoch_val')
epoch_save = config.get('epoch_save')
max_val_v = -1e18
timer = utils.Timer()
for epoch in range(epoch_start, epoch_max + 1):
t_epoch_start = timer.t()
log_info = ['epoch {}/{}'.format(epoch, epoch_max)]
writer.add_scalar('lr', optimizer.param_groups[0]['lr'], epoch)
train_loss = train(train_loader, model, optimizer, \
epoch)
if lr_scheduler is not None:
lr_scheduler.step()
log_info.append('train: loss={:.4f}'.format(train_loss))
if n_gpus > 1:
model_ = model.module
else:
model_ = model
model_spec = config['model']
model_spec['sd'] = model_.state_dict()
optimizer_spec = config['optimizer']
optimizer_spec['sd'] = optimizer.state_dict()
sv_file = {
'model': model_spec,
'optimizer': optimizer_spec,
'epoch': epoch
}
torch.save(sv_file, os.path.join(save_path, 'epoch-last.pth'))
if (epoch_save is not None) and (epoch % epoch_save == 0):
torch.save(sv_file,
os.path.join(save_path, 'epoch-{}.pth'.format(epoch)))
if (epoch_val is not None) and (epoch % epoch_val == 0):
if n_gpus > 1 and (config.get('eval_bsize') is not None):
model_ = model.module
else:
model_ = model
val_res = eval_psnr(val_loader, model_,
data_norm=config['data_norm'],
eval_type=config.get('eval_type'),
eval_bsize=config.get('eval_bsize'))
log_info.append('val: psnr={:.4f}'.format(val_res))
if val_res > max_val_v:
max_val_v = val_res
torch.save(sv_file, os.path.join(save_path, 'epoch-best.pth'))
t = timer.t()
prog = (epoch - epoch_start + 1) / (epoch_max - epoch_start + 1)
t_epoch = utils.time_text(t - t_epoch_start)
t_elapsed, t_all = utils.time_text(t), utils.time_text(t / prog)
log_info.append('{} {}/{}'.format(t_epoch, t_elapsed, t_all))
log(', '.join(log_info))
writer.flush()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='/root/autodl-tmp/liwt/configs/train-div2k/train_edsr-baseline-liwt.yaml')
parser.add_argument('--name', default='_train_edsr-liwt')
parser.add_argument('--tag', default=None)
parser.add_argument('--gpu', default='0')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
def setup_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed) # sets the seed for cpu
torch.cuda.manual_seed(seed) # Sets the seed for the current GPU.
torch.cuda.manual_seed_all(seed) # Sets the seed for the all GPU.
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
setup_seed(2454) #2021
with open(args.config, 'r') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
print('config loaded.')
save_name = args.name
if save_name is None:
save_name = '_' + args.config.split('/')[-1][:-len('.yaml')]
if args.tag is not None:
save_name += '_' + args.tag
save_path = os.path.join('./save', save_name)
main(config, save_path)