wasmdashai commited on
Commit
a30f38b
·
verified ·
1 Parent(s): d1553c7

Upload vits_model_only_d.py

Browse files
Files changed (1) hide show
  1. VitsModelSplit/vits_model_only_d.py +431 -0
VitsModelSplit/vits_model_only_d.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ import math
6
+ from typing import Any, Callable, Optional, Tuple, Union
7
+ from torch.cuda.amp import autocast, GradScaler
8
+
9
+ from .vits_config import VitsConfig,VitsPreTrainedModel
10
+ from .flow import VitsResidualCouplingBlock
11
+ from .duration_predictor import VitsDurationPredictor, VitsStochasticDurationPredictor
12
+ from .encoder import VitsTextEncoder
13
+ from .decoder import VitsHifiGan
14
+ from .posterior_encoder import VitsPosteriorEncoder
15
+ from .discriminator import VitsDiscriminator
16
+ from .vits_output import VitsModelOutput, VitsTrainingOutput
17
+
18
+
19
+ class Vits_models_only_decoder(VitsPreTrainedModel):
20
+
21
+ def __init__(self, config: VitsConfig):
22
+ super().__init__(config)
23
+
24
+ self.config = config
25
+ self.text_encoder = VitsTextEncoder(config)
26
+ self.flow = VitsResidualCouplingBlock(config)
27
+ self.decoder = VitsHifiGan(config)
28
+
29
+
30
+
31
+ if config.use_stochastic_duration_prediction:
32
+ self.duration_predictor = VitsStochasticDurationPredictor(config)
33
+ else:
34
+ self.duration_predictor = VitsDurationPredictor(config)
35
+
36
+ if config.num_speakers > 1:
37
+ self.embed_speaker = nn.Embedding(config.num_speakers, config.speaker_embedding_size)
38
+
39
+ # This is used only for training.
40
+ self.posterior_encoder = VitsPosteriorEncoder(config)
41
+ self.discriminator = VitsDiscriminator(config)
42
+
43
+ # These parameters control the synthesised speech properties
44
+ self.speaking_rate = config.speaking_rate
45
+ self.noise_scale = config.noise_scale
46
+ self.noise_scale_duration = config.noise_scale_duration
47
+ self.segment_size = self.config.segment_size // self.config.hop_length
48
+
49
+ # Initialize weights and apply final processing
50
+ self.post_init()
51
+
52
+
53
+ #....................................
54
+
55
+ def monotonic_align_max_path(self,log_likelihoods, mask):
56
+ # used for training - awfully slow
57
+ # an alternative is proposed in examples/pytorch/text-to-speech/run_vits_finetuning.py
58
+ path = torch.zeros_like(log_likelihoods)
59
+
60
+ text_length_maxs = mask.sum(1)[:, 0]
61
+ latent_length_maxs = mask.sum(2)[:, 0]
62
+
63
+ indexes = latent_length_maxs - 1
64
+
65
+ max_neg_val = -1e9
66
+
67
+ for batch_id in range(len(path)):
68
+ index = int(indexes[batch_id].item())
69
+ text_length_max = int(text_length_maxs[batch_id].item())
70
+ latent_length_max = int(latent_length_maxs[batch_id].item())
71
+
72
+ for y in range(text_length_max):
73
+ for x in range(max(0, latent_length_max + y - text_length_max), min(latent_length_max, y + 1)):
74
+ if x == y:
75
+ v_cur = max_neg_val
76
+ else:
77
+ v_cur = log_likelihoods[batch_id, y - 1, x]
78
+ if x == 0:
79
+ if y == 0:
80
+ v_prev = 0.0
81
+ else:
82
+ v_prev = max_neg_val
83
+ else:
84
+ v_prev = log_likelihoods[batch_id, y - 1, x - 1]
85
+ log_likelihoods[batch_id, y, x] += max(v_prev, v_cur)
86
+
87
+ for y in range(text_length_max - 1, -1, -1):
88
+ path[batch_id, y, index] = 1
89
+ if index != 0 and (
90
+ index == y or log_likelihoods[batch_id, y - 1, index] < log_likelihoods[batch_id, y - 1, index - 1]
91
+ ):
92
+ index = index - 1
93
+ return path
94
+
95
+ #....................................
96
+
97
+ def slice_segments(self,hidden_states, ids_str, segment_size=4):
98
+
99
+ batch_size, channels, _ = hidden_states.shape
100
+ # 1d tensor containing the indices to keep
101
+ indices = torch.arange(segment_size).to(ids_str.device)
102
+ # extend the indices to match the shape of hidden_states
103
+ indices = indices.view(1, 1, -1).expand(batch_size, channels, -1)
104
+ # offset indices with ids_str
105
+ indices = indices + ids_str.view(-1, 1, 1)
106
+ # gather indices
107
+ output = torch.gather(hidden_states, dim=2, index=indices)
108
+
109
+ return output
110
+
111
+
112
+ #....................................
113
+
114
+
115
+ def rand_slice_segments(self,hidden_states, sample_lengths=None, segment_size=4):
116
+
117
+ batch_size, _, seq_len = hidden_states.size()
118
+ if sample_lengths is None:
119
+ sample_lengths = seq_len
120
+ ids_str_max = sample_lengths - segment_size + 1
121
+ ids_str = (torch.rand([batch_size]).to(device=hidden_states.device) * ids_str_max).to(dtype=torch.long)
122
+ ret = self.slice_segments(hidden_states, ids_str, segment_size)
123
+
124
+ return ret, ids_str
125
+
126
+ #....................................
127
+
128
+ def resize_speaker_embeddings(
129
+ self,
130
+ new_num_speakers: int,
131
+ speaker_embedding_size: Optional[int] = None,
132
+ pad_to_multiple_of: Optional[int] = 2,
133
+ ):
134
+ if pad_to_multiple_of is not None:
135
+ new_num_speakers = ((new_num_speakers + pad_to_multiple_of - 1) // pad_to_multiple_of) * pad_to_multiple_of
136
+
137
+ # first, take care of embed_speaker
138
+ if self.config.num_speakers <= 1:
139
+ if speaker_embedding_size is None:
140
+ raise ValueError(
141
+ "The current model had no previous speaker embedding, but `speaker_embedding_size` is not specified. Pass `speaker_embedding_size` to this method."
142
+ )
143
+ # create new embedding layer
144
+ new_embeddings = nn.Embedding(
145
+ new_num_speakers,
146
+ speaker_embedding_size,
147
+ device=self.device,
148
+ )
149
+ # initialize all new embeddings
150
+ self._init_weights(new_embeddings)
151
+ else:
152
+ new_embeddings = self._get_resized_embeddings(self.embed_speaker, new_num_speakers)
153
+
154
+ self.embed_speaker = new_embeddings
155
+
156
+ # then take care of sub-models
157
+ self.flow.resize_speaker_embeddings(speaker_embedding_size)
158
+ for flow in self.flow.flows:
159
+ self._init_weights(flow.wavenet.cond_layer)
160
+
161
+ self.decoder.resize_speaker_embedding(speaker_embedding_size)
162
+ self._init_weights(self.decoder.cond)
163
+
164
+ self.duration_predictor.resize_speaker_embeddings(speaker_embedding_size)
165
+ self._init_weights(self.duration_predictor.cond)
166
+
167
+ self.posterior_encoder.resize_speaker_embeddings(speaker_embedding_size)
168
+ self._init_weights(self.posterior_encoder.wavenet.cond_layer)
169
+
170
+ self.config.num_speakers = new_num_speakers
171
+ self.config.speaker_embedding_size = speaker_embedding_size
172
+
173
+ #....................................
174
+
175
+ def get_input_embeddings(self):
176
+ return self.text_encoder.get_input_embeddings()
177
+
178
+ #....................................
179
+
180
+ def set_input_embeddings(self, value):
181
+ self.text_encoder.set_input_embeddings(value)
182
+
183
+ #....................................
184
+
185
+ def apply_weight_norm(self):
186
+ self.decoder.apply_weight_norm()
187
+ self.flow.apply_weight_norm()
188
+ self.posterior_encoder.apply_weight_norm()
189
+
190
+ #....................................
191
+
192
+ def remove_weight_norm(self):
193
+ self.decoder.remove_weight_norm()
194
+ self.flow.remove_weight_norm()
195
+ self.posterior_encoder.remove_weight_norm()
196
+
197
+ #....................................
198
+
199
+ def discriminate(self, hidden_states):
200
+ return self.discriminator(hidden_states)
201
+
202
+ #....................................
203
+
204
+ def get_encoder(self):
205
+ return self.text_encoder
206
+
207
+ #....................................
208
+
209
+ def _inference_forward(
210
+ self,
211
+ input_ids: Optional[torch.Tensor] = None,
212
+ attention_mask: Optional[torch.Tensor] = None,
213
+ speaker_embeddings: Optional[torch.Tensor] = None,
214
+ output_attentions: Optional[bool] = None,
215
+ output_hidden_states: Optional[bool] = None,
216
+ return_dict: Optional[bool] = None,
217
+ padding_mask: Optional[torch.Tensor] = None,
218
+ ):
219
+ text_encoder_output = self.text_encoder(
220
+ input_ids=input_ids,
221
+ padding_mask=padding_mask,
222
+ attention_mask=attention_mask,
223
+ output_attentions=output_attentions,
224
+ output_hidden_states=output_hidden_states,
225
+ return_dict=return_dict,
226
+ )
227
+ hidden_states = text_encoder_output[0] if not return_dict else text_encoder_output.last_hidden_state
228
+ hidden_states = hidden_states.transpose(1, 2)
229
+ input_padding_mask = padding_mask.transpose(1, 2)
230
+
231
+ prior_means = text_encoder_output[1] if not return_dict else text_encoder_output.prior_means
232
+ prior_log_variances = text_encoder_output[2] if not return_dict else text_encoder_output.prior_log_variances
233
+
234
+ if self.config.use_stochastic_duration_prediction:
235
+ log_duration = self.duration_predictor(
236
+ hidden_states,
237
+ input_padding_mask,
238
+ speaker_embeddings,
239
+ reverse=True,
240
+ noise_scale=self.noise_scale_duration,
241
+ )
242
+ else:
243
+ log_duration = self.duration_predictor(hidden_states, input_padding_mask, speaker_embeddings)
244
+
245
+ length_scale = 1.0 / self.speaking_rate
246
+ duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
247
+ predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
248
+
249
+
250
+ # Create a padding mask for the output lengths of shape (batch, 1, max_output_length)
251
+ indices = torch.arange(predicted_lengths.max(), dtype=predicted_lengths.dtype, device=predicted_lengths.device)
252
+ output_padding_mask = indices.unsqueeze(0) < predicted_lengths.unsqueeze(1)
253
+ output_padding_mask = output_padding_mask.unsqueeze(1).to(input_padding_mask.dtype)
254
+
255
+ # Reconstruct an attention tensor of shape (batch, 1, out_length, in_length)
256
+ attn_mask = torch.unsqueeze(input_padding_mask, 2) * torch.unsqueeze(output_padding_mask, -1)
257
+ batch_size, _, output_length, input_length = attn_mask.shape
258
+ cum_duration = torch.cumsum(duration, -1).view(batch_size * input_length, 1)
259
+ indices = torch.arange(output_length, dtype=duration.dtype, device=duration.device)
260
+ valid_indices = indices.unsqueeze(0) < cum_duration
261
+ valid_indices = valid_indices.to(attn_mask.dtype).view(batch_size, input_length, output_length)
262
+ padded_indices = valid_indices - nn.functional.pad(valid_indices, [0, 0, 1, 0, 0, 0])[:, :-1]
263
+ attn = padded_indices.unsqueeze(1).transpose(2, 3) * attn_mask
264
+
265
+ # Expand prior distribution
266
+ prior_means = torch.matmul(attn.squeeze(1), prior_means).transpose(1, 2)
267
+ prior_log_variances = torch.matmul(attn.squeeze(1), prior_log_variances).transpose(1, 2)
268
+
269
+ prior_latents = prior_means + torch.randn_like(prior_means) * torch.exp(prior_log_variances) * self.noise_scale
270
+ latents = self.flow(prior_latents, output_padding_mask, speaker_embeddings, reverse=True)
271
+
272
+ spectrogram = latents * output_padding_mask
273
+ return spectrogram
274
+
275
+ def forward(
276
+ self,
277
+ input_ids: Optional[torch.Tensor] = None,
278
+ attention_mask: Optional[torch.Tensor] = None,
279
+ speaker_id: Optional[int] = None,
280
+ output_attentions: Optional[bool] = None,
281
+ output_hidden_states: Optional[bool] = None,
282
+ return_dict: Optional[bool] = None,
283
+ labels: Optional[torch.FloatTensor] = None,
284
+ labels_attention_mask: Optional[torch.Tensor] = None,
285
+ monotonic_alignment_function: Optional[Callable] = None,
286
+ ) -> Union[Tuple[Any], VitsModelOutput]:
287
+
288
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
289
+ output_hidden_states = (
290
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
291
+ )
292
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
293
+
294
+ monotonic_alignment_function = (
295
+ self.monotonic_align_max_path if monotonic_alignment_function is None else monotonic_alignment_function
296
+ )
297
+
298
+ if attention_mask is not None:
299
+ input_padding_mask = attention_mask.unsqueeze(-1).float()
300
+ else:
301
+ input_padding_mask = torch.ones_like(input_ids).unsqueeze(-1).float()
302
+
303
+ if self.config.num_speakers > 1 and speaker_id is not None:
304
+ if isinstance(speaker_id, int):
305
+ speaker_id = torch.full(size=(1,), fill_value=speaker_id, device=self.device)
306
+ elif isinstance(speaker_id, (list, tuple, np.ndarray)):
307
+ speaker_id = torch.tensor(speaker_id, device=self.device)
308
+
309
+ if not ((0 <= speaker_id).all() and (speaker_id < self.config.num_speakers).all()).item():
310
+ raise ValueError(f"Set `speaker_id` in the range 0-{self.config.num_speakers - 1}.")
311
+ if not (len(speaker_id) == 1 or len(speaker_id == len(input_ids))):
312
+ raise ValueError(
313
+ f"You passed {len(speaker_id)} `speaker_id` but you should either pass one speaker id or `batch_size` `speaker_id`."
314
+ )
315
+
316
+ speaker_embeddings = self.embed_speaker(speaker_id).unsqueeze(-1)
317
+ else:
318
+ speaker_embeddings = None
319
+
320
+ # if inference, return inference forward of VitsModel
321
+ if labels is None:
322
+ return self._inference_forward(
323
+ input_ids,
324
+ attention_mask,
325
+ speaker_embeddings,
326
+ output_attentions,
327
+ output_hidden_states,
328
+ return_dict,
329
+ input_padding_mask,
330
+ )
331
+
332
+ if labels_attention_mask is not None:
333
+ labels_padding_mask = labels_attention_mask.unsqueeze(1).float()
334
+ else:
335
+ labels_attention_mask = torch.ones((labels.shape[0], labels.shape[2])).float().to(self.device)
336
+ labels_padding_mask = labels_attention_mask.unsqueeze(1)
337
+
338
+ text_encoder_output = self.text_encoder(
339
+ input_ids=input_ids,
340
+ padding_mask=input_padding_mask,
341
+ attention_mask=attention_mask,
342
+ output_attentions=output_attentions,
343
+ output_hidden_states=output_hidden_states,
344
+ return_dict=return_dict,
345
+ )
346
+ hidden_states = text_encoder_output[0] if not return_dict else text_encoder_output.last_hidden_state
347
+ hidden_states = hidden_states.transpose(1, 2)
348
+ input_padding_mask = input_padding_mask.transpose(1, 2)
349
+ prior_means = text_encoder_output[1] if not return_dict else text_encoder_output.prior_means
350
+ prior_log_variances = text_encoder_output[2] if not return_dict else text_encoder_output.prior_log_variances
351
+
352
+ latents, posterior_means, posterior_log_variances = self.posterior_encoder(
353
+ labels, labels_padding_mask, speaker_embeddings
354
+ )
355
+ prior_latents = self.flow(latents, labels_padding_mask, speaker_embeddings, reverse=False)
356
+
357
+ prior_means, prior_log_variances = prior_means.transpose(1, 2), prior_log_variances.transpose(1, 2)
358
+ with torch.no_grad():
359
+ # negative cross-entropy
360
+
361
+ # [batch_size, d, latent_length]
362
+ prior_variances = torch.exp(-2 * prior_log_variances)
363
+ # [batch_size, 1, latent_length]
364
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - prior_log_variances, [1], keepdim=True)
365
+ # [batch_size, text_length, d] x [batch_size, d, latent_length] = [batch_size, text_length, latent_length]
366
+ neg_cent2 = torch.matmul(-0.5 * (prior_latents**2).transpose(1, 2), prior_variances)
367
+ # [batch_size, text_length, d] x [batch_size, d, latent_length] = [batch_size, text_length, latent_length]
368
+ neg_cent3 = torch.matmul(prior_latents.transpose(1, 2), (prior_means * prior_variances))
369
+ # [batch_size, 1, latent_length]
370
+ neg_cent4 = torch.sum(-0.5 * (prior_means**2) * prior_variances, [1], keepdim=True)
371
+
372
+ # [batch_size, text_length, latent_length]
373
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
374
+
375
+ attn_mask = torch.unsqueeze(input_padding_mask, 2) * torch.unsqueeze(labels_padding_mask, -1)
376
+
377
+ attn = monotonic_alignment_function(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
378
+
379
+ durations = attn.sum(2)
380
+
381
+ if self.config.use_stochastic_duration_prediction:
382
+ log_duration = self.duration_predictor(
383
+ hidden_states, input_padding_mask, speaker_embeddings, durations=durations, reverse=False
384
+ )
385
+ log_duration = log_duration / torch.sum(input_padding_mask)
386
+ else:
387
+ log_duration_padded = torch.log(durations + 1e-6) * input_padding_mask
388
+ log_duration = self.duration_predictor(hidden_states, input_padding_mask, speaker_embeddings)
389
+ log_duration = torch.sum((log_duration - log_duration_padded) ** 2, [1, 2]) / torch.sum(input_padding_mask)
390
+
391
+ # expand priors
392
+ prior_means = torch.matmul(attn.squeeze(1), prior_means.transpose(1, 2)).transpose(1, 2)
393
+ prior_log_variances = torch.matmul(attn.squeeze(1), prior_log_variances.transpose(1, 2)).transpose(1, 2)
394
+
395
+ label_lengths = labels_attention_mask.sum(dim=1)
396
+ latents_slice, ids_slice = self.rand_slice_segments(latents, label_lengths, segment_size=self.segment_size)
397
+
398
+ waveform = self.decoder(latents_slice, speaker_embeddings)
399
+
400
+ if not return_dict:
401
+ outputs = (
402
+ waveform,
403
+ log_duration,
404
+ attn,
405
+ ids_slice,
406
+ input_padding_mask,
407
+ labels_padding_mask,
408
+ latents,
409
+ prior_latents,
410
+ prior_means,
411
+ prior_log_variances,
412
+ posterior_means,
413
+ posterior_log_variances,
414
+ )
415
+ return outputs
416
+
417
+ return VitsTrainingOutput(
418
+ waveform=waveform,
419
+ log_duration=log_duration,
420
+ attn=attn,
421
+ ids_slice=ids_slice,
422
+ input_padding_mask=input_padding_mask,
423
+ labels_padding_mask=labels_padding_mask,
424
+ latents=latents,
425
+ prior_latents=prior_latents,
426
+ prior_means=prior_means,
427
+ prior_log_variances=prior_log_variances,
428
+ posterior_means=posterior_means,
429
+ posterior_log_variances=posterior_log_variances,
430
+ )
431
+