-
Notifications
You must be signed in to change notification settings - Fork 42
/
train.py
225 lines (169 loc) · 6.89 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
import os
from tqdm import tqdm
import torch
import data.common
from utils import interact, MultiSaver
import torch.cuda.amp as amp
class Trainer():
def __init__(self, args, model, criterion, optimizer, loaders):
print('===> Initializing trainer')
self.args = args
self.mode = 'train' # 'val', 'test'
self.epoch = args.start_epoch
self.save_dir = args.save_dir
self.model = model
self.criterion = criterion
self.optimizer = optimizer
self.loaders = loaders
self.do_train = args.do_train
self.do_validate = args.do_validate
self.do_test = args.do_test
self.device = args.device
self.dtype = args.dtype
self.dtype_eval = torch.float32 if args.precision == 'single' else torch.float16
if self.args.demo and self.args.demo_output_dir:
self.result_dir = self.args.demo_output_dir
else:
self.result_dir = os.path.join(self.save_dir, 'result')
os.makedirs(self.result_dir, exist_ok=True)
print('results are saved in {}'.format(self.result_dir))
self.imsaver = MultiSaver(self.result_dir)
self.is_slave = self.args.launched and self.args.rank != 0
self.scaler = amp.GradScaler(
init_scale=self.args.init_scale,
enabled=self.args.amp
)
def save(self, epoch=None):
epoch = self.epoch if epoch is None else epoch
if epoch % self.args.save_every == 0:
if self.mode == 'train':
self.model.save(epoch)
self.optimizer.save(epoch)
self.criterion.save()
return
def load(self, epoch=None, pretrained=None):
if epoch is None:
epoch = self.args.load_epoch
self.epoch = epoch
self.model.load(epoch, pretrained)
self.optimizer.load(epoch)
self.criterion.load(epoch)
return
def train(self, epoch):
self.mode = 'train'
self.epoch = epoch
self.model.train()
self.model.to(dtype=self.dtype)
self.criterion.train()
self.criterion.epoch = epoch
if not self.is_slave:
print('[Epoch {} / lr {:.2e}]'.format(
epoch, self.optimizer.get_lr()
))
if self.args.distributed:
self.loaders[self.mode].sampler.set_epoch(epoch)
if self.is_slave:
tq = self.loaders[self.mode]
else:
tq = tqdm(self.loaders[self.mode], ncols=80, smoothing=0, bar_format='{desc}|{bar}{r_bar}')
torch.set_grad_enabled(True)
for idx, batch in enumerate(tq):
self.optimizer.zero_grad()
input, target = data.common.to(
batch[0], batch[1], device=self.device, dtype=self.dtype)
with amp.autocast(self.args.amp):
output = self.model(input)
loss = self.criterion(output, target)
self.scaler.scale(loss).backward()
self.scaler.step(self.optimizer.G)
self.scaler.update()
if isinstance(tq, tqdm):
tq.set_description(self.criterion.get_loss_desc())
self.criterion.normalize()
if isinstance(tq, tqdm):
tq.set_description(self.criterion.get_loss_desc())
tq.display(pos=-1) # overwrite with synchronized loss
self.criterion.step()
self.optimizer.schedule(self.criterion.get_last_loss())
if self.args.rank == 0:
self.save(epoch)
return
def evaluate(self, epoch, mode='val'):
self.mode = mode
self.epoch = epoch
self.model.eval()
self.model.to(dtype=self.dtype_eval)
if mode == 'val':
self.criterion.validate()
elif mode == 'test':
self.criterion.test()
self.criterion.epoch = epoch
self.imsaver.join_background()
if self.is_slave:
tq = self.loaders[self.mode]
else:
tq = tqdm(self.loaders[self.mode], ncols=80, smoothing=0, bar_format='{desc}|{bar}{r_bar}')
compute_loss = True
torch.set_grad_enabled(False)
for idx, batch in enumerate(tq):
input, target = data.common.to(
batch[0], batch[1], device=self.device, dtype=self.dtype_eval)
with amp.autocast(self.args.amp):
output = self.model(input)
if mode == 'demo': # remove padded part
pad_width = batch[2]
output[0], _ = data.common.pad(output[0], pad_width=pad_width, negative=True)
if isinstance(batch[1], torch.BoolTensor):
compute_loss = False
if compute_loss:
self.criterion(output, target)
if isinstance(tq, tqdm):
tq.set_description(self.criterion.get_loss_desc())
if self.args.save_results != 'none':
if isinstance(output, (list, tuple)):
result = output[0] # select last output in a pyramid
elif isinstance(output, torch.Tensor):
result = output
names = batch[-1]
if self.args.save_results == 'part' and compute_loss: # save all when GT not available
indices = batch[-2]
save_ids = [save_id for save_id, idx in enumerate(indices) if idx % 10 == 0]
result = result[save_ids]
names = [names[save_id] for save_id in save_ids]
self.imsaver.save_image(result, names)
if compute_loss:
self.criterion.normalize()
if isinstance(tq, tqdm):
tq.set_description(self.criterion.get_loss_desc())
tq.display(pos=-1) # overwrite with synchronized loss
self.criterion.step()
if self.args.rank == 0:
self.save()
self.imsaver.end_background()
def validate(self, epoch):
self.evaluate(epoch, 'val')
return
def test(self, epoch):
self.evaluate(epoch, 'test')
return
def fill_evaluation(self, epoch, mode=None, force=False):
if epoch <= 0:
return
if mode is not None:
self.mode = mode
do_eval = force
if not force:
loss_missing = epoch not in self.criterion.loss_stat[self.mode]['Total'] # should it switch to all loss types?
metric_missing = False
for metric_type in self.criterion.metric:
if epoch not in self.criterion.metric_stat[mode][metric_type]:
metric_missing = True
do_eval = loss_missing or metric_missing
if do_eval:
try:
self.load(epoch)
self.evaluate(epoch, self.mode)
except:
# print('saved model/optimizer at epoch {} not found!'.format(epoch))
pass
return