forked from chj1330/emotionalVC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
166 lines (128 loc) · 5.93 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
import argparse, os, glob, json
import numpy as np
import torch
import data_utils as util
from vawgan import *
# untuned hyperparam
LAMBDA_GP = 10
def main(architecture, corpus, save_dir='save', device=0, **kwargs):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
with open(architecture) as f:
arch = json.load(f)
# load data
src_files = sorted(glob.glob(arch['training']['src_dir']))
tgt_files = sorted(glob.glob(arch['training']['tgt_dir']))
normalizer = util.Tanhize(corpus)
batch_size = arch['training']['batch_size']
src_loader = util.load_concat(src_files, transform=normalizer,
batch_size=batch_size, shuffle=True, drop_last=True)
tgt_loader = util.load_concat(tgt_files, transform=normalizer,
batch_size=batch_size, shuffle=True, drop_last=True)
# load models
length = arch['hwc'][0]
z_dim, y_dim = arch['z_dim'], arch['y_dim']
archE = arch['encoder']
archG = arch['generator']
archD = arch['discriminator']
E = Encoder(length, z_dim,
archE['output'], archE['kernel'], archE['stride'])
G = Generator(length, z_dim, y_dim, archG['merge_dim'], archG['init_out'],
archG['output'], archG['kernel'], archG['stride'])
D = Discriminator(length, y_dim,
archD['output'], archD['kernel'], archD['stride'])
E.train()
G.train()
D.train()
# GPU?
if device >= 0:
E.cuda(device)
G.cuda(device)
D.cuda(device)
# optimizers
lr = arch['training']['lr']
optim_E = torch.optim.Adam(E.parameters(), lr, weight_decay=archE['l2-reg'])
optim_G = torch.optim.Adam(G.parameters(), lr, weight_decay=archG['l2-reg'])
optim_D = torch.optim.Adam(D.parameters(), lr, weight_decay=archD['l2-reg'])
## PRETRAIN VAE ##
num_iter = min(len(src_loader), len(tgt_loader))
epoch_vae = arch['training']['epoch_vae']
for epoch in range(epoch_vae):
recon_losses = np.zeros(num_iter)
kld_losses = np.zeros(num_iter)
for i, loads in enumerate(zip(src_loader, tgt_loader)):
s_x, s_cond = util.load_to_vars(loads[0], device)
t_x, t_cond = util.load_to_vars(loads[1], device)
# forward
s_xh, (s_mu, s_logv) = forward_VAE(E, G, s_x, s_cond)
t_xh, (t_mu, t_logv) = forward_VAE(E, G, t_x, t_cond)
recon = (recon_loss(s_x, s_xh) + recon_loss(t_x, t_xh)) / 2
kld = (kld_loss(s_mu, s_logv) + kld_loss(t_mu, t_logv)) / 2
# backward
optim_E.zero_grad()
optim_G.zero_grad()
(recon + kld).backward()
optim_E.step()
optim_G.step()
# stats
recon_losses[i] = recon.item()
kld_losses[i] = kld.item()
print('VAE: Epoch [{:3d}/{:3d}] recon= {:.3f} kld= {:.3f}'
.format(epoch+1, epoch_vae, np.mean(recon_losses), np.mean(kld_losses)))
# save VAE checkpoint
torch.save(E.state_dict(), os.path.join(save_dir, 'VAE_encoder.pth'))
torch.save(G.state_dict(), os.path.join(save_dir, 'VAE_generator.pth'))
print('Saved VAE to ' + save_dir + '\n')
## TRAIN VAWGAN ##
epoch_vawgan = arch['training']['epoch_vawgan']
n_unroll = arch['training']['n_unroll']
n_unroll_intense = arch['training']['n_unroll_intense']
gamma_wgan = arch['training']['gamma']
for epoch in range(epoch_vawgan):
recon_losses = np.zeros(num_iter)
kld_losses = np.zeros(num_iter)
wgan_losses = np.zeros(num_iter)
for i, loads in enumerate(zip(src_loader, tgt_loader)):
s_x, s_cond = util.load_to_vars(loads[0], device)
t_x, t_cond = util.load_to_vars(loads[1], device)
# train discriminator first
s2t_xh, _ = forward_VAE(E, G, s_x, t_cond)
wgan = wgan_loss(D, t_x, s2t_xh, t_cond)
grad_penalty = gradient_penalty(D, t_x, s2t_xh, t_cond)
optim_D.zero_grad()
(-wgan + LAMBDA_GP * grad_penalty).backward()
optim_D.step()
# train generator every n_unroll
if i > 0 and i % n_unroll == 0 or i == 0 and i % n_unroll_intense == 0:
s_xh, (s_mu, s_logv) = forward_VAE(E, G, s_x, s_cond)
t_xh, (t_mu, t_logv) = forward_VAE(E, G, t_x, t_cond)
s2t_xh, _ = forward_VAE(E, G, s_x, t_cond)
recon = (recon_loss(s_x, s_xh) + recon_loss(t_x, t_xh)) / 2
kld = (kld_loss(s_mu, s_logv) + kld_loss(t_mu, t_logv)) / 2
wgan = wgan_loss(D, t_x, s2t_xh, t_cond)
optim_E.zero_grad()
(recon + kld).backward(retain_graph=True)
optim_E.step()
optim_G.zero_grad()
(recon + gamma_wgan * wgan).backward()
optim_G.step()
# stats
recon_losses[i] = recon.item()
kld_losses[i] = kld.item()
wgan_losses[i] = wgan.item()
print('VAWGAN: Epoch [{:3d}/{:3d}] recon= {:.3f} kld= {:.3f} wgan= {:.3f}'
.format(epoch+1, epoch_vawgan, np.mean(recon_losses), np.mean(kld_losses),
np.mean(wgan_losses)))
# save VAWGAN
torch.save(E.state_dict(), os.path.join(save_dir, 'VAWGAN_encoder.pth'))
torch.save(G.state_dict(), os.path.join(save_dir, 'VAWGAN_generator.pth'))
torch.save(D.state_dict(), os.path.join(save_dir, 'VAWGAN_discriminator.pth'))
print('Saved VAWGAN to ' + save_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('architecture', type=str, help='json architecture file')
parser.add_argument('corpus', type=str, help='dataset name')
parser.add_argument('--save_dir', type=str, help='save directory')
parser.add_argument('--device', type=int, help='-1: cpu, 0+: gpu')
args = {k:v for k,v in vars(parser.parse_args()).items() if v is not None}
main(**args)