-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine_pretrain.py
438 lines (334 loc) · 17.1 KB
/
engine_pretrain.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import math
import sys
from typing import Iterable
import torch
import torch.nn as nn
import util.misc as misc
import util.lr_sched as lr_sched
from loss import GANLoss
ls_gan_loss = GANLoss('lsgan', 1.0, 0.0)
L1_loss = nn.L1Loss()
def train_one_epoch(model: torch.nn.Module,
data_loader: Iterable, optimizer: torch.optim.Optimizer,
device: torch.device, epoch: int, loss_scaler,
log_writer=None,
args=None,
epoch_size=1):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]'.format(epoch)
print_freq = 20
accum_iter = args.accum_iter
optimizer.zero_grad()
if log_writer is not None:
print('log_dir: {}'.format(log_writer.log_dir))
data_loader_i = iter(data_loader)
for data_iter_step in metric_logger.log_every(range(epoch_size), print_freq, header):
(batch, _) = next(data_loader_i)
# we use a per iteration (instead of per epoch) lr scheduler
if isinstance(batch, tuple):
samples, visual_tokens = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = visual_tokens.to(device, non_blocking=True)
else: # hack for consistency
samples = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = samples
if data_iter_step % accum_iter == 0:
lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
with torch.cuda.amp.autocast():
loss_dict = model(samples, visual_tokens)[0]
loss = torch.stack([loss_dict[l] for l in loss_dict if 'unscaled' not in l]).sum()
loss_value = loss.item()
if not math.isfinite(loss_value):
print("Loss is {}, stopping training".format(loss_value))
sys.exit(1)
loss /= accum_iter
loss_scaler(loss, optimizer, parameters=model.parameters(),
update_grad=(data_iter_step + 1) % accum_iter == 0)
if (data_iter_step + 1) % accum_iter == 0:
optimizer.zero_grad()
torch.cuda.synchronize()
metric_logger.update(**{k: v.item() for k, v in loss_dict.items()})
lr = optimizer.param_groups[0]["lr"]
metric_logger.update(lr=lr)
loss_value_reduce = misc.all_reduce_mean(loss_value)
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
""" We use epoch_1000x as the x-axis in tensorboard.
This calibrates different curves when batch size changes.
"""
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
log_writer.add_scalar('train_loss', loss_value_reduce, epoch_1000x)
log_writer.add_scalar('lr', lr, epoch_1000x)
# gather the stats from all processes
metric_logger.synchronize_between_processes()
print("Averaged stats:", metric_logger)
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
def train_one_epoch_adversarial(model: torch.nn.Module, model_D: torch.nn.Module, model_F: torch.nn.Module,
data_loader: Iterable, optimizer: torch.optim.Optimizer, optimizer_D: torch.optim.Optimizer,
device: torch.device, epoch: int, loss_scaler, loss_scaler_D,
log_writer=None,
args=None,
epoch_size=1,
patch_size=16,
l_pix_w=0.1,
l_fea_w=1,
l_gan_w=5e-3):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]'.format(epoch)
print_freq = 20
accum_iter = args.accum_iter
optimizer.zero_grad()
optimizer_D.zero_grad()
if log_writer is not None:
print('log_dir: {}'.format(log_writer.log_dir))
data_loader_i = iter(data_loader)
for data_iter_step in metric_logger.log_every(range(epoch_size), print_freq, header):
(batch, _) = next(data_loader_i)
# we use a per iteration (instead of per epoch) lr scheduler
if isinstance(batch, tuple):
samples, visual_tokens = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = visual_tokens.to(device, non_blocking=True)
else: # hack for consistency
samples = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = samples
if data_iter_step % accum_iter == 0:
lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
with torch.cuda.amp.autocast():
loss_dict, pred, mask = model(samples, visual_tokens, mask_ratio=args.mask_ratio)
# G
for p in model_D.parameters():
p.requires_grad = False
# pix loss (in loss_dict)
loss_dict['pix_loss'] = l_pix_w * loss_dict['pix_loss']
# perceptual loss
input_img1 = visual_tokens[:, 0, :, :, :]
target_img1 = visual_tokens[:, 1, :, :, :]
input_img2 = visual_tokens[:, 2, :, :, :]
target_img2 = visual_tokens[:, 3, :, :, :]
input_img1_patch_num = input_img1.shape[2]//patch_size*input_img1.shape[3]//patch_size
target_img1_patch_num = target_img1.shape[2]//patch_size*target_img1.shape[3]//patch_size
input_img2_patch_num = input_img2.shape[2]//patch_size*input_img2.shape[3]//patch_size
pred_target_img1 = pred[:, input_img1_patch_num:input_img1_patch_num+target_img1_patch_num, :]
pred_target_img1 = model.module.unpatchify(pred_target_img1).float()
pred_target_img2 = pred[:, input_img1_patch_num+target_img1_patch_num+input_img2_patch_num:, :]
pred_target_img2 = model.module.unpatchify(pred_target_img2).float()
real_fea1 = model_F(target_img1).detach()
fake_fea1 = model_F(pred_target_img1)
l_g_fea1 = l_fea_w * L1_loss(real_fea1, fake_fea1)
real_fea2 = model_F(target_img2).detach()
fake_fea2 = model_F(pred_target_img2)
l_g_fea2 = l_fea_w * L1_loss(real_fea2, fake_fea2)
loss_dict['per_loss'] = l_g_fea1 + l_g_fea2
# adversarial loss G
pred_g_fake1 = model_D(pred_target_img1)
l_g_gan1 = l_gan_w * ls_gan_loss(pred_g_fake1, True)
pred_g_fake2 = model_D(pred_target_img2)
l_g_gan2 = l_gan_w * ls_gan_loss(pred_g_fake2, True)
loss_dict['gan_G'] = l_g_gan1 + l_g_gan2
loss = torch.stack([loss_dict[l] for l in loss_dict if 'unscaled' not in l]).sum()
loss_value = loss.item()
if not math.isfinite(loss_value):
print("Loss is {}, stopping training".format(loss_value))
sys.exit(1)
loss /= accum_iter
loss_scaler(loss, optimizer, parameters=model.parameters(),
update_grad=(data_iter_step + 1) % accum_iter == 0)
if (data_iter_step + 1) % accum_iter == 0:
optimizer.zero_grad()
# D
for p in model_D.parameters():
p.requires_grad = True
loss_D_dict = {}
l_d_total = 0
pred_d_real1 = model_D(target_img1)
pred_d_fake1 = model_D(pred_target_img1.detach()) # detach to avoid BP to G
l_d_real1 = ls_gan_loss(pred_d_real1, True)
l_d_fake1 = ls_gan_loss(pred_d_fake1, False)
l_d_total1 = l_d_real1 + l_d_fake1
pred_d_real2 = model_D(target_img2)
pred_d_fake2 = model_D(pred_target_img2.detach()) # detach to avoid BP to G
l_d_real2 = ls_gan_loss(pred_d_real2, True)
l_d_fake2 = ls_gan_loss(pred_d_fake2, False)
l_d_total2 = l_d_real2 + l_d_fake2
l_d_total = l_d_total1 + l_d_total2
loss_D_dict['gan_D'] = l_d_total
loss_D = torch.stack([loss_D_dict[l] for l in loss_D_dict if 'unscaled' not in l]).sum()
loss_value_D = loss_D.item()
if not math.isfinite(loss_value_D):
print("Loss is {}, stopping training".format(loss_value_D))
sys.exit(1)
loss_D /= accum_iter
loss_scaler_D(loss_D, optimizer_D, parameters=model_D.parameters(),
update_grad=(data_iter_step + 1) % accum_iter == 0)
if (data_iter_step + 1) % accum_iter == 0:
optimizer_D.zero_grad()
torch.cuda.synchronize()
metric_logger.update(**{k: v.item() for k, v in loss_dict.items()})
metric_logger.update(**{k: v.item() for k, v in loss_D_dict.items()})
lr = optimizer.param_groups[0]["lr"]
metric_logger.update(lr=lr)
loss_value_reduce = misc.all_reduce_mean(loss_value)
loss_value_reduce_D = misc.all_reduce_mean(loss_value_D)
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
""" We use epoch_1000x as the x-axis in tensorboard.
This calibrates different curves when batch size changes.
"""
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
log_writer.add_scalar('train_loss_G', loss_value_reduce, epoch_1000x)
log_writer.add_scalar('train_loss_D', loss_value_reduce_D, epoch_1000x)
log_writer.add_scalar('lr', lr, epoch_1000x)
# gather the stats from all processes
metric_logger.synchronize_between_processes()
print("Averaged stats:", metric_logger)
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
def train_one_epoch_adversarial_CNN_Head(model: torch.nn.Module, model_D: torch.nn.Module, model_F: torch.nn.Module,
data_loader: Iterable, optimizer: torch.optim.Optimizer, optimizer_D: torch.optim.Optimizer,
device: torch.device, epoch: int, loss_scaler, loss_scaler_D,
log_writer=None,
args=None,
epoch_size=1,
patch_size=16,
l_pix_w=0.1,
l_fea_w=1,
l_gan_w=5e-3,
lr_decay=True):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]'.format(epoch)
print_freq = 20
accum_iter = args.accum_iter
optimizer.zero_grad()
optimizer_D.zero_grad()
if log_writer is not None:
print('log_dir: {}'.format(log_writer.log_dir))
data_loader_i = iter(data_loader)
for data_iter_step in metric_logger.log_every(range(epoch_size), print_freq, header):
(batch, _) = next(data_loader_i)
# we use a per iteration (instead of per epoch) lr scheduler
if isinstance(batch, tuple):
samples, visual_tokens = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = visual_tokens.to(device, non_blocking=True)
else: # hack for consistency
samples = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = samples
if data_iter_step % accum_iter == 0:
if lr_decay:
lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
else:
pass
with torch.cuda.amp.autocast():
loss_dict, pred, mask, pred_target_img1, pred_target_img2 = model(samples, visual_tokens, mask_ratio=args.mask_ratio)
# G
for p in model_D.parameters():
p.requires_grad = False
# pix loss (in loss_dict)
loss_dict['pix_loss'] = l_pix_w * loss_dict['pix_loss']
# perceptual loss
input_img1 = visual_tokens[:, 0, :, :, :]
target_img1 = visual_tokens[:, 1, :, :, :]
input_img2 = visual_tokens[:, 2, :, :, :]
target_img2 = visual_tokens[:, 3, :, :, :]
pred_target_img1 = pred_target_img1.float()
pred_target_img2 = pred_target_img2.float()
real_fea1 = model_F(target_img1).detach()
fake_fea1 = model_F(pred_target_img1)
l_g_fea1 = l_fea_w * L1_loss(real_fea1, fake_fea1)
real_fea2 = model_F(target_img2).detach()
fake_fea2 = model_F(pred_target_img2)
l_g_fea2 = l_fea_w * L1_loss(real_fea2, fake_fea2)
loss_dict['per_loss'] = l_g_fea1 + l_g_fea2
# adversarial loss G
pred_g_fake1 = model_D(pred_target_img1)
l_g_gan1 = l_gan_w * ls_gan_loss(pred_g_fake1, True)
pred_g_fake2 = model_D(pred_target_img2)
l_g_gan2 = l_gan_w * ls_gan_loss(pred_g_fake2, True)
loss_dict['gan_G'] = l_g_gan1 + l_g_gan2
loss = torch.stack([loss_dict[l] for l in loss_dict if 'unscaled' not in l]).sum()
loss_value = loss.item()
if not math.isfinite(loss_value):
print("Loss is {}, stopping training".format(loss_value))
sys.exit(1)
loss /= accum_iter
loss_scaler(loss, optimizer, parameters=model.parameters(),
update_grad=(data_iter_step + 1) % accum_iter == 0)
if (data_iter_step + 1) % accum_iter == 0:
optimizer.zero_grad()
# D
for p in model_D.parameters():
p.requires_grad = True
loss_D_dict = {}
l_d_total = 0
pred_d_real1 = model_D(target_img1)
pred_d_fake1 = model_D(pred_target_img1.detach()) # detach to avoid BP to G
l_d_real1 = ls_gan_loss(pred_d_real1, True)
l_d_fake1 = ls_gan_loss(pred_d_fake1, False)
l_d_total1 = l_d_real1 + l_d_fake1
pred_d_real2 = model_D(target_img2)
pred_d_fake2 = model_D(pred_target_img2.detach()) # detach to avoid BP to G
l_d_real2 = ls_gan_loss(pred_d_real2, True)
l_d_fake2 = ls_gan_loss(pred_d_fake2, False)
l_d_total2 = l_d_real2 + l_d_fake2
l_d_total = l_d_total1 + l_d_total2
loss_D_dict['gan_D'] = l_d_total
loss_D = torch.stack([loss_D_dict[l] for l in loss_D_dict if 'unscaled' not in l]).sum()
loss_value_D = loss_D.item()
if not math.isfinite(loss_value_D):
print("Loss is {}, stopping training".format(loss_value_D))
sys.exit(1)
loss_D /= accum_iter
loss_scaler_D(loss_D, optimizer_D, parameters=model_D.parameters(),
update_grad=(data_iter_step + 1) % accum_iter == 0)
if (data_iter_step + 1) % accum_iter == 0:
optimizer_D.zero_grad()
torch.cuda.synchronize()
metric_logger.update(**{k: v.item() for k, v in loss_dict.items()})
metric_logger.update(**{k: v.item() for k, v in loss_D_dict.items()})
lr = optimizer.param_groups[0]["lr"]
metric_logger.update(lr=lr)
loss_value_reduce = misc.all_reduce_mean(loss_value)
loss_value_reduce_D = misc.all_reduce_mean(loss_value_D)
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
""" We use epoch_1000x as the x-axis in tensorboard.
This calibrates different curves when batch size changes.
"""
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
log_writer.add_scalar('train_loss_G', loss_value_reduce, epoch_1000x)
log_writer.add_scalar('train_loss_D', loss_value_reduce_D, epoch_1000x)
log_writer.add_scalar('lr', lr, epoch_1000x)
# gather the stats from all processes
metric_logger.synchronize_between_processes()
print("Averaged stats:", metric_logger)
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
@torch.no_grad()
def validate(model, data_loader, device, epoch, log_writer, args):
model.eval()
metric_logger = misc.MetricLogger(delimiter=" ")
header = 'Epoch: [{}]'.format(epoch)
print_freq = 50
if log_writer is not None:
print('log_dir: {}'.format(log_writer.log_dir))
for data_iter_step, (batch, _) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
samples, visual_tokens = batch
samples = samples.to(device, non_blocking=True)
visual_tokens = visual_tokens.to(device, non_blocking=True)
with torch.cuda.amp.autocast():
loss_dict, _, _ = model(samples, visual_tokens, mask_ratio=args.mask_ratio)
loss = torch.stack([loss_dict[l] for l in loss_dict if 'unscaled' not in l]).sum()
loss_value = loss.item()
if not math.isfinite(loss_value):
print("Loss is {}, stopping training".format(loss_value))
sys.exit(1)
metric_logger.update(**{k: v.item() for k, v in loss_dict.items()})
# gather the stats from all processes
metric_logger.synchronize_between_processes()
print("Averaged stats for val:", metric_logger)
return {'val_' + k: meter.global_avg for k, meter in metric_logger.meters.items()}