-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrainer.py
More file actions
329 lines (248 loc) · 11.9 KB
/
trainer.py
File metadata and controls
329 lines (248 loc) · 11.9 KB
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
import shutil
import gc
import os
import numpy as np
import torch
from tqdm import tqdm
from pathlib import Path
from util.stream_helper_SPS import SPSHelper
from loguru import logger
class Trainer():
def __init__(self, args, model, train_cfg, current_epoch, save_root, device, epoch_ratio=1):
super(Trainer, self).__init__()
assert current_epoch > 0
self.args = args
self.model = model
self.train_cfg = train_cfg
if train_cfg is not None:
self.phase = {}
for k, v in sorted({v: k for k, v in train_cfg['phase'].items()}.items()):
self.phase[k] = v
self.end_epoch = max(self.phase.keys())
if hasattr(self.args, "end_epoch") and self.args.end_epoch is not None:
self.end_epoch = self.args.end_epoch
self.current_epoch = current_epoch
self.current_phase = None
self.save_root = save_root
self.num_device = 1 if device == 'cpu' else args.gpus
self.epoch_ratio = epoch_ratio
self.device = device
def get_phase(self, epoch):
for k in self.phase.keys():
if epoch <= k:
return self.phase[k]
def get_prev_phase(self, epoch):
previous = None
current = None
for k in self.phase.keys():
previous = current
current = self.phase[k]
if epoch <= k:
return previous
def save_checkpoint(self, state, is_best):
torch.save(state, self.save_root + f'/epoch={self.current_epoch}.pth.tar')
if is_best:
shutil.copyfile(self.save_root + f'/epoch={self.current_epoch}.pth.tar',
self.save_root + f'/checkpoint_best_loss.pth.tar')
def fit(self):
if not self.args.no_sanity:
self.before_train()
start = self.current_epoch
best_loss = float("inf")
print("Remember to change the frozen modules function !!!")
for epoch in range(start, self.end_epoch + 1):
phase = self.get_phase(epoch)
if phase != self.current_phase:
kwargs = {
"stage": "fit",
"max_num_Pframe": self.train_cfg[phase]['max_num_Pframe'] if 'max_num_Pframe' in self.train_cfg[phase].keys() else 6,
"epoch_ratio": self.train_cfg[phase]['train_len'] if 'train_len' in self.train_cfg[phase].keys() else 1
}
if self.epoch_ratio != 1:
kwargs.update({"epoch_ratio": self.epoch_ratio})
self.model.setup(**kwargs)
# setup train dataloader
self.train_loader = self.model.train_dataloader(self.train_cfg[phase]['batch_size'] * self.num_device)
# setup val dataloader
self.val_loader = self.model.val_dataloader(self.num_device)
# re-calculate the milestones of lr_scheduler
milestones = np.array(self.train_cfg[phase]['lr_scheduler']['milestones'])
previous_phase = self.get_prev_phase(epoch)
if previous_phase is None:
diff = self.current_epoch
else:
diff = self.current_epoch - self.train_cfg['phase'][previous_phase]
milestones = milestones - diff
done = len(milestones[milestones <= 0])
milestones = list(milestones[milestones>0])
lr = self.train_cfg[phase]['lr'] * self.train_cfg[phase]['lr_scheduler']['gamma']**done
# setup optimizer
self.model.configure_optimizers(lr,
include_module_name=self.train_cfg[phase]['include_module_name'] if 'include_module_name' in self.train_cfg[phase] else None,
exclude_module_name=self.train_cfg[phase]['exclude_module_name'] if 'exclude_module_name' in self.train_cfg[phase] else None)
# setup lr_scheduler
if len(self.train_cfg[phase]['lr_scheduler']['milestones']) != 0:
lr_scheduler = self.model.configure_lr_scheduler(milestones, self.train_cfg[phase]['lr_scheduler']['gamma'])
else:
lr_scheduler = None
self.current_phase = phase
print(f'Start {self.current_phase} phase. Batch size={self.train_cfg[phase]["batch_size"]}\n lr: {lr}, milestones: {milestones}, frozen_modules: {self.train_cfg[phase]["frozen_modules"]}')
self.current_epoch = epoch
self.model.train()
# setup train progressbar
data_len = len(self.train_loader)
progressbar = tqdm(self.train_loader, total=data_len)
progressbar.set_description(f'epoch {epoch}')
for i, batch in enumerate(progressbar, start=1):
self.model.optimizer.zero_grad()
loss, logs = self.model.training_step(batch, phase)
# skip nan loss
if loss > 10000 or torch.any(torch.isnan(loss)):
logger.warning(f"Skip this step: loss={loss.item()}")
gc.collect()
torch.cuda.empty_cache()
del batch, loss, logs
continue
if loss != 0:
loss.backward()
self.model.optimizer_step()
self.model.training_step_end(logs, epoch, (epoch - 1) * data_len + i)
update_txt=f'Loss: {loss.item():.3f}'
progressbar.set_postfix_str(update_txt, refresh=True)
del batch, loss, logs
if lr_scheduler is not None:
lr_scheduler.step()
gc.collect()
torch.cuda.empty_cache()
self.model.eval()
outputs = []
val_loss = []
# setup validation progressbar
progressbar = tqdm(self.val_loader, total=len(self.val_loader), leave=True)
progressbar.set_description(f'epoch {epoch}')
gc.collect()
torch.cuda.empty_cache()
for batch in progressbar:
logs = self.model.validation_step(batch, epoch)
outputs.append(logs)
val_loss.append(np.mean(logs['val/loss']))
update_txt=f'[Validation Loss: {np.mean(logs["val/loss"]):.3f}]'
progressbar.set_postfix_str(update_txt, refresh=True)
del batch
gc.collect()
torch.cuda.empty_cache()
self.model.validation_epoch_end(outputs, epoch)
del outputs
gc.collect()
torch.cuda.empty_cache()
val_loss = np.mean(val_loss)
is_best = val_loss < best_loss
best_loss = min(val_loss, best_loss)
self.save_checkpoint(
{
"epoch": epoch,
"state_dict": self.model.state_dict(),
"loss": val_loss,
"optimizer": self.model.optimizer.state_dict(),
},
is_best
)
def test(self):
torch.backends.cudnn.enabled = True
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
torch.set_num_threads(1)
self.model.setup('test')
test_loader = self.model.test_dataloader()
self.model.eval()
outputs = []
for batch in tqdm(test_loader):
logs = self.model.test_step(batch)
outputs.append(logs)
del batch
gc.collect()
torch.cuda.empty_cache()
self.model.test_epoch_end(outputs)
def compress(self):
torch.backends.cudnn.enabled = True
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
torch.set_num_threads(1)
self.model.setup('test')
test_loader = self.model.test_dataloader()
os.makedirs(os.path.join(self.args.save_dir, 'bin'), exist_ok=True)
self.model.bin_path = os.path.join(self.args.save_dir, 'bin', f'{self.args.test_seqs[0]}_{self.args.color_transform}.bin')
bitstream_path = Path(self.model.bin_path)
self.model.output_file = bitstream_path.open("wb")
self.model.sps_helper = SPSHelper()
self.model.bits = []
if self.args.YUV_FILE:
os.makedirs(os.path.join(self.args.save_dir, 'yuv'), exist_ok=True)
self.model.yuv_path = os.path.join(self.args.save_dir, 'yuv', f"{self.args.test_seqs[0]}_{self.args.color_transform}.yuv")
self.model.yuv_file = open(self.model.yuv_path, "wb")
self.model.eval()
outputs = []
first = True
for batch in tqdm(test_loader):
logs = self.model.compress_step(batch, first)
outputs.append(logs)
first = False
self.model.output_file.close()
if self.args.YUV_FILE:
self.model.yuv_file.close()
rate_bin = os.path.getsize(self.model.bin_path) / self.model.shape[0] / self.model.shape[1] * 8 / self.model.num_frames
for i in range(len(outputs)):
outputs[i]['metrics']['rate_bin'] = rate_bin
self.model.test_epoch_end(outputs)
def decompress(self):
torch.backends.cudnn.enabled = True
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
torch.set_num_threads(1)
self.model.setup('test')
test_loader = self.model.test_dataloader()
self.model.bin_path = os.path.join(self.args.save_dir, 'bin', f'{self.args.test_seqs[0]}_{self.args.color_transform}.bin')
bitstream_path = Path(self.model.bin_path)
self.model.input_file = bitstream_path.open("rb")
self.model.sps_helper = SPSHelper()
if self.args.YUV_FILE:
os.makedirs(os.path.join(self.args.save_dir, 'yuv_recon'), exist_ok=True)
self.model.yuv_path = os.path.join(self.args.save_dir, 'yuv_recon', f"{self.args.test_seqs[0]}_{self.args.color_transform}.yuv")
self.model.yuv_file = open(self.model.yuv_path, "wb")
self.model.eval()
outputs = []
first = True
self.model.gop_count = 0
for batch in tqdm(test_loader):
logs = self.model.decompress_step(batch, first)
outputs.append(logs)
first = False
self.model.gop_count += 1
self.model.input_file.close()
if self.args.YUV_FILE:
self.model.yuv_file.close()
rate_bin = os.path.getsize(self.model.bin_path) / self.model.shape[0] / self.model.shape[1] * 8 / self.model.num_frames
for i in range(len(outputs)):
outputs[i]['metrics']['rate_bin'] = rate_bin
self.model.test_epoch_end(outputs)
def before_train(self):
self.model.setup('fit')
self.val_loader = self.model.val_dataloader(self.num_device)
self.model.eval()
outputs = []
val_loss = []
progressbar = tqdm(self.val_loader, total=len(self.val_loader), leave=True)
progressbar.set_description(f'epoch {self.current_epoch - 1}')
for batch in progressbar:
logs = self.model.validation_step(batch, (self.current_epoch - 1))
outputs.append(logs)
val_loss.append(np.mean(logs["val/loss"]))
update_txt=f'[Validation Loss: {np.mean(logs["val/loss"]):.3f}]'
progressbar.set_postfix_str(update_txt, refresh=True)
del batch
gc.collect()
torch.cuda.empty_cache()
self.model.validation_epoch_end(outputs, (self.current_epoch - 1))