Transformers documentation
VITS
该模型于 2021-06-11 在 HF papers 上发布,并于 2023-09-01 贡献至 Hugging Face Transformers。
VITS
VITS(用于端到端文本转语音的变分推断与对抗学习) 是一种端到端语音合成模型,简化了传统的两阶段文本转语音(TTS)系统。其独特之处在于,它利用变分推断、对抗学习和归一化流直接从文本合成语音,从而生成具有多样化节奏和语调的自然且富有表现力的语音。
您可以在 AI at Meta 组织下找到所有原始的 VITS 检查点。
点击右侧边栏中的 VITS 模型,以查看更多有关如何应用 VITS 的示例。
以下示例演示了如何使用 Pipeline 或 AutoModel 类基于图像生成文本。
from scipy.io.wavfile import write
from transformers import pipeline, set_seed
set_seed(555)
pipe = pipeline(
task="text-to-speech",
model="facebook/mms-tts-eng",
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())import scipy
import torch
from IPython.display import Audio
from transformers import AutoTokenizer, VitsModel, set_seed
tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-eng")
model = VitsModel.from_pretrained("facebook/mms-tts-eng", device_map="auto")
inputs = tokenizer("Hello, my dog is cute", return_tensors="pt").to(model.device)
set_seed(555)
with torch.no_grad():
outputs = model(**inputs)
waveform = outputs.waveform[0]
scipy.io.wavfile.write("hello.wav", rate=model.config.sampling_rate, data=waveform)
# display in Colab notebook
Audio(waveform, rate=model.config.sampling_rate)备注
由于 VITS 以非确定性方式合成语音,请设置随机种子以确保可复现性。
对于使用非拉丁字母的语言(如韩语、阿拉伯语等),请安装 uroman 包,将文本输入预处理为拉丁字母。您可以按照以下方法检查分词器是否需要 uroman。
# pip install -U uroman from transformers import VitsTokenizer tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng") print(tokenizer.is_uroman)如果您的语言需要 uroman,分词器会自动将其应用于文本输入。
VitsConfig
class transformers.VitsConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 38hidden_size: int = 192num_hidden_layers: int = 6num_attention_heads: int = 2window_size: int = 4use_bias: bool = Trueffn_dim: int = 768layerdrop: float | int = 0.1ffn_kernel_size: int = 3flow_size: int = 192spectrogram_bins: int = 513hidden_act: str = 'relu'hidden_dropout: float | int = 0.1attention_dropout: float | int = 0.1activation_dropout: float | int = 0.1initializer_range: float = 0.02layer_norm_eps: float = 1e-05use_stochastic_duration_prediction: bool = Truenum_speakers: int = 1speaker_embedding_size: int = 0upsample_initial_channel: int = 512upsample_rates: list[int] | tuple[int, ...] = (8, 8, 2, 2)upsample_kernel_sizes: list[int] | tuple[int, ...] = (16, 16, 4, 4)resblock_kernel_sizes: list[int] | tuple[int, ...] = (3, 7, 11)resblock_dilation_sizes: list | tuple = ((1, 3, 5), (1, 3, 5), (1, 3, 5))leaky_relu_slope: float = 0.1depth_separable_channels: int = 2depth_separable_num_layers: int = 3duration_predictor_flow_bins: int = 10duration_predictor_tail_bound: float = 5.0duration_predictor_kernel_size: int = 3duration_predictor_dropout: float | int = 0.5duration_predictor_num_flows: int = 4duration_predictor_filter_channels: int = 256prior_encoder_num_flows: int = 4prior_encoder_num_wavenet_layers: int = 4posterior_encoder_num_wavenet_layers: int = 16wavenet_kernel_size: int = 5wavenet_dilation_rate: int = 1wavenet_dropout: float | int = 0.0speaking_rate: float | int = 1.0noise_scale: float = 0.667noise_scale_duration: float = 0.8sampling_rate: int = 16000pad_token_id: int | None = None )
参数
- vocab_size (
int,可选,默认为38) — 模型的词汇表大小。定义了input_ids可以表示的不同 token 的数量。 - 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) — MLP 表示的维度。 - layerdrop (
Union[float, int],可选,默认为0.1) — LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。 - ffn_kernel_size (
int, 可选,默认为 3) — Transformer 编码器中前馈网络所使用的 1D 卷积层的卷积核大小。 - flow_size (
int,可选,默认为 192) — 流层的维度。 - spectrogram_bins (
int,可选,默认为 513) — 目标频谱图中的频率 bin 数量。 - hidden_act (
str,可选,默认为relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - hidden_dropout (
Union[float, int],可选,默认为0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - attention_dropout (
Union[float, int],可选,默认为0.1) — 注意力概率的 dropout 比率。 - activation_dropout (
Union[float, int],可选,默认为0.1) — 全连接层内部激活值的 dropout 比率。 - 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) — 在时长预测器模型中计算无约束有理样条时,尾部 bin 边界的值。 - duration_predictor_kernel_size (
int, 可选,默认为 3) — 时长预测器模型中使用的 1D 卷积层的卷积核大小。 - duration_predictor_dropout (
float, 可选,默认为 0.5) — 时长预测器模型的 dropout 比率。 - 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 模型中使用的 1D 卷积层的卷积核大小。 - wavenet_dilation_rate (
int, 可选,默认为 1) — WaveNet 模型中使用的膨胀一维卷积层的膨胀率。 - wavenet_dropout (
float, 可选,默认值为 0.0) — WaveNet 层的 dropout 比率。 - speaking_rate (
float,可选,默认为 1.0) — 语速。值越大,合成的语音速度越快。 - noise_scale (
float,可选,默认值为 0.667) — 语音预测的随机程度。值越大,预测语音的变化越多。 - noise_scale_duration (
float,可选,默认值为 0.8) — 时长预测的随机程度。值越大,预测时长的变化范围越大。 - sampling_rate (
int,可选,默认为16000) — 音频文件应被数字化时的采样率,以赫兹(Hz)为单位。 - pad_token_id (
int, 可选) — 词表中用于填充的 token id。
这是用于存储 VitsModel 配置的类。它根据指定的参数实例化 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.configVitsTokenizer
class transformers.VitsTokenizer
< source >( vocab_filepad_token = '<pad>'unk_token = '<unk>'language = Noneadd_blank = Truenormalize = Truephonemize = Trueis_uroman = False**kwargs )
构建 VITS 分词器。同时支持 MMS-TTS。
该分词器继承自 PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考该父类以获取有关这些方法的更多信息。
__call__
< source >( text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Nonetext_pair: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Nonetext_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Nonetext_pair_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Noneadd_special_tokens: bool = Truepadding: bool | str | PaddingStrategy = Falsetruncation: bool | str | TruncationStrategy | None = Nonemax_length: int | None = Nonestride: int = 0is_split_into_words: bool = Falsepad_to_multiple_of: int | None = Nonepadding_side: str | None = Nonereturn_tensors: str | TensorType | None = Nonereturn_token_type_ids: bool | None = Nonereturn_attention_mask: bool | None = Nonereturn_overflowing_tokens: bool = Falsereturn_special_tokens_mask: bool = Falsereturn_offsets_mapping: bool = Falsereturn_length: bool = Falseverbose: bool = Truetokenizer_kwargs: dict[str, Any] | None = None**kwargs ) → BatchEncoding
参数
- text (
str、list[str]、list[list[str]]、可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)形式提供序列,则必须设置is_split_into_words=True(以消除与序列批次的歧义)。 - text_pair (
str、list[str]、list[list[str]]、可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)形式提供序列,则必须设置is_split_into_words=True(以消除与序列批次的歧义)。 - text_target (
str、list[str]、list[list[str]]、可选) — 要编码为目标文本的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)的形式提供序列,则必须设置is_split_into_words=True(以消除与序列批次的歧义)。 - text_pair_target (
str、list[str]、list[list[str]]、可选) — 要编码为目标文本的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果序列以字符串列表(预分词)的形式提供,则必须设置is_split_into_words=True(以消除与序列批次的歧义)。 - tokenizer_kwargs (
dict[str, Any], 可选) — 传递给 tokenizer 的额外 kwargs。这些 kwargs 将与显式参数及其他 kwargs 合并,其中显式参数具有更高的优先级。 - add_special_tokens (
bool,可选,默认为True) — 在编码序列时是否添加特殊标记。此操作将使用底层的PretrainedTokenizerBase.build_inputs_with_special_tokens函数,该函数定义了哪些标记会自动添加到输入 ID 中。如果您希望自动添加bos或eos标记,此功能非常有用。 - padding (
bool,str或 PaddingStrategy, ,可选, ,默认为False) — 启用并控制填充。接受以下值:True或'longest':填充至批次中最长的序列(如果仅提供单个序列,则不进行填充)。'max_length':填充至由参数max_length指定的最大长度;若未提供该参数,则填充至模型可接受的最大输入长度。False或'do_not_pad'(默认值):不进行填充(即可以输出包含不同长度序列的批次)。
- truncation (
bool,str或 TruncationStrategy, ,可选, ,默认为False) — 启用并控制截断。接受以下值:True或'longest_first':截断至由参数max_length指定的最大长度,或者如果未提供该参数,则截断至模型可接受的最大输入长度。这将逐个 token 进行截断,如果提供了一对序列(或一批序列对),则会从该对中最长的序列中移除一个 token。'only_first':截断至由参数max_length指定的最大长度,或者在未提供该参数时,截断至模型可接受的最大输入长度。如果提供了一对序列(或一批序列对),则仅截断其中的第一个序列。'only_second':截断至由参数max_length指定的最大长度,或者如果未提供该参数,则截断至模型可接受的最大输入长度。仅当提供了一对序列(或一批序列对)时,才会截断其中的第二个序列。False或'do_not_truncate'(默认值):不进行截断(即,可以输出序列长度大于模型最大可接受输入大小的批次)。
- max_length (
int, 可选) — 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 None,则当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(如 XLNet),则禁用截断/填充到最大长度的功能。如果未设置或设置为
None,当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(例如 XLNet),则禁用截断/填充至最大长度的功能。 - stride (
int,可选,默认为 0) — 如果与max_length一起设置为某个数值,则当return_overflowing_tokens=True时,返回的溢出 token 将包含截断序列末尾的若干 token,以在截断序列和溢出序列之间提供一定的重叠。此参数的值定义了重叠 token 的数量。 - is_split_into_words (
bool,可选,默认为False) — 输入是否已经预先分词(例如,已拆分为单词)。如果设置为True,分词器将假设输入已经拆分为单词(例如,通过按空白字符拆分),然后对其进行分词。这对于命名实体识别(NER)或 token 分类非常有用。 - pad_to_multiple_of (
int, 可选) — 如果设置,则将序列填充为所提供值的倍数。需要启用padding。 这对于在计算能力为>= 7.5(Volta)的 NVIDIA 硬件上启用 Tensor Cores 的使用特别有用。 - padding_side (
str, 可选) — 模型应应用填充的一侧。应在 [‘right’, ‘left’] 之间进行选择。 默认值取自同名的类属性。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回张量而不是 Python 整数列表。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 Numpynp.ndarray对象。
- return_token_type_ids (
bool, 可选) — 是否返回 token type ID。如果保持默认值,将根据特定分词器的默认设置返回 token type ID,该设置由return_outputs属性定义。 - return_attention_mask (
bool, 可选) — 是否返回注意力掩码。如果保持默认值,将根据特定分词器的默认设置返回注意力掩码,该设置由return_outputs属性定义。 - return_overflowing_tokens (
bool,可选,默认为False) — 是否返回溢出的 token 序列。如果提供了输入 id 的序列对(或序列对批次),且truncation_strategy = longest_first或True,则会抛出错误,而不是返回溢出的 token。 - return_special_tokens_mask (
bool,可选,默认为False) — 是否返回特殊 token 掩码信息。 - return_offsets_mapping (
bool, 可选, 默认为False) — 是否返回(char_start, char_end)每个 token 的。此功能仅在继承自 PreTrainedTokenizerFast 的快速分词器上可用。如果使用 Python 分词器,此方法将抛出
NotImplementedError。 - return_length (
bool,可选,默认为False) — 是否返回编码后输入的长度。 - verbose (
bool,可选,默认为True) — 是否打印更多信息和警告。 - **kwargs — 传递给
self.tokenize()方法
返回值
一个包含以下字段的 BatchEncoding:
-
input_ids — 要输入模型的 token id 列表。
-
token_type_ids — 要输入模型的 token 类型 ID 列表(当
return_token_type_ids=True或self.model_input_names中包含 “token_type_ids” 时)。 -
attention_mask — 索引列表,指定模型应关注哪些 token(当
return_attention_mask=True或 “attention_mask” 位于self.model_input_names中时)。 -
overflowing_tokens — 溢出 token 序列的列表(当指定了
max_length且return_overflowing_tokens=True时)。 -
num_truncated_tokens — 被截断的 token 数量(当指定了
max_length且return_overflowing_tokens=True时)。 -
special_tokens_mask — 由 0 和 1 组成的列表,其中 1 表示添加的特殊标记,0 表示常规序列标记(当
add_special_tokens=True且return_special_tokens_mask=True时)。 -
length — 输入的长度(当
return_length=True时)
用于对一条或多条序列,或一对或多对序列进行分词并准备输入模型的主要方法。
VitsModel
class transformers.VitsModel
< source >( config: VitsConfig )
参数
- config (VitsConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
完整的 VITS 模型,用于文本转语音合成。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonespeaker_id: int | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = Nonelabels: typing.Optional[torch.Tensor] = Nonespeaking_rate: float | None = None**kwargs ) → VitsModelOutput or tuple(torch.Tensor)
参数
- input_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- speaker_id (
int,可选) — 要使用的说话人嵌入。仅用于多说话人模型。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels(形状为
(batch_size, config.spectrogram_bins, sequence_length)的torch.Tensor,可选) — 目标频谱图的浮点数值。时间步设置为-100.0的位置在损失计算中会被忽略(被掩码)。 - speaking_rate (
float,可选) — 语速。
返回值
VitsModelOutput 或 tuple(torch.Tensor)
VitsModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(VitsConfig)和输入。
VitsModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
waveform(形状为
(batch_size, sequence_length)的torch.Tensor)— 模型预测的最终音频波形。sequence_lengths(形状为
(batch_size,)的torch.Tensor)—waveform批次中每个元素的样本长度。spectrogram(形状为
(batch_size, sequence_length, num_bins)的torch.Tensor)— 流模型输出端预测的对数梅尔频谱图。该频谱图将被传入 Hi-Fi GAN 解码器模型,以获取最终的音频波形。hidden_states (
tuple[torch.Tensor],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> 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])