Transformers 文档

VITS

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

PyTorch

VITS

VITS(Variational Inference with adversarial learning for end-to-end Text-to-Speech)是一个端到端的语音合成模型,简化了传统的两阶段文本到语音(TTS)系统。它的独特之处在于,它利用变分推断、对抗性学习和归一化流直接从文本合成语音,从而产生自然、富有表现力且节奏和语调多样的语音。

你可以在 AI at Meta 组织下找到所有原始的 VITS 检查点。

点击右侧边栏中的 VITS 模型,查看更多关于如何应用 VITS 的示例。

下面的示例演示了如何使用 PipelineAutoModel 类基于图像生成文本。

流水线
自动模型
import torch
from transformers import pipeline, set_seed
from scipy.io.wavfile import write

set_seed(555)

pipe = pipeline(
    task="text-to-speech",
    model="facebook/mms-tts-eng",
    torch_dtype=torch.float16,
    device=0
)

speech = pipe("Hello, my dog is cute")

# Extract audio data and sampling rate
audio_data = speech["audio"]
sampling_rate = speech["sampling_rate"]

# Save as WAV file
write("hello.wav", sampling_rate, audio_data.squeeze())

注意事项

  • 由于 VITS 是非确定性地合成语音,请设置一个种子以确保可复现性。

  • 对于使用非罗马字母的语言(如韩语、阿拉伯语等),请安装 uroman 包,将文本输入预处理为罗马字母。你可以通过以下方式检查分词器是否需要 uroman。

    # pip install -U uroman
    from transformers import VitsTokenizer
    
    tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
    print(tokenizer.is_uroman)

    如果你的语言需要 uroman,分词器会自动将其应用于文本输入。Python >= 3.10 不需要任何额外的预处理步骤。对于 Python < 3.10,请按照以下步骤操作。

    git clone https://github.com/isi-nlp/uroman.git
    cd uroman
    export UROMAN=$(pwd)

    创建一个函数来预处理输入。你可以使用 bash 变量 UROMAN 或直接将目录路径传递给该函数。

    import torch
    from transformers import VitsTokenizer, VitsModel, set_seed
    import os
    import subprocess
    
    tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-kor")
    model = VitsModel.from_pretrained("facebook/mms-tts-kor")
    
    def uromanize(input_string, uroman_path):
        """Convert non-Roman strings to Roman using the `uroman` perl package."""
        script_path = os.path.join(uroman_path, "bin", "uroman.pl")
    
        command = ["perl", script_path]
    
        process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        # Execute the perl command
        stdout, stderr = process.communicate(input=input_string.encode())
    
        if process.returncode != 0:
            raise ValueError(f"Error {process.returncode}: {stderr.decode()}")
    
        # Return the output as a string and skip the new-line character at the end
        return stdout.decode()[:-1]
    
    text = "이봐 무슨 일이야"
    uromanized_text = uromanize(text, uroman_path=os.environ["UROMAN"])
    
    inputs = tokenizer(text=uromanized_text, return_tensors="pt")
    
    set_seed(555)  # make deterministic
    with torch.no_grad():
       outputs = model(inputs["input_ids"])
    
    waveform = outputs.waveform[0]

VitsConfig

class transformers.VitsConfig

< >

( vocab_size = 38 hidden_size = 192 num_hidden_layers = 6 num_attention_heads = 2 window_size = 4 use_bias = True ffn_dim = 768 layerdrop = 0.1 ffn_kernel_size = 3 flow_size = 192 spectrogram_bins = 513 hidden_act = 'relu' hidden_dropout = 0.1 attention_dropout = 0.1 activation_dropout = 0.1 initializer_range = 0.02 layer_norm_eps = 1e-05 use_stochastic_duration_prediction = True num_speakers = 1 speaker_embedding_size = 0 upsample_initial_channel = 512 upsample_rates = [8, 8, 2, 2] upsample_kernel_sizes = [16, 16, 4, 4] resblock_kernel_sizes = [3, 7, 11] resblock_dilation_sizes = [[1, 3, 5], [1, 3, 5], [1, 3, 5]] leaky_relu_slope = 0.1 depth_separable_channels = 2 depth_separable_num_layers = 3 duration_predictor_flow_bins = 10 duration_predictor_tail_bound = 5.0 duration_predictor_kernel_size = 3 duration_predictor_dropout = 0.5 duration_predictor_num_flows = 4 duration_predictor_filter_channels = 256 prior_encoder_num_flows = 4 prior_encoder_num_wavenet_layers = 4 posterior_encoder_num_wavenet_layers = 16 wavenet_kernel_size = 5 wavenet_dilation_rate = 1 wavenet_dropout = 0.0 speaking_rate = 1.0 noise_scale = 0.667 noise_scale_duration = 0.8 sampling_rate = 16000 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 38) — VITS 模型的词汇表大小。定义了传递给 VitsModel 的 forward 方法的 `inputs_ids` 可以表示的不同标记的数量。
  • hidden_size (int, 可选, 默认为 192) — 文本编码器层的维度。
  • num_hidden_layers (int, 可选, 默认为 6) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 2) — Transformer 编码器中每个注意力层的注意力头数量。
  • window_size (int, 可选, 默认为 4) — Transformer 编码器注意力层中相对位置编码的窗口大小。
  • use_bias (bool, 可选, 默认为 True) — 是否在 Transformer 编码器的键(key)、查询(query)、值(value)投影层中使用偏置。
  • ffn_dim (int, 可选, 默认为 768) — Transformer 编码器中“中间”(即前馈)层的维度。
  • layerdrop (float, 可选, 默认为 0.1) — 编码器的 LayerDrop 概率。更多详情请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • ffn_kernel_size (int, 可选, 默认为 3) — Transformer 编码器中前馈网络使用的一维卷积层的核大小。
  • flow_size (int, 可选, 默认为 192) — 流(flow)层的维度。
  • spectrogram_bins (int, 可选, 默认为 513) — 目标频谱图中的频率仓(bin)数量。
  • hidden_act (strfunction, 可选, 默认为 "relu") — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout (float, 可选, 默认为 0.1) — 嵌入层和编码器中所有全连接层的丢弃概率。
  • attention_dropout (float, 可选, 默认为 0.1) — 注意力概率的丢弃率。
  • activation_dropout (float, 可选, 默认为 0.1) — 全连接层内激活函数的丢弃率。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
  • use_stochastic_duration_prediction (bool, 可选, 默认为 True) — 是否使用随机时长预测模块或常规时长预测器。
  • num_speakers (int, 可选, 默认为 1) — 如果是多说话人模型,则为说话人的数量。
  • speaker_embedding_size (int, 可选, 默认为 0) — 说话人嵌入使用的通道数。对于单说话人模型,此值为零。
  • upsample_initial_channel (int, 可选, 默认为 512) — HiFi-GAN 上采样网络的输入通道数。
  • upsample_rates (tuple[int]list[int], 可选, 默认为 [8, 8, 2, 2]) — 定义 HiFi-GAN 上采样网络中每个一维卷积层步幅的整数元组。`upsample_rates` 的长度定义了卷积层的数量,并且必须与 `upsample_kernel_sizes` 的长度匹配。
  • upsample_kernel_sizes (tuple[int]list[int], 可选, 默认为 [16, 16, 4, 4]) — 定义 HiFi-GAN 上采样网络中每个一维卷积层核大小的整数元组。`upsample_kernel_sizes` 的长度定义了卷积层的数量,并且必须与 `upsample_rates` 的长度匹配。
  • resblock_kernel_sizes (tuple[int]list[int], 可选, 默认为 [3, 7, 11]) — 定义 HiFi-GAN 多感受野融合(MRF)模块中一维卷积层核大小的整数元组。
  • resblock_dilation_sizes (tuple[tuple[int]]list[list[int]], 可选, 默认为 [[1, 3, 5], [1, 3, 5], [1, 3, 5]]) — 定义 HiFi-GAN 多感受野融合(MRF)模块中扩张一维卷积层扩张率的嵌套整数元组。
  • leaky_relu_slope (float, 可选, 默认为 0.1) — Leaky ReLU 激活函数使用的负斜率角度。
  • depth_separable_channels (int, 可选, 默认为 2) — 每个深度可分离块中使用的通道数。
  • depth_separable_num_layers (int, 可选, 默认为 3) — 每个深度可分离块中使用的卷积层数。
  • duration_predictor_flow_bins (int, 可选, 默认为 10) — 在时长预测器模型中使用非约束有理样条映射的通道数。
  • duration_predictor_tail_bound (float, 可选, 默认为 5.0) — 在时长预测器模型中计算非约束有理样条时,尾部仓(tail bin)边界的值。
  • duration_predictor_kernel_size (int, 可选, 默认为 3) — 时长预测器模型中使用的一维卷积层的核大小。
  • duration_predictor_dropout (float, 可选, 默认为 0.5) — 时长预测器模型的丢弃率。
  • duration_predictor_num_flows (int, 可选, 默认为 4) — 时长预测器模型使用的流(flow)阶段数。
  • duration_predictor_filter_channels (int, 可选, 默认为 256) — 时长预测器模型中使用的卷积层的通道数。
  • prior_encoder_num_flows (int, 可选, 默认为 4) — 先验编码器流模型使用的流阶段数。
  • prior_encoder_num_wavenet_layers (int, 可选, 默认为 4) — 先验编码器流模型使用的 WaveNet 层数。
  • posterior_encoder_num_wavenet_layers (int, 可选, 默认为 16) — 后验编码器模型使用的 WaveNet 层数。
  • wavenet_kernel_size (int, 可选, 默认为 5) — WaveNet 模型中使用的一维卷积层的核大小。
  • wavenet_dilation_rate (int, 可选, 默认为 1) — WaveNet 模型中使用的扩张一维卷积层的扩张率。
  • wavenet_dropout (float, 可选, 默认为 0.0) — WaveNet 层的丢弃率。
  • speaking_rate (float, 可选, 默认为 1.0) — 语速。值越大,合成的语音速度越快。
  • noise_scale (float, 可选, 默认为 0.667) — 语音预测的随机性。值越大,预测的语音变化越多。
  • noise_scale_duration (float, 可选, 默认为 0.8) — 持续时间预测的随机性。值越大,预测的持续时间变化越多。
  • sampling_rate (int, 可选, 默认为 16000) — 输出音频波形数字化的采样率,以赫兹 (Hz) 表示。

这是用于存储 VitsModel 配置的配置类。它用于根据指定的参数实例化一个 VITS 模型,定义模型架构。使用默认值实例化配置将产生与 VITS facebook/mms-tts-eng 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

示例

>>> from transformers import VitsModel, VitsConfig

>>> # Initializing a "facebook/mms-tts-eng" style configuration
>>> configuration = VitsConfig()

>>> # Initializing a model (with random weights) from the "facebook/mms-tts-eng" style configuration
>>> model = VitsModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

VitsTokenizer

class transformers.VitsTokenizer

< >

( vocab_file pad_token = '<pad>' unk_token = '<unk>' language = None add_blank = True normalize = True phonemize = True is_uroman = False **kwargs )

参数

  • vocab_file (str) — 词汇文件的路径。
  • language (str, 可选) — 语言标识符。
  • add_blank (bool, 可选, 默认为 True) — 是否在其他词元之间插入词元ID 0。
  • normalize (bool, 可选, 默认为 True) — 是否通过移除所有大小写和标点符号来规范化输入文本。
  • phonemize (bool, 可选, 默认为 True) — 是否将输入文本转换为音素。
  • is_uroman (bool, 可选, 默认为 False) — 在分词之前是否需要对输入文本应用 uroman 罗马化工具。

构建一个 VITS 分词器。也支持 MMS-TTS。

该分词器继承自 PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

normalize_text

< >

( input_string )

将输入字符串转换为小写,同时尊重任何可能部分或全部大写的特殊词元ID。

prepare_for_tokenization

< >

( text: str is_split_into_words: bool = False normalize: typing.Optional[bool] = None **kwargs ) tuple[str, dict[str, Any]]

参数

  • text (str) — 待准备的文本。
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,拆分成单词)。如果设置为 True,分词器将假定输入已被拆分成单词(例如,通过在空白处分割),然后对其进行分词。
  • normalize (bool, 可选, 默认为 None) — 是否对输入文本应用标点和大小写规范化。通常,VITS 在小写且无标点的文本上训练。因此,使用规范化以确保输入文本仅包含小写字符。
  • kwargs (dict[str, Any], 可选) — 用于分词的关键字参数。

返回

tuple[str, dict[str, Any]]

准备好的文本和未使用的kwargs。

在分词前执行任何必要的转换。

该方法应从 kwargs 中弹出参数,并返回剩余的 kwargs。我们在编码过程结束时测试 kwargs,以确保所有参数都已使用。

  • 调用
  • save_vocabulary

VitsModel

class transformers.VitsModel

< >

( config: VitsConfig )

参数

  • config (VitsConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。

完整的 VITS 模型,用于文本到语音的合成。

此模型继承自 PreTrainedModel。请查阅超类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 的子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与一般用法和行为相关的事项。

forward

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None speaker_id: typing.Optional[int] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None labels: typing.Optional[torch.FloatTensor] = None ) transformers.models.vits.modeling_vits.VitsModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.Tensor,形状为 (batch_size, sequence_length)可选) — 词汇表中输入序列词元的索引。默认情况下会忽略填充。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length)可选) — 用于避免对填充词元索引执行注意力操作的掩码。掩码值选自 [0, 1]

    • 1 表示词元未被遮盖
    • 0 表示词元被遮盖

    什么是注意力掩码?

  • speaker_id (int, 可选) — 使用哪个说话人嵌入。仅用于多说话人模型。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
  • labels (torch.FloatTensor,形状为 (batch_size, config.spectrogram_bins, sequence_length)可选) — 目标频谱图的浮点值。设置为 -100.0 的时间步在损失计算中被忽略(遮盖)。

返回

transformers.models.vits.modeling_vits.VitsModelOutputtuple(torch.FloatTensor)

一个 transformers.models.vits.modeling_vits.VitsModelOutput 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置 (VitsConfig) 和输入包含不同的元素。

  • waveform (torch.FloatTensor,形状为 (batch_size, sequence_length)) — 模型预测的最终音频波形。

  • sequence_lengths (torch.FloatTensor,形状为 (batch_size,)) — waveform 批次中每个元素的样本长度。

  • spectrogram (torch.FloatTensor,形状为 (batch_size, sequence_length, num_bins)) — 在流模型输出处预测的对数梅尔频谱图。此频谱图被传递给 Hi-Fi GAN 解码器模型以获得最终的音频波形。

  • hidden_states (tuple[torch.FloatTensor], 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor], 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

VitsModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的逻辑需要在此函数内定义,但之后应调用 Module 实例而不是此函数,因为前者会处理预处理和后处理步骤,而后者会静默忽略它们。

示例

>>> from transformers import VitsTokenizer, VitsModel, set_seed
>>> import torch

>>> tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng")
>>> model = VitsModel.from_pretrained("facebook/mms-tts-eng")

>>> inputs = tokenizer(text="Hello - my dog is cute", return_tensors="pt")

>>> set_seed(555)  # make deterministic

>>> with torch.no_grad():
...     outputs = model(inputs["input_ids"])
>>> outputs.waveform.shape
torch.Size([1, 45824])
  • forward
< > 在 GitHub 上更新