Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,526 @@ tokenizer = AutoTokenizer.from_pretrained("wasmdashai/vits-ar-sa-huba",token=tok
|
|
| 10 |
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
model_vits=VitsModel.from_pretrained("wasmdashai/vits-ar-sa-huba",token=token)#.to(device)
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def modelspeech(texts):
|
| 14 |
|
| 15 |
|
|
|
|
| 10 |
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
model_vits=VitsModel.from_pretrained("wasmdashai/vits-ar-sa-huba",token=token)#.to(device)
|
| 12 |
|
| 13 |
+
import VitsModelSplit.monotonic_align as monotonic_align
|
| 14 |
+
from IPython.display import clear_output
|
| 15 |
+
from transformers import set_seed
|
| 16 |
+
import wandb
|
| 17 |
+
import logging
|
| 18 |
+
import copy
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from datasets import DatasetDict,Dataset
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
from VitsModelSplit.vits_model2 import VitsModel,get_state_grad_loss
|
| 28 |
+
from VitsModelSplit.PosteriorDecoderModel import PosteriorDecoderModel
|
| 29 |
+
from VitsModelSplit.feature_extraction import VitsFeatureExtractor
|
| 30 |
+
|
| 31 |
+
from transformers import AutoTokenizer, HfArgumentParser, set_seed
|
| 32 |
+
from VitsModelSplit.Arguments import DataTrainingArguments, ModelArguments, VITSTrainingArguments
|
| 33 |
+
from VitsModelSplit.dataset_features_collector import FeaturesCollectionDataset
|
| 34 |
+
from torch.cuda.amp import autocast, GradScaler
|
| 35 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 36 |
+
model=VitsModel.from_pretrained("facebook/mms-tts-eng").to(device)
|
| 37 |
+
# model1= VitsModel.from_pretrained("/content/drive/MyDrive/vitsM/OneBatch/S6/MMMMM-dash-azd60").to("cuda")
|
| 38 |
+
# model= VitsModel.from_pretrained("/content/drive/MyDrive/vitsM/TO/sp3/core/vend").to("cuda")
|
| 39 |
+
# model=VitsModel.from_pretrained("/content/drive/MyDrive/vitsM/heppa/EndCore3/v0").to("cuda")
|
| 40 |
+
# model.discriminator=model1.discriminator
|
| 41 |
+
# model.duration_predictor=model1.duration_predictor
|
| 42 |
+
|
| 43 |
+
model.setMfA(monotonic_align.maximum_path)
|
| 44 |
+
# tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-ara",cache_dir="./")
|
| 45 |
+
feature_extractor = VitsFeatureExtractor()
|
| 46 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, VITSTrainingArguments))
|
| 47 |
+
json_file = os.path.abspath('VitsModelSplit/finetune_config_ara.json')
|
| 48 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file = json_file)
|
| 49 |
+
sgl=get_state_grad_loss(mel=True,
|
| 50 |
+
# generator=False,
|
| 51 |
+
# discriminator=False,
|
| 52 |
+
duration=False)
|
| 53 |
+
|
| 54 |
+
training_args.num_train_epochs=1000
|
| 55 |
+
training_args.fp16=True
|
| 56 |
+
training_args.eval_steps=300
|
| 57 |
+
# sgl=get_state_grad_loss(k1=True,#generator=False,
|
| 58 |
+
# discriminator=False,
|
| 59 |
+
# duration=False
|
| 60 |
+
# )
|
| 61 |
+
Lst=['input_ids',
|
| 62 |
+
'attention_mask',
|
| 63 |
+
'waveform',
|
| 64 |
+
'labels',
|
| 65 |
+
'labels_attention_mask',
|
| 66 |
+
'mel_scaled_input_features']
|
| 67 |
+
def covert_cuda_batch(d):
|
| 68 |
+
# return d
|
| 69 |
+
for key in Lst:
|
| 70 |
+
d[key]=d[key].cuda(non_blocking=True)
|
| 71 |
+
# for key in d['text_encoder_output']:
|
| 72 |
+
# d['text_encoder_output'][key]=d['text_encoder_output'][key].cuda(non_blocking=True)
|
| 73 |
+
# for key in d['posterior_encode_output']:
|
| 74 |
+
# d['posterior_encode_output'][key]=d['posterior_encode_output'][key].cuda(non_blocking=True)
|
| 75 |
+
|
| 76 |
+
return d
|
| 77 |
+
def generator_loss(disc_outputs):
|
| 78 |
+
total_loss = 0
|
| 79 |
+
gen_losses = []
|
| 80 |
+
for disc_output in disc_outputs:
|
| 81 |
+
disc_output = disc_output
|
| 82 |
+
loss = torch.mean((1 - disc_output) ** 2)
|
| 83 |
+
gen_losses.append(loss)
|
| 84 |
+
total_loss += loss
|
| 85 |
+
|
| 86 |
+
return total_loss, gen_losses
|
| 87 |
+
|
| 88 |
+
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
|
| 89 |
+
loss = 0
|
| 90 |
+
real_losses = 0
|
| 91 |
+
generated_losses = 0
|
| 92 |
+
for disc_real, disc_generated in zip(disc_real_outputs, disc_generated_outputs):
|
| 93 |
+
real_loss = torch.mean((1 - disc_real) ** 2)
|
| 94 |
+
generated_loss = torch.mean(disc_generated**2)
|
| 95 |
+
loss += real_loss + generated_loss
|
| 96 |
+
real_losses += real_loss
|
| 97 |
+
generated_losses += generated_loss
|
| 98 |
+
|
| 99 |
+
return loss, real_losses, generated_losses
|
| 100 |
+
|
| 101 |
+
def feature_loss(feature_maps_real, feature_maps_generated):
|
| 102 |
+
loss = 0
|
| 103 |
+
for feature_map_real, feature_map_generated in zip(feature_maps_real, feature_maps_generated):
|
| 104 |
+
for real, generated in zip(feature_map_real, feature_map_generated):
|
| 105 |
+
real = real.detach()
|
| 106 |
+
loss += torch.mean(torch.abs(real - generated))
|
| 107 |
+
|
| 108 |
+
return loss * 2
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
|
| 112 |
+
"""
|
| 113 |
+
z_p, logs_q: [b, h, t_t]
|
| 114 |
+
m_p, logs_p: [b, h, t_t]
|
| 115 |
+
"""
|
| 116 |
+
z_p = z_p.float()
|
| 117 |
+
logs_q = logs_q.float()
|
| 118 |
+
m_p = m_p.float()
|
| 119 |
+
logs_p = logs_p.float()
|
| 120 |
+
z_mask = z_mask.float()
|
| 121 |
+
|
| 122 |
+
kl = logs_p - logs_q - 0.5
|
| 123 |
+
kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
|
| 124 |
+
kl = torch.sum(kl * z_mask)
|
| 125 |
+
l = kl / torch.sum(z_mask)
|
| 126 |
+
return l
|
| 127 |
+
#.............................................
|
| 128 |
+
# def kl_loss(prior_latents, posterior_log_variance, prior_means, prior_log_variance, labels_mask):
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# kl = prior_log_variance - posterior_log_variance - 0.5
|
| 132 |
+
# kl += 0.5 * ((prior_latents - prior_means) ** 2) * torch.exp(-2.0 * prior_log_variance)
|
| 133 |
+
# kl = torch.sum(kl * labels_mask)
|
| 134 |
+
# loss = kl / torch.sum(labels_mask)
|
| 135 |
+
# return loss
|
| 136 |
+
|
| 137 |
+
def get_state_grad_loss(k1=True,
|
| 138 |
+
mel=True,
|
| 139 |
+
duration=True,
|
| 140 |
+
generator=True,
|
| 141 |
+
discriminator=True):
|
| 142 |
+
return {'k1':k1,'mel':mel,'duration':duration,'generator':generator,'discriminator':discriminator}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
| 146 |
+
if isinstance(parameters, torch.Tensor):
|
| 147 |
+
parameters = [parameters]
|
| 148 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
| 149 |
+
norm_type = float(norm_type)
|
| 150 |
+
if clip_value is not None:
|
| 151 |
+
clip_value = float(clip_value)
|
| 152 |
+
|
| 153 |
+
total_norm = 0
|
| 154 |
+
for p in parameters:
|
| 155 |
+
param_norm = p.grad.data.norm(norm_type)
|
| 156 |
+
total_norm += param_norm.item() ** norm_type
|
| 157 |
+
if clip_value is not None:
|
| 158 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
| 159 |
+
total_norm = total_norm ** (1. / norm_type)
|
| 160 |
+
return total_norm
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def get_embed_speaker(self,speaker_id):
|
| 164 |
+
if self.config.num_speakers > 1 and speaker_id is not None:
|
| 165 |
+
if isinstance(speaker_id, int):
|
| 166 |
+
speaker_id = torch.full(size=(1,), fill_value=speaker_id, device=self.device)
|
| 167 |
+
elif isinstance(speaker_id, (list, tuple, np.ndarray)):
|
| 168 |
+
speaker_id = torch.tensor(speaker_id, device=self.device)
|
| 169 |
+
|
| 170 |
+
if not ((0 <= speaker_id).all() and (speaker_id < self.config.num_speakers).all()).item():
|
| 171 |
+
raise ValueError(f"Set `speaker_id` in the range 0-{self.config.num_speakers - 1}.")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
return self.embed_speaker(speaker_id).unsqueeze(-1)
|
| 175 |
+
else:
|
| 176 |
+
return None
|
| 177 |
+
def get_data_loader(train_dataset_dirs,eval_dataset_dir,full_generation_dir,device):
|
| 178 |
+
ctrain_datasets=[]
|
| 179 |
+
for dataset_dir ,id_sp in train_dataset_dirs:
|
| 180 |
+
train_dataset = FeaturesCollectionDataset(dataset_dir = os.path.join(dataset_dir,'train'),
|
| 181 |
+
device = device
|
| 182 |
+
)
|
| 183 |
+
ctrain_datasets.append((train_dataset,id_sp))
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
eval_dataset = None
|
| 189 |
+
if training_args.do_eval:
|
| 190 |
+
eval_dataset = FeaturesCollectionDataset(dataset_dir = eval_dataset_dir,
|
| 191 |
+
device = device
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
full_generation_dataset = FeaturesCollectionDataset(dataset_dir = full_generation_dir,
|
| 195 |
+
device = device)
|
| 196 |
+
return ctrain_datasets,eval_dataset,full_generation_dataset
|
| 197 |
+
global_step=0
|
| 198 |
+
def trainer_to_cuda(self,
|
| 199 |
+
ctrain_datasets = None,
|
| 200 |
+
eval_dataset = None,
|
| 201 |
+
full_generation_dataset = None,
|
| 202 |
+
feature_extractor = VitsFeatureExtractor(),
|
| 203 |
+
training_args = None,
|
| 204 |
+
full_generation_sample_index= 0,
|
| 205 |
+
project_name = "Posterior_Decoder_Finetuning",
|
| 206 |
+
wandbKey = "782b6a6e82bbb5a5348de0d3c7d40d1e76351e79",
|
| 207 |
+
is_used_text_encoder=True,
|
| 208 |
+
is_used_posterior_encode=True,
|
| 209 |
+
dict_state_grad_loss=None,
|
| 210 |
+
nk=1,
|
| 211 |
+
path_save_model='./',
|
| 212 |
+
maf=None,
|
| 213 |
+
n_back_save_model=3000,
|
| 214 |
+
start_speeker=0,
|
| 215 |
+
end_speeker=1,
|
| 216 |
+
n_epoch=0,
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
):
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# os.makedirs(training_args.output_dir,exist_ok=True)
|
| 224 |
+
# logger = logging.getLogger(f"{__name__} Training")
|
| 225 |
+
# log_level = training_args.get_process_log_level()
|
| 226 |
+
# logger.setLevel(log_level)
|
| 227 |
+
|
| 228 |
+
# # wandb.login(key= wandbKey)
|
| 229 |
+
# # wandb.init(project= project_name,config = training_args.to_dict())
|
| 230 |
+
if dict_state_grad_loss is None:
|
| 231 |
+
dict_state_grad_loss=get_state_grad_loss()
|
| 232 |
+
global global_step
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
set_seed(training_args.seed)
|
| 237 |
+
scaler = GradScaler(enabled=training_args.fp16)
|
| 238 |
+
self.config.save_pretrained(training_args.output_dir)
|
| 239 |
+
len_db=len(ctrain_datasets)
|
| 240 |
+
self.full_generation_sample = full_generation_dataset[full_generation_sample_index]
|
| 241 |
+
|
| 242 |
+
# init optimizer, lr_scheduler
|
| 243 |
+
for disc in self.discriminator.discriminators:
|
| 244 |
+
disc.apply_weight_norm()
|
| 245 |
+
self.decoder.apply_weight_norm()
|
| 246 |
+
# torch.nn.utils.weight_norm(self.decoder.conv_pre)
|
| 247 |
+
# torch.nn.utils.weight_norm(self.decoder.conv_post)
|
| 248 |
+
for flow in self.flow.flows:
|
| 249 |
+
torch.nn.utils.weight_norm(flow.conv_pre)
|
| 250 |
+
torch.nn.utils.weight_norm(flow.conv_post)
|
| 251 |
+
|
| 252 |
+
discriminator=self.discriminator
|
| 253 |
+
self.discriminator=None
|
| 254 |
+
|
| 255 |
+
optimizer = torch.optim.AdamW(
|
| 256 |
+
self.parameters(),
|
| 257 |
+
training_args.learning_rate,
|
| 258 |
+
betas=[training_args.adam_beta1, training_args.adam_beta2],
|
| 259 |
+
eps=training_args.adam_epsilon,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# hack to be able to train on multiple device
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
disc_optimizer = torch.optim.AdamW(
|
| 266 |
+
discriminator.parameters(),
|
| 267 |
+
training_args.d_learning_rate,
|
| 268 |
+
betas=[training_args.d_adam_beta1, training_args.d_adam_beta2],
|
| 269 |
+
eps=training_args.adam_epsilon,
|
| 270 |
+
)
|
| 271 |
+
lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(
|
| 272 |
+
optimizer, gamma=training_args.lr_decay, last_epoch=-1
|
| 273 |
+
)
|
| 274 |
+
disc_lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(
|
| 275 |
+
disc_optimizer, gamma=training_args.lr_decay, last_epoch=-1)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
logger.info("***** Running training *****")
|
| 279 |
+
logger.info(f" Num Epochs = {training_args.num_train_epochs}")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
#.......................loop training............................
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
for epoch in range(training_args.num_train_epochs):
|
| 287 |
+
train_losses_sum = 0
|
| 288 |
+
loss_gen=0
|
| 289 |
+
loss_des=0
|
| 290 |
+
loss_durationsall=0
|
| 291 |
+
loss_melall=0
|
| 292 |
+
loss_klall=0
|
| 293 |
+
loss_fmapsall=0
|
| 294 |
+
lr_scheduler.step()
|
| 295 |
+
|
| 296 |
+
disc_lr_scheduler.step()
|
| 297 |
+
train_dataset,speaker_id=ctrain_datasets[epoch%len_db]
|
| 298 |
+
print(f" Num Epochs = {int((epoch+n_epoch)/len_db)}, speaker_id DB ={speaker_id}")
|
| 299 |
+
num_div_proc=int(len(train_dataset)/10)
|
| 300 |
+
print(' -process traning : [',end='')
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
for step, batch in enumerate(train_dataset):
|
| 309 |
+
# if speaker_id==None:
|
| 310 |
+
# if step<3 :continue
|
| 311 |
+
|
| 312 |
+
# if step>200:break
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
batch=covert_cuda_batch(batch)
|
| 316 |
+
displayloss={}
|
| 317 |
+
|
| 318 |
+
with autocast(enabled=training_args.fp16):
|
| 319 |
+
speaker_embeddings=get_embed_speaker(self,batch["speaker_id"] if speaker_id ==None else speaker_id )
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
waveform,ids_slice,log_duration,prior_latents,posterior_log_variances,prior_means,prior_log_variances,labels_padding_mask = self.forward_train(
|
| 323 |
+
input_ids=batch["input_ids"],
|
| 324 |
+
attention_mask=batch["attention_mask"],
|
| 325 |
+
labels=batch["labels"],
|
| 326 |
+
labels_attention_mask=batch["labels_attention_mask"],
|
| 327 |
+
text_encoder_output =None ,
|
| 328 |
+
posterior_encode_output=None ,
|
| 329 |
+
return_dict=True,
|
| 330 |
+
monotonic_alignment_function= maf,
|
| 331 |
+
speaker_embeddings=speaker_embeddings
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
mel_scaled_labels = batch["mel_scaled_input_features"]
|
| 335 |
+
mel_scaled_target = self.slice_segments(mel_scaled_labels, ids_slice,self.segment_size)
|
| 336 |
+
mel_scaled_generation = feature_extractor._torch_extract_fbank_features(waveform.squeeze(1))[1]
|
| 337 |
+
|
| 338 |
+
target_waveform = batch["waveform"].transpose(1, 2)
|
| 339 |
+
target_waveform = self.slice_segments(
|
| 340 |
+
target_waveform,
|
| 341 |
+
ids_slice * feature_extractor.hop_length,
|
| 342 |
+
self.config.segment_size
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
discriminator_target, fmaps_target = discriminator(target_waveform)
|
| 346 |
+
discriminator_candidate, fmaps_candidate = discriminator(waveform.detach())
|
| 347 |
+
with autocast(enabled=False):
|
| 348 |
+
if dict_state_grad_loss['discriminator']:
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
loss_disc, loss_real_disc, loss_fake_disc = discriminator_loss(
|
| 352 |
+
discriminator_target, discriminator_candidate
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
dk={"step_loss_disc": loss_disc.detach().item(),
|
| 356 |
+
"step_loss_real_disc": loss_real_disc.detach().item(),
|
| 357 |
+
"step_loss_fake_disc": loss_fake_disc.detach().item()}
|
| 358 |
+
displayloss['dict_loss_discriminator']=dk
|
| 359 |
+
loss_dd = loss_disc# + loss_real_disc + loss_fake_disc
|
| 360 |
+
|
| 361 |
+
# loss_dd.backward()
|
| 362 |
+
|
| 363 |
+
disc_optimizer.zero_grad()
|
| 364 |
+
scaler.scale(loss_dd).backward()
|
| 365 |
+
scaler.unscale_(disc_optimizer )
|
| 366 |
+
grad_norm_d = clip_grad_value_(discriminator.parameters(), None)
|
| 367 |
+
scaler.step(disc_optimizer)
|
| 368 |
+
loss_des+=grad_norm_d
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
with autocast(enabled=training_args.fp16):
|
| 372 |
+
|
| 373 |
+
# backpropagate
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
discriminator_target, fmaps_target = discriminator(target_waveform)
|
| 380 |
+
|
| 381 |
+
discriminator_candidate, fmaps_candidate = discriminator(waveform.detach())
|
| 382 |
+
with autocast(enabled=False):
|
| 383 |
+
if dict_state_grad_loss['k1']:
|
| 384 |
+
loss_kl = kl_loss(
|
| 385 |
+
prior_latents,
|
| 386 |
+
posterior_log_variances,
|
| 387 |
+
prior_means,
|
| 388 |
+
prior_log_variances,
|
| 389 |
+
labels_padding_mask,
|
| 390 |
+
)
|
| 391 |
+
loss_kl=loss_kl*training_args.weight_kl
|
| 392 |
+
loss_klall+=loss_kl.detach().item()
|
| 393 |
+
#if displayloss['loss_kl']>=0:
|
| 394 |
+
# loss_kl.backward()
|
| 395 |
+
|
| 396 |
+
if dict_state_grad_loss['mel']:
|
| 397 |
+
loss_mel = torch.nn.functional.l1_loss(mel_scaled_target, mel_scaled_generation)*training_args.weight_mel
|
| 398 |
+
loss_melall+= loss_mel.detach().item()
|
| 399 |
+
# train_losses_sum = train_losses_sum + displayloss['loss_mel']
|
| 400 |
+
# if displayloss['loss_mel']>=0:
|
| 401 |
+
# loss_mel.backward()
|
| 402 |
+
|
| 403 |
+
if dict_state_grad_loss['duration']:
|
| 404 |
+
loss_duration=torch.sum(log_duration)*training_args.weight_duration
|
| 405 |
+
loss_durationsall+=loss_duration.detach().item()
|
| 406 |
+
# if displayloss['loss_duration']>=0:
|
| 407 |
+
# loss_duration.backward()
|
| 408 |
+
if dict_state_grad_loss['generator']:
|
| 409 |
+
loss_fmaps = feature_loss(fmaps_target, fmaps_candidate)
|
| 410 |
+
loss_gen, losses_gen = generator_loss(discriminator_candidate)
|
| 411 |
+
loss_gen=loss_gen * training_args.weight_gen
|
| 412 |
+
displayloss['loss_gen'] = loss_gen.detach().item()
|
| 413 |
+
# loss_gen.backward(retain_graph=True)
|
| 414 |
+
loss_fmaps=loss_fmaps * training_args.weight_fmaps
|
| 415 |
+
displayloss['loss_fmaps'] = loss_fmaps.detach().item()
|
| 416 |
+
# loss_fmaps.backward(retain_graph=True)
|
| 417 |
+
total_generator_loss = (
|
| 418 |
+
loss_duration
|
| 419 |
+
+ loss_mel
|
| 420 |
+
+ loss_kl
|
| 421 |
+
+ loss_fmaps
|
| 422 |
+
+ loss_gen
|
| 423 |
+
)
|
| 424 |
+
# total_generator_loss.backward()
|
| 425 |
+
optimizer.zero_grad()
|
| 426 |
+
scaler.scale(total_generator_loss).backward()
|
| 427 |
+
scaler.unscale_(optimizer)
|
| 428 |
+
grad_norm_g = clip_grad_value_(self.parameters(), None)
|
| 429 |
+
scaler.step(optimizer)
|
| 430 |
+
scaler.update()
|
| 431 |
+
loss_gen+=grad_norm_g
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
# optimizer.step()
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
# print(f"TRAINIG - batch {step}, waveform {(batch['waveform'].shape)}, lr {lr_scheduler.get_last_lr()[0]}... ")
|
| 444 |
+
# print(f"display loss function enable :{displayloss}")
|
| 445 |
+
|
| 446 |
+
global_step +=1
|
| 447 |
+
if step%num_div_proc==0:
|
| 448 |
+
print('==',end='')
|
| 449 |
+
|
| 450 |
+
# validation
|
| 451 |
+
|
| 452 |
+
do_eval = training_args.do_eval and (global_step % training_args.eval_steps == 0)
|
| 453 |
+
if do_eval:
|
| 454 |
+
speaker_id_c=int(torch.randint(start_speeker,end_speeker,size=(1,))[0])
|
| 455 |
+
logger.info("Running validation... ")
|
| 456 |
+
eval_losses_sum = 0
|
| 457 |
+
cc=0;
|
| 458 |
+
for step, batch in enumerate(eval_dataset):
|
| 459 |
+
break
|
| 460 |
+
if cc>2: break
|
| 461 |
+
cc+=1
|
| 462 |
+
with torch.no_grad():
|
| 463 |
+
model_outputs = self.forward(
|
| 464 |
+
input_ids=batch["input_ids"],
|
| 465 |
+
attention_mask=batch["attention_mask"],
|
| 466 |
+
labels=batch["labels"],
|
| 467 |
+
labels_attention_mask=batch["labels_attention_mask"],
|
| 468 |
+
speaker_id=batch["speaker_id"],
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
return_dict=True,
|
| 472 |
+
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
mel_scaled_labels = batch["mel_scaled_input_features"]
|
| 476 |
+
mel_scaled_target = self.slice_segments(mel_scaled_labels, model_outputs.ids_slice,self.segment_size)
|
| 477 |
+
mel_scaled_generation = feature_extractor._torch_extract_fbank_features(model_outputs.waveform.squeeze(1))[1]
|
| 478 |
+
loss = loss_mel.detach().item()
|
| 479 |
+
eval_losses_sum +=loss
|
| 480 |
+
|
| 481 |
+
loss_mel = torch.nn.functional.l1_loss(mel_scaled_target, mel_scaled_generation)
|
| 482 |
+
print(f"VALIDATION - batch {step}, waveform {(batch['waveform'].shape)}, step_loss_mel {loss} ... ")
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
with torch.no_grad():
|
| 487 |
+
full_generation_sample = self.full_generation_sample
|
| 488 |
+
full_generation =self.forward(
|
| 489 |
+
input_ids =full_generation_sample["input_ids"],
|
| 490 |
+
attention_mask=full_generation_sample["attention_mask"],
|
| 491 |
+
speaker_id=speaker_id_c
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
full_generation_waveform = full_generation.waveform.cpu().numpy()
|
| 495 |
+
|
| 496 |
+
wandb.log({
|
| 497 |
+
"eval_losses": eval_losses_sum,
|
| 498 |
+
"full generations samples": [
|
| 499 |
+
wandb.Audio(w.reshape(-1), caption=f"Full generation sample {epoch}", sample_rate=16000)
|
| 500 |
+
for w in full_generation_waveform],})
|
| 501 |
+
step+=1
|
| 502 |
+
# wandb.log({"train_losses":loss_melall})
|
| 503 |
+
wandb.log({"loss_gen":loss_gen/step})
|
| 504 |
+
wandb.log({"loss_des":loss_des/step})
|
| 505 |
+
wandb.log({"loss_duration":loss_durationsall/step})
|
| 506 |
+
wandb.log({"loss_mel":loss_melall/step})
|
| 507 |
+
wandb.log({f"loss_kl_db{speaker_id}":loss_klall/step})
|
| 508 |
+
print(']',end='')
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
# self.save_pretrained(path_save_model)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
self.discriminator=discriminator
|
| 517 |
+
for disc in self.discriminator.discriminators:
|
| 518 |
+
disc.remove_weight_norm()
|
| 519 |
+
self.decoder.remove_weight_norm()
|
| 520 |
+
# torch.nn.utils.remove_weight_norm(self.decoder.conv_pre)
|
| 521 |
+
# torch.nn.utils.remove_weight_norm(self.decoder.conv_post)
|
| 522 |
+
for flow in self.flow.flows:
|
| 523 |
+
torch.nn.utils.remove_weight_norm(flow.conv_pre)
|
| 524 |
+
torch.nn.utils.remove_weight_norm(flow.conv_post)
|
| 525 |
+
|
| 526 |
+
self.save_pretrained(path_save_model)
|
| 527 |
+
|
| 528 |
+
logger.info("Running final full generations samples... ")
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
logger.info("***** Training / Inference Done *****")
|
| 533 |
def modelspeech(texts):
|
| 534 |
|
| 535 |
|