forked from MRzzm/DINet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_DINet_frame.py
153 lines (139 loc) · 7.36 KB
/
train_DINet_frame.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
from models.Discriminator import Discriminator
from models.VGG19 import Vgg19
from models.DINet import DINet
from utils.training_utils import get_scheduler, update_learning_rate,GANLoss
from torch.utils.data import DataLoader
from dataset.dataset_DINet_frame import DINetDataset
from sync_batchnorm import convert_model
from config.config import DINetTrainingOptions
import random
import numpy as np
import os
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import cv2
if __name__ == "__main__":
'''
frame training code of DINet
we use coarse-to-fine training strategy
so you can use this code to train the model in arbitrary resolution
'''
# load config
opt = DINetTrainingOptions().parse_args()
writer = SummaryWriter('./logs/' + opt.result_path.split('/')[-1])
# set seed
random.seed(opt.seed)
np.random.seed(opt.seed)
torch.cuda.manual_seed(opt.seed)
# load training data in memory
train_data = DINetDataset(opt.train_data,opt.augment_num,opt.mouth_region_size)
training_data_loader = DataLoader(dataset=train_data, batch_size=opt.batch_size, shuffle=True,drop_last=True)
train_data_length = len(training_data_loader)
# init network
opt.audio_channel = 256
net_g = DINet(opt.source_channel,opt.ref_channel,opt.audio_channel).cuda()
net_dI = Discriminator(opt.source_channel ,opt.D_block_expansion, opt.D_num_blocks, opt.D_max_features).cuda()
net_vgg = Vgg19().cuda()
# parallel
net_g = nn.DataParallel(net_g)
net_g = convert_model(net_g)
net_dI = nn.DataParallel(net_dI)
net_vgg = nn.DataParallel(net_vgg)
# setup optimizer
optimizer_g = optim.Adam(net_g.parameters(), lr=opt.lr_g)
optimizer_dI = optim.Adam(net_dI.parameters(), lr=opt.lr_dI)
# coarse2fine
if opt.coarse2fine:
print('loading checkpoint for coarse2fine training: {}'.format(opt.coarse_model_path))
checkpoint = torch.load(opt.coarse_model_path)
net_g.load_state_dict(checkpoint['state_dict']['net_g'])
# set criterion
criterionGAN = GANLoss().cuda()
criterionL1 = nn.L1Loss().cuda()
# set scheduler
net_g_scheduler = get_scheduler(optimizer_g, opt.non_decay, opt.decay)
net_dI_scheduler = get_scheduler(optimizer_dI, opt.non_decay, opt.decay)
# start train
for epoch in range(opt.start_epoch, opt.non_decay+opt.decay+1):
net_g.train()
for iteration, data in enumerate(training_data_loader):
# read data
source_image_data,source_image_mask, reference_clip_data,deepspeech_feature = data
source_image_data = source_image_data.float().cuda()
source_image_mask = source_image_mask.float().cuda()
reference_clip_data = reference_clip_data.float().cuda()
deepspeech_feature = deepspeech_feature.float().cuda()
# network forward
fake_out = net_g(source_image_mask,reference_clip_data,deepspeech_feature)
# print("source_image_data.shape: ", source_image_data.shape) #[24, 3, 104, 80]
# print("fake_out.shape: ", fake_out.shape) # [24, 3, 104, 80]
# vis network output img
if iteration % 100 == 0:
fake_frame = fake_out[0, :, :, :].squeeze(0).permute(1, 2, 0).detach().cpu().numpy() * 255
real_frame = source_image_data[0, :, :, :].permute(1, 2, 0).detach().cpu().numpy() * 255
fake_img_name = "./vis_img/epoch" + str(epoch).zfill(4) + '_' + str(iteration).zfill(5) + '_fake.jpg'
real_img_name = "./vis_img/epoch" + str(epoch).zfill(4) + '_' + str(iteration).zfill(5) + '_real.jpg'
cv2.imwrite(fake_img_name, fake_frame[:, :, ::-1])
cv2.imwrite(real_img_name, real_frame[:, :, ::-1])
# down sample output image and real image
fake_out_half = F.avg_pool2d(fake_out, 3, 2, 1, count_include_pad=False)
target_tensor_half = F.interpolate(source_image_data, scale_factor=0.5, mode='bilinear')
# (1) Update D network
optimizer_dI.zero_grad()
# compute fake loss
_,pred_fake_dI = net_dI(fake_out)
loss_dI_fake = criterionGAN(pred_fake_dI, False)
# compute real loss
_,pred_real_dI = net_dI(source_image_data)
loss_dI_real = criterionGAN(pred_real_dI, True)
# Combined DI loss
loss_dI = (loss_dI_fake + loss_dI_real) * 0.5
loss_dI.backward(retain_graph=True)
optimizer_dI.step()
# (2) Update G network
_, pred_fake_dI = net_dI(fake_out)
optimizer_g.zero_grad()
# compute perception loss
perception_real = net_vgg(source_image_data)
perception_fake = net_vgg(fake_out)
perception_real_half = net_vgg(target_tensor_half)
perception_fake_half = net_vgg(fake_out_half)
loss_g_perception = 0
for i in range(len(perception_real)):
loss_g_perception += criterionL1(perception_fake[i], perception_real[i])
loss_g_perception += criterionL1(perception_fake_half[i], perception_real_half[i])
loss_g_perception = (loss_g_perception / (len(perception_real) * 2)) * opt.lamb_perception
# # gan dI loss
loss_g_dI = criterionGAN(pred_fake_dI, True)
# combine perception loss and gan loss
loss_g = loss_g_perception + loss_g_dI
loss_g.backward()
optimizer_g.step()
print(
"===> Epoch[{}]({}/{}): Loss_DI: {:.4f} Loss_GI: {:.4f} Loss_perception: {:.4f} lr_g = {:.7f} ".format(
epoch, iteration, len(training_data_loader), float(loss_dI), float(loss_g_dI), float(loss_g_perception),optimizer_g.param_groups[0]['lr']))
writer.add_scalar("Loss_DI", float(loss_dI), epoch*len(training_data_loader)+iteration)
writer.add_scalar("Loss_GI", float(loss_g_dI), epoch*len(training_data_loader)+iteration)
writer.add_scalar("Loss_perception", float(loss_g_perception), epoch*len(training_data_loader)+iteration)
writer.add_scalar("lr_g", float(optimizer_g.param_groups[0]['lr']), epoch*len(training_data_loader)+iteration)
update_learning_rate(net_g_scheduler, optimizer_g)
update_learning_rate(net_dI_scheduler, optimizer_dI)
writer.add_scalar("Loss_DI_epoch", float(loss_dI), epoch)
writer.add_scalar("Loss_GI_epoch", float(loss_g_dI), epoch)
writer.add_scalar("Loss_perception_epoch", float(loss_g_perception), epoch)
writer.add_scalar("lr_g_epoch", float(optimizer_g.param_groups[0]['lr']), epoch)
#checkpoint
if epoch % opt.checkpoint == 0:
if not os.path.exists(opt.result_path):
os.mkdir(opt.result_path)
model_out_path = os.path.join(opt.result_path, 'netG_model_epoch_{}.pth'.format(epoch))
states = {
'epoch': epoch + 1,
'state_dict': {'net_g': net_g.state_dict(), 'net_dI': net_dI.state_dict()},#
'optimizer': {'net_g': optimizer_g.state_dict(), 'net_dI': optimizer_dI.state_dict()}#
}
torch.save(states, model_out_path)
print("Checkpoint saved to {}".format(epoch))