-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.py
275 lines (241 loc) · 9.78 KB
/
main.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchcontrib.optim import SWA
from torch.nn.utils import rnn, clip_grad_norm_
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import os
import sys
import pdb
import json
import argparse
from argparse import Namespace
import numpy as np
from pesq import pesq
from tqdm import tqdm
from colorama import Fore
from collections import OrderedDict
from multiprocessing import Pool
from dataset import VoiceBankDemandDataset # please make your own "dataset.py" including a torch Dataset module.
from models import DeepConvolutionalUNet
from perceptual.losses import PerceptualLoss
from optimizers import RAdam
from utils import rnn_collate
def fix_seed(seed):
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def cal_pesq(x, y, l):
try:
score = pesq(16000, y[:l], x[:l], 'wb')
except:
score = 0.
return score
def evaluate(x, y, lens, fn):
y = list(y.cpu().detach().numpy())
x = list(x.cpu().detach().numpy())
lens = lens.cpu().detach().tolist()
pool = Pool(processes=args.num_workers)
try:
ret = pool.starmap(
fn,
iter([(deg, ref, l) for deg, ref, l in zip(x, y, lens)])
)
pool.close()
return torch.FloatTensor(ret).mean()
except KeyboardInterrupt:
pool.terminate()
pool.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# system setting
parser.add_argument('--exp_dir', default=os.getcwd(), type=str)
parser.add_argument('--exp_name', default='logs', type=str)
parser.add_argument('--data_dir', default='/Data/tahsieh/NSDTSEA/', type=str)
parser.add_argument('--num_workers', default=8, type=int)
parser.add_argument('--cuda', action='store_true')
parser.add_argument('--add_graph', action='store_true')
parser.add_argument('--log_interval', default=20, type=int)
parser.add_argument('--seed', default=0, type=int)
# training specifics
parser.add_argument('--batch_size', default=16, type=int)
parser.add_argument('--learning_rate', default=0.0001, type=float)
parser.add_argument('--num_epochs', default=100, type=int)
parser.add_argument('--clip_grad_norm_val', default=0.0, type=float)
parser.add_argument('--grad_accumulate_batches', default=1, type=int)
parser.add_argument('--log_grad_norm', action='store_true')
parser.add_argument('--resume_dir', default='', type=str)
parser.add_argument('--use_swa', action='store_true')
parser.add_argument('--lr_decay', default=1.0, type=float)
# stft/istft settings
parser.add_argument('--n_fft', default=512, type=int)
parser.add_argument('--hop_length', default=128, type=int)
# model hyperparameters
parser.add_argument('--model_type', default='wav2vec', type=str)
args = parser.parse_args()
# add hyperparameters
ckpt_path = os.path.join(args.exp_dir, args.exp_name, 'ckpt')
if not os.path.exists(ckpt_path):
os.makedirs(ckpt_path)
os.makedirs(ckpt_path.replace('ckpt', 'logs'))
with open(os.path.join(ckpt_path, 'hparams.json'), 'w') as f:
json.dump(vars(args), f)
else:
print(f'Experiment {args.exp_name} already exists.')
sys.exit()
writer = SummaryWriter(os.path.join(args.exp_dir, args.exp_name, 'logs'))
writer.add_hparams(vars(args), dict())
# seed
if args.seed:
fix_seed(args.seed)
# device
device = 'cuda' if torch.cuda.is_available() and args.cuda else 'cpu'
if device == 'cuda':
print(f'DEVICE: [{torch.cuda.current_device()}] {torch.cuda.get_device_name()}')
else:
print(f'DEVICE: CPU')
# create loaders
train_dataloader = DataLoader(
# put your train dataset here,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers
)
val_dataloader = DataLoader(
# put your validation dataset here,
batch_size=args.batch_size,
shuffle=False,
collate_fn=rnn_collate,
num_workers=args.num_workers
)
# create model
if not args.resume_dir:
net = DeepConvolutionalUNet(hidden_size=args.n_fft // 2 + 1)
net = nn.DataParallel(net)
else:
try:
with open(os.path.join(args.resume_dir, 'hparams.json'), 'r') as f:
hparams = json.load(f)
except FileNotFoundError:
print('Cannot find "hparams.json".')
sys.exit()
hparams['resume_dir'] = args.resume_dir
args = Namespace(**hparams)
net = DeepConvolutionalUNet(hidden_size=args.n_fft // 2 + 1)
net = nn.DataParallel(net)
model_path = os.path.join(args.resume_dir, 'model_best.ckpt')
print(f'Resume model from {model_path} ...')
checkpoint = torch.load(model_path)
net.load_state_dict(checkpoint['model_state_dict'])
net = net.to(device)
# optimization
# optimizer = optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9)
# optimizer = optim.Adam(net.parameters(), lr=args.learning_rate, weight_decay=0.1)
optimizer = RAdam(net.parameters(), lr=args.learning_rate, weight_decay=0.1)
scheduler = None
if args.use_swa:
steps_per_epoch = len(train_dataloader) // args.batch_size
optimizer = SWA(optimizer, swa_start=20 * steps_per_epoch, swa_freq=steps_per_epoch)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer.optimizer, mode="max", patience=5, factor=0.5)
else:
scheduler = None
if args.resume_dir:
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
start_epoch = checkpoint['epoch'] + 1
# best_pesq = checkpoint['pesq']
best_pesq = 0.0
else:
start_epoch = 0
best_pesq = 0.0
# scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'max', patience=5)
# add graph to tensorboard
if args.add_graph:
dummy = torch.randn(16, 1, args.hop_length * 16).to(device)
writer.add_graph(net, dummy)
# define loss
per_loss = PerceptualLoss(model_type=args.model_type)
per_loss = per_loss.to(device)
criterion = lambda y_hat, y: per_loss(y_hat, y) + F.l1_loss(y_hat, y)
# iteration start
for epoch in range(start_epoch, start_epoch + args.num_epochs, 1):
# ------------- training -------------
net.train()
pbar = tqdm(train_dataloader, bar_format='{l_bar}%s{bar}%s{r_bar}'%(Fore.BLUE, Fore.RESET))
pbar.set_description(f'Epoch {epoch + 1}')
total_loss = 0.0
if args.log_grad_norm:
total_norm = 0.0
net.zero_grad()
for i, (n, c) in enumerate(pbar):
n, c = n.to(device), c.to(device)
e = net(n)
loss = criterion(e, c)
loss /= args.grad_accumulate_batches
loss.backward()
# gradient clipping
if args.clip_grad_norm_val > 0.0:
clip_grad_norm_(net.parameters(), args.clip_grad_norm_val)
# log metrics
pbar_dict = OrderedDict({
'loss': loss.item(),
})
pbar.set_postfix(pbar_dict)
total_loss += loss.item()
if (i + 1) % args.log_interval == 0:
step = epoch * len(train_dataloader) + i
writer.add_scalar('Loss/train', total_loss / args.log_interval, step)
total_loss = 0.0
# log gradient norm
if args.log_grad_norm:
for p in net.parameters():
if p.requires_grad:
norm = p.grad.data.norm(2)
total_norm += norm.item() ** 2
norm = total_norm ** 0.5
writer.add_scalar('Gradient 2-Norm/train', norm, step)
total_norm = 0.0
# accumulate gradients
if (i + 1) % args.grad_accumulate_batches == 0:
optimizer.step()
net.zero_grad()
# ------------- validation -------------
pbar = tqdm(val_dataloader, bar_format='{l_bar}%s{bar}%s{r_bar}'%(Fore.LIGHTMAGENTA_EX, Fore.RESET))
pbar.set_description('Validation')
total_loss, total_pesq = 0.0, 0.0
num_val_data = len(val_dataloader)
with torch.no_grad():
net.eval()
for i, (n, c, l) in enumerate(pbar):
n, c = n.to(device), c.to(device)
e = net(n)
loss = criterion(e, c)
pesq_score = evaluate(e, c, l, fn=cal_pesq)
pbar_dict = OrderedDict({
'val_loss': loss.item(),
'val_pesq': pesq_score.item(),
})
pbar.set_postfix(pbar_dict)
total_loss += loss.item()
total_pesq += pesq_score.item()
if scheduler is not None:
scheduler.step(total_pesq / num_val_data)
writer.add_scalar('Loss/valid', total_loss / num_val_data, epoch)
writer.add_scalar('PESQ/valid', total_pesq / num_val_data, epoch)
# checkpointing
curr_pesq = total_pesq / num_val_data
if curr_pesq > best_pesq:
best_pesq = curr_pesq
save_path = os.path.join(ckpt_path, 'model_best.ckpt')
print(f'Saving checkpoint to {save_path}')
torch.save({
'epoch': epoch,
'model_state_dict': net.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': total_loss / num_val_data,
'pesq': total_pesq / num_val_data
}, save_path)
writer.flush()
writer.close()