-
Notifications
You must be signed in to change notification settings - Fork 2
/
Train.py
173 lines (146 loc) · 5.57 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
167
168
169
170
171
172
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import argparse
import json
from Datasets import *
from Autoencoder import Autoencoder
from Encoders import *
from Decoders import *
from PyFire import Trainer
from Utils import *
from Losses import *
from Metrics import *
import matplotlib.pyplot as plt
if __name__ == '__main__':
seed_everything()
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', type=str,
help='JSON file for configuration')
args = parser.parse_args()
with open(f'Configs/{args.config}') as f:
data = f.read()
config = json.loads(data)
global dataset_config
dataset_config = config['dataset_config']
global encoder_config
encoder_config = config['model_config']['encoder_config']
global decoder_config
decoder_config = config['model_config']['decoder_config']
global autoencoder_config
autoencoder_config = config['model_config']
global learning_params
learning_params = config['learning_params']
global trainer_params
trainer_params = config['trainer_params']
if dataset_config['name'] == 'Chirp':
train_set = ChirpDataset(subset='train',
n_samples=dataset_config['n_train_samples'],
**dataset_config['signal_params'])
val_set = ChirpDataset(subset='test',
n_samples=dataset_config['n_test_samples'],
**dataset_config['signal_params'])
elif dataset_config['name'] == 'Macaque':
train_set = MacaqueDataset(subset='train')
val_set = MacaqueDataset(subset='test')
elif dataset_config['name'] == 'ESC':
train_set = ESCDataset(subset='train')
val_set = ESCDataset(subset='test')
elif dataset_config['name'] == 'MusDB18':
train_set = MusDB18Dataset(split='train',
n_samples=dataset_config['n_train_samples'],
**dataset_config['signal_params'])
val_set = MusDB18Dataset(split='test',
n_samples=dataset_config['n_test_samples'],
**dataset_config['signal_params'])
elif dataset_config['name'] == 'Geladas':
train_set = GeladaDataset(subset='train')
val_set = GeladaDataset(subset='test')
elif dataset_config['name'] == 'HumpbackWhups':
train_set = HumpbackWhupsDataset(subset='train')
val_set = HumpbackWhupsDataset(subset='test')
train_loader = DataLoader(train_set,
batch_size=learning_params['batch_size'],
shuffle=True)
val_loader = DataLoader(val_set,
batch_size=learning_params['batch_size'],
shuffle=False)
if encoder_config['model_name'] == 'ToyConv':
encoder = ToyConvEncoder(**encoder_config['model_params'])
elif encoder_config['model_name'] == 'Conv':
encoder = ConvEncoder(**encoder_config['model_params'])
if encoder_config['model_name'] == 'ToyConvV0':
encoder = ToyConvEncoderV0()
if decoder_config['model_name'] == 'ToyConv':
decoder = ToyConvDecoder(**decoder_config['model_params'])
elif decoder_config['model_name'] == 'Conv':
decoder = ConvDecoder(**decoder_config['model_params'])
elif decoder_config['model_name'] == 'ToyConvV0':
decoder = ToyConvDecoderV0()
autoencoder = Autoencoder(encoder,
decoder,
**autoencoder_config['model_params'])
autoencoder.apply(weights_init)
optimizer = torch.optim.Adam(autoencoder.parameters(),
lr=learning_params['learning_rate'])
scheduler = trainer_params['scheduler']
if scheduler is not None:
if scheduler['type'] == 'plateau':
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', **scheduler['kwargs'])
elif scheduler['type'] == 'step':
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, **scheduler['kwargs'])
elif scheduler['type'] == 'multi_step':
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, **scheduler['kwargs'])
stft = STFT(kernel_size=encoder_config['model_params']['nfft'],
stride=encoder_config['model_params']['hop'],
coords='polar',
dB=False)
if autoencoder.vae:
recon_loss_fx = lambda x, y: vae_perceptual_loss(*x, stft=stft)
loss_func = {'Perceptual_Loss': recon_loss_fx}
kld_loss_fx = lambda x, y: vae_kld_loss(*x)
trainer_params['params']['kld_loss'] = kld_loss_fx
assert len(trainer_params['params']['weights']) == 2
metric_fx = vae_si_sdr
metric_func = {'SI_SDR': metric_fx}
elif autoencoder.vq_vae:
recon_loss_fx = lambda x, y: vae_perceptual_loss(*x, stft=stft)
loss_func = {'Perceptual_Loss': recon_loss_fx}
latent_loss_fx = lambda x, y: vq_vae_latent_loss(*x)
trainer_params['params']['latent_loss'] = latent_loss_fx
metric_fx = vae_si_sdr
metric_func = {'SI_SDR': metric_fx}
else:
loss_fx = lambda x, y: perceptual_loss(x, y, stft=stft)
loss_func = {'Perceptual_Loss': loss_fx}
metric_fx = si_sdr
metric_func = {'SI_SDR': metric_fx}
try:
logistic_fx = lambda x: logistic(x, **trainer_params['weights_func']['kwargs'])
index = trainer_params['weights_func']['index']
def weights_func(weights, epoch):
weights[index] = logistic_fx(epoch)
return weights
trainer_params['params']['weights_func'] = weights_func
except KeyError:
pass
if trainer_params['device'] == 'cuda':
if torch.cuda.is_available():
pass
else:
print('CUDA not available. Switching to CPU.')
trainer_params['device'] = 'cpu'
trainer = Trainer(autoencoder, optimizer,
scheduler=scheduler,
loss_func=loss_func,
metric_func=metric_func,
verbose=trainer_params['verbose'],
device=trainer_params['device'],
dest=trainer_params['dest'],
**trainer_params['params'])
trainer.fit(train_loader,
val_loader,
learning_params['epochs'])
trainer.save_model()