-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsolver.py
128 lines (92 loc) · 4.18 KB
/
solver.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
import torch
from torch import nn
from tqdm import tqdm
from model.discriminator import Discriminator
from model.generator import Generator
class Solver():
def __init__(self, train_loader, test_loader, config):
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.train_loader = train_loader
self.test_loader = test_loader
# epoch
self.epoch = 1
# networks
self.gen = Generator(embed_dim=256).to(self.device)
self.dis = Discriminator(embed_dim=256).to(self.device)
# gen frequency
self.gen_freq = config['gen_freq']
# train optimizers
self.gen_lr = config['optimizers']['gen_lr']
self.dis_lr = config['optimizers']['dis_lr']
self.beta1 = config['optimizers']['beta1']
self.beta2 = config['optimizers']['beta2']
self.gen_opt = torch.optim.Adam(self.gen.parameters(), self.gen_lr, [self.beta1, self.beta2])
self.dis_opt = torch.optim.Adam(self.dis.parameters(), self.dis_lr, [self.beta1, self.beta2])
# hyperparams
self.hparam = config['hparam']
# epoch save
self.epoch_save = config['epoch_save']
# load checkpoint
if config['resume'] != '':
checkpoint = torch.load(config['resume'])
self.epoch = checkpoint['epoch'] + 1
self.gen.load_state_dict(checkpoint['gen'])
self.dis.load_state_dict(checkpoint['dis'])
# losses
self.l1_loss = nn.L1Loss()
self.l2_loss = nn.MSELoss()
def reset_grad(self):
self.dis_opt.zero_grad()
self.gen_opt.zero_grad()
def train_step(self, idx, x_src, src, trg):
x_src = x_src.to(self.device)
src = src.unsqueeze(0).to(self.device)
trg = trg.unsqueeze(0).to(self.device)
# inference
x_src_src = self.gen(x_src, src, src)
x_src_trg = self.gen(x_src, src, trg)
x_src_trg_src = self.gen(x_src_trg, trg, src)
d_src = self.dis(x_src, src, trg)
d_src_trg = self.dis(x_src_trg, trg, src)
# Train discriminator
dis_loss = torch.mean((d_src_trg - self.hparam['b']) ** 2 + (d_src - self.hparam['a']) ** 2)
self.reset_grad()
dis_loss.backward(retain_graph=True)
self.dis_opt.step()
# Train generator
if idx % self.gen_freq == 0:
id_loss = self.l2_loss(x_src, x_src_src)
cyc_loss = self.l1_loss(x_src, x_src_trg_src)
d_src_trg_2 = self.dis(x_src_trg, trg, src)
adv_loss = torch.mean((d_src_trg_2 - self.hparam['a']) ** 2)
gen_loss = self.hparam['lambda_id'] * id_loss + self.hparam['lambda_cyc'] * cyc_loss + adv_loss
self.reset_grad()
gen_loss.backward(retain_graph=True)
self.gen_opt.step()
return dis_loss.item(), gen_loss.item(), adv_loss.item()
return dis_loss.item(), None, None
def train(self, num_epoch=3000):
# loop epoch
while self.epoch <= num_epoch:
print('Epoch {}'.format(self.epoch))
gen_losses = []
dis_losses = []
adv_losses = []
# loop batch
for idx, (mel, src, trg) in tqdm(enumerate(self.train_loader), total=len(self.train_loader)):
dis_loss, gen_loss, adv_loss = self.train_step(idx+1, mel.squeeze(0), src.squeeze(0), trg.squeeze(0))
dis_losses.append(dis_loss)
if gen_loss is not None:
gen_losses.append(gen_loss)
adv_losses.append(adv_loss)
print(' dis loss: {}'.format(sum(dis_losses) / len(dis_losses)))
print(' gen loss: {}'.format(sum(gen_losses) / len(gen_losses)))
print(' adv loss: {}'.format(sum(adv_losses) / len(adv_losses)))
# save checkpoint
if self.epoch % self.epoch_save == 0:
torch.save({
'epoch': self.epoch,
'gen': self.gen.state_dict(),
'dis': self.dis.state_dict()
}, f'./checkpoints/checkpoint_{self.epoch}.pt')
self.epoch += 1