Spaces:
Sleeping
Sleeping
Update VitsModelSplit/vits_models_only_decoder.py
Browse files
VitsModelSplit/vits_models_only_decoder.py
CHANGED
|
@@ -14,20 +14,68 @@ 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:
|
|
@@ -37,188 +85,83 @@ class Vits_models_only_decoder(VitsPreTrainedModel):
|
|
| 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
|
| 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 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 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 |
-
|
| 181 |
-
self.text_encoder.set_input_embeddings(value)
|
| 182 |
|
| 183 |
-
|
| 184 |
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
self.posterior_encoder.apply_weight_norm()
|
| 189 |
|
| 190 |
-
|
|
|
|
| 191 |
|
| 192 |
-
|
| 193 |
-
self.decoder.remove_weight_norm()
|
| 194 |
-
self.flow.remove_weight_norm()
|
| 195 |
-
self.posterior_encoder.remove_weight_norm()
|
| 196 |
|
| 197 |
-
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
|
|
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
|
|
|
|
|
|
| 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=
|
| 222 |
attention_mask=attention_mask,
|
| 223 |
output_attentions=output_attentions,
|
| 224 |
output_hidden_states=output_hidden_states,
|
|
@@ -226,8 +169,7 @@ class Vits_models_only_decoder(VitsPreTrainedModel):
|
|
| 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 =
|
| 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 |
|
|
@@ -246,7 +188,6 @@ class Vits_models_only_decoder(VitsPreTrainedModel):
|
|
| 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)
|
|
@@ -271,61 +212,18 @@ class Vits_models_only_decoder(VitsPreTrainedModel):
|
|
| 271 |
|
| 272 |
spectrogram = latents * output_padding_mask
|
| 273 |
return spectrogram
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
self
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 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 |
-
|
|
|
|
| 14 |
from .posterior_encoder import VitsPosteriorEncoder
|
| 15 |
from .discriminator import VitsDiscriminator
|
| 16 |
from .vits_output import VitsModelOutput, VitsTrainingOutput
|
| 17 |
+
_CONFIG_FOR_DOC = "VitsConfig"
|
| 18 |
+
|
| 19 |
+
VITS_START_DOCSTRING = r"""
|
| 20 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 21 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 22 |
+
etc.)
|
| 23 |
+
|
| 24 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 25 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 26 |
+
and behavior.
|
| 27 |
+
|
| 28 |
+
Parameters:
|
| 29 |
+
config ([`VitsConfig`]):
|
| 30 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 31 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 32 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
VITS_INPUTS_DOCSTRING = r"""
|
| 37 |
+
Args:
|
| 38 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 39 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 40 |
+
it.
|
| 41 |
+
|
| 42 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 43 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 44 |
+
|
| 45 |
+
[What are input IDs?](../glossary#input-ids)
|
| 46 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 47 |
+
Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,
|
| 48 |
+
1]`:
|
| 49 |
+
|
| 50 |
+
- 1 for tokens that are **not masked**,
|
| 51 |
+
- 0 for tokens that are **masked**.
|
| 52 |
+
|
| 53 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 54 |
+
speaker_id (`int`, *optional*):
|
| 55 |
+
Which speaker embedding to use. Only used for multispeaker models.
|
| 56 |
+
output_attentions (`bool`, *optional*):
|
| 57 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 58 |
+
tensors for more detail.
|
| 59 |
+
output_hidden_states (`bool`, *optional*):
|
| 60 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 61 |
+
more detail.
|
| 62 |
+
return_dict (`bool`, *optional*):
|
| 63 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@add_start_docstrings(
|
| 68 |
+
"The complete VITS model, for text-to-speech synthesis.",
|
| 69 |
+
VITS_START_DOCSTRING,
|
| 70 |
+
)
|
| 71 |
class Vits_models_only_decoder(VitsPreTrainedModel):
|
|
|
|
| 72 |
def __init__(self, config: VitsConfig):
|
| 73 |
super().__init__(config)
|
|
|
|
| 74 |
self.config = config
|
| 75 |
self.text_encoder = VitsTextEncoder(config)
|
| 76 |
self.flow = VitsResidualCouplingBlock(config)
|
| 77 |
self.decoder = VitsHifiGan(config)
|
| 78 |
|
|
|
|
|
|
|
| 79 |
if config.use_stochastic_duration_prediction:
|
| 80 |
self.duration_predictor = VitsStochasticDurationPredictor(config)
|
| 81 |
else:
|
|
|
|
| 85 |
self.embed_speaker = nn.Embedding(config.num_speakers, config.speaker_embedding_size)
|
| 86 |
|
| 87 |
# This is used only for training.
|
| 88 |
+
# self.posterior_encoder = VitsPosteriorEncoder(config)
|
|
|
|
| 89 |
|
| 90 |
# These parameters control the synthesised speech properties
|
| 91 |
self.speaking_rate = config.speaking_rate
|
| 92 |
self.noise_scale = config.noise_scale
|
| 93 |
self.noise_scale_duration = config.noise_scale_duration
|
|
|
|
| 94 |
|
| 95 |
# Initialize weights and apply final processing
|
| 96 |
self.post_init()
|
| 97 |
|
| 98 |
+
def get_encoder(self):
|
| 99 |
+
return self.text_encoder
|
| 100 |
|
| 101 |
+
@add_start_docstrings_to_model_forward(VITS_INPUTS_DOCSTRING)
|
| 102 |
+
@replace_return_docstrings(output_type=VitsModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 103 |
+
def forward(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
self,
|
| 105 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 106 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 107 |
+
speaker_id: Optional[int] = None,
|
| 108 |
+
output_attentions: Optional[bool] = None,
|
| 109 |
+
output_hidden_states: Optional[bool] = None,
|
| 110 |
+
return_dict: Optional[bool] = None,
|
| 111 |
+
labels: Optional[torch.FloatTensor] = None,
|
| 112 |
+
) -> Union[Tuple[Any], VitsModelOutput]:
|
| 113 |
+
r"""
|
| 114 |
+
labels (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`, *optional*):
|
| 115 |
+
Float values of target spectrogram. Timesteps set to `-100.0` are ignored (masked) for the loss
|
| 116 |
+
computation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
Returns:
|
|
|
|
| 119 |
|
| 120 |
+
Example:
|
| 121 |
|
| 122 |
+
```python
|
| 123 |
+
>>> from transformers import VitsTokenizer, VitsModel, set_seed
|
| 124 |
+
>>> import torch
|
|
|
|
| 125 |
|
| 126 |
+
>>> tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
|
| 127 |
+
>>> model = VitsModel.from_pretrained("facebook/mms-tts-eng")
|
| 128 |
|
| 129 |
+
>>> inputs = tokenizer(text="Hello - my dog is cute", return_tensors="pt")
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
>>> set_seed(555) # make deterministic
|
| 132 |
|
| 133 |
+
>>> with torch.no_grad():
|
| 134 |
+
... outputs = model(inputs["input_ids"])
|
| 135 |
+
>>> outputs.waveform.shape
|
| 136 |
+
torch.Size([1, 45824])
|
| 137 |
+
```
|
| 138 |
+
"""
|
| 139 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 140 |
+
output_hidden_states = (
|
| 141 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 142 |
+
)
|
| 143 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 144 |
|
| 145 |
+
if labels is not None:
|
| 146 |
+
raise NotImplementedError("Training of VITS is not supported yet.")
|
| 147 |
|
| 148 |
+
if attention_mask is not None:
|
| 149 |
+
input_padding_mask = attention_mask.unsqueeze(-1).float()
|
| 150 |
+
else:
|
| 151 |
+
input_padding_mask = torch.ones_like(input_ids).unsqueeze(-1).float()
|
| 152 |
|
| 153 |
+
if self.config.num_speakers > 1 and speaker_id is not None:
|
| 154 |
+
if not 0 <= speaker_id < self.config.num_speakers:
|
| 155 |
+
raise ValueError(f"Set `speaker_id` in the range 0-{self.config.num_speakers - 1}.")
|
| 156 |
+
if isinstance(speaker_id, int):
|
| 157 |
+
speaker_id = torch.full(size=(1,), fill_value=speaker_id, device=self.device)
|
| 158 |
+
speaker_embeddings = self.embed_speaker(speaker_id).unsqueeze(-1)
|
| 159 |
+
else:
|
| 160 |
+
speaker_embeddings = None
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
text_encoder_output = self.text_encoder(
|
| 163 |
input_ids=input_ids,
|
| 164 |
+
padding_mask=input_padding_mask,
|
| 165 |
attention_mask=attention_mask,
|
| 166 |
output_attentions=output_attentions,
|
| 167 |
output_hidden_states=output_hidden_states,
|
|
|
|
| 169 |
)
|
| 170 |
hidden_states = text_encoder_output[0] if not return_dict else text_encoder_output.last_hidden_state
|
| 171 |
hidden_states = hidden_states.transpose(1, 2)
|
| 172 |
+
input_padding_mask = input_padding_mask.transpose(1, 2)
|
|
|
|
| 173 |
prior_means = text_encoder_output[1] if not return_dict else text_encoder_output.prior_means
|
| 174 |
prior_log_variances = text_encoder_output[2] if not return_dict else text_encoder_output.prior_log_variances
|
| 175 |
|
|
|
|
| 188 |
duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
|
| 189 |
predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
|
| 190 |
|
|
|
|
| 191 |
# Create a padding mask for the output lengths of shape (batch, 1, max_output_length)
|
| 192 |
indices = torch.arange(predicted_lengths.max(), dtype=predicted_lengths.dtype, device=predicted_lengths.device)
|
| 193 |
output_padding_mask = indices.unsqueeze(0) < predicted_lengths.unsqueeze(1)
|
|
|
|
| 212 |
|
| 213 |
spectrogram = latents * output_padding_mask
|
| 214 |
return spectrogram
|
| 215 |
+
# waveform = self.decoder(spectrogram, speaker_embeddings)
|
| 216 |
+
# waveform = waveform.squeeze(1)
|
| 217 |
+
# sequence_lengths = predicted_lengths * np.prod(self.config.upsample_rates)
|
| 218 |
+
|
| 219 |
+
# if not return_dict:
|
| 220 |
+
# outputs = (waveform, sequence_lengths, spectrogram) + text_encoder_output[3:]
|
| 221 |
+
# return outputs
|
| 222 |
+
|
| 223 |
+
# return VitsModelOutput(
|
| 224 |
+
# waveform=waveform,
|
| 225 |
+
# sequence_lengths=sequence_lengths,
|
| 226 |
+
# spectrogram=spectrogram,
|
| 227 |
+
# hidden_states=text_encoder_output.hidden_states,
|
| 228 |
+
# attentions=text_encoder_output.attentions,
|
| 229 |
+
# )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|