Transformers 文档

FastSpeech2Conformer

FastSpeech2Conformer

概述

FastSpeech2Conformer 模型是由 Pengcheng Guo、Florian Boyer、Xuankai Chang、Tomoki Hayashi、Yosuke Higuchi、Hirofumi Inaguma、Naoyuki Kamo、Chenda Li、Daniel Garcia-Romero、Jiatong Shi、Jing Shi、Shinji Watanabe、Kun Wei、Wangyou Zhang 和 Yuekai Zhang 在论文 Recent Developments On Espnet Toolkit Boosted By Conformer 中提出的。

原始FastSpeech2论文的摘要如下:

非自回归文本到语音(TTS)模型,如FastSpeech(Ren等,2019),可以在质量相当的情况下显著比之前的自回归模型更快地合成语音。FastSpeech模型的训练依赖于自回归教师模型进行持续时间预测(以提供更多输入信息)和知识蒸馏(以简化输出中的数据分布),这可以缓解TTS中的一对多映射问题(即,多个语音变体对应于同一文本)。然而,FastSpeech有几个缺点:1)教师-学生蒸馏流程复杂且耗时,2)从教师模型中提取的持续时间不够准确,并且从教师模型中蒸馏出的目标梅尔频谱图由于数据简化而遭受信息损失,这两者都限制了语音质量。在本文中,我们提出了FastSpeech 2,它解决了FastSpeech中的问题,并通过以下方式更好地解决了TTS中的一对多映射问题:1)直接使用真实目标训练模型,而不是教师模型的简化输出,2)引入更多语音变化信息(例如,音高、能量和更准确的持续时间)作为条件输入。具体来说,我们从语音波形中提取持续时间、音高和能量,并直接将其作为训练中的条件输入,并在推理中使用预测值。我们进一步设计了FastSpeech 2s,这是首次尝试直接从文本并行生成语音波形,享受完全端到端推理的好处。实验结果表明:1)FastSpeech 2比FastSpeech实现了3倍的训练加速,而FastSpeech 2s的推理速度更快;2)FastSpeech 2和2s在语音质量上优于FastSpeech,而FastSpeech 2甚至可以超越自回归模型。音频样本可在https://speechresearch.github.io/fastspeech2/上获取。

该模型由Connor Henderson贡献。原始代码可以在这里找到。

🤗 模型架构

实现了带有梅尔频谱图解码器的FastSpeech2的通用结构,并且按照ESPnet库中的做法,将传统的transformer块替换为conformer块。

FastSpeech2 模型架构

FastSpeech2 模型架构

Conformer 模块

Conformer 模块

卷积模块

卷积模块

🤗 Transformers 使用

您可以使用 🤗 Transformers 库在本地运行 FastSpeech2Conformer。

  1. 首先安装🤗 Transformers库,g2p-en:
pip install --upgrade pip
pip install --upgrade transformers g2p-en
  1. 通过Transformers建模代码分别使用模型和hifigan进行推理

from transformers import FastSpeech2ConformerTokenizer, FastSpeech2ConformerModel, FastSpeech2ConformerHifiGan
import soundfile as sf

tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
inputs = tokenizer("Hello, my dog is cute.", return_tensors="pt")
input_ids = inputs["input_ids"]

model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer")
output_dict = model(input_ids, return_dict=True)
spectrogram = output_dict["spectrogram"]

hifigan = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan")
waveform = hifigan(spectrogram)

sf.write("speech.wav", waveform.squeeze().detach().numpy(), samplerate=22050)
  1. 通过Transformers建模代码运行推理,结合模型和hifigan
from transformers import FastSpeech2ConformerTokenizer, FastSpeech2ConformerWithHifiGan
import soundfile as sf

tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
inputs = tokenizer("Hello, my dog is cute.", return_tensors="pt")
input_ids = inputs["input_ids"]

model = FastSpeech2ConformerWithHifiGan.from_pretrained("espnet/fastspeech2_conformer_with_hifigan")
output_dict = model(input_ids, return_dict=True)
waveform = output_dict["waveform"]

sf.write("speech.wav", waveform.squeeze().detach().numpy(), samplerate=22050)
  1. 使用管道运行推理并指定要使用的声码器
from transformers import pipeline, FastSpeech2ConformerHifiGan
import soundfile as sf

vocoder = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan")
synthesiser = pipeline(model="espnet/fastspeech2_conformer", vocoder=vocoder)

speech = synthesiser("Hello, my dog is cooler than you!")

sf.write("speech.wav", speech["audio"].squeeze(), samplerate=speech["sampling_rate"])

FastSpeech2ConformerConfig

transformers.FastSpeech2ConformerConfig

< >

( hidden_size = 384 vocab_size = 78 num_mel_bins = 80 encoder_num_attention_heads = 2 encoder_layers = 4 encoder_linear_units = 1536 decoder_layers = 4 decoder_num_attention_heads = 2 decoder_linear_units = 1536 speech_decoder_postnet_layers = 5 speech_decoder_postnet_units = 256 speech_decoder_postnet_kernel = 5 positionwise_conv_kernel_size = 3 encoder_normalize_before = False decoder_normalize_before = False encoder_concat_after = False decoder_concat_after = False reduction_factor = 1 speaking_speed = 1.0 use_macaron_style_in_conformer = True use_cnn_in_conformer = True encoder_kernel_size = 7 decoder_kernel_size = 31 duration_predictor_layers = 2 duration_predictor_channels = 256 duration_predictor_kernel_size = 3 energy_predictor_layers = 2 energy_predictor_channels = 256 energy_predictor_kernel_size = 3 energy_predictor_dropout = 0.5 energy_embed_kernel_size = 1 energy_embed_dropout = 0.0 stop_gradient_from_energy_predictor = False pitch_predictor_layers = 5 pitch_predictor_channels = 256 pitch_predictor_kernel_size = 5 pitch_predictor_dropout = 0.5 pitch_embed_kernel_size = 1 pitch_embed_dropout = 0.0 stop_gradient_from_pitch_predictor = True encoder_dropout_rate = 0.2 encoder_positional_dropout_rate = 0.2 encoder_attention_dropout_rate = 0.2 decoder_dropout_rate = 0.2 decoder_positional_dropout_rate = 0.2 decoder_attention_dropout_rate = 0.2 duration_predictor_dropout_rate = 0.2 speech_decoder_postnet_dropout = 0.5 max_source_positions = 5000 use_masking = True use_weighted_masking = False num_speakers = None num_languages = None speaker_embed_dim = None is_encoder_decoder = True **kwargs )

参数

  • hidden_size (int, optional, 默认为 384) — 隐藏层的维度。
  • vocab_size (int, optional, defaults to 78) — 词汇表的大小。
  • num_mel_bins (int, 可选, 默认为 80) — 滤波器组中使用的梅尔滤波器数量。
  • encoder_num_attention_heads (int, optional, 默认为 2) — 编码器中注意力头的数量。
  • encoder_layers (int, optional, defaults to 4) — 编码器中的层数。
  • encoder_linear_units (int, optional, 默认为 1536) — 编码器线性层中的单元数量。
  • decoder_layers (int, optional, defaults to 4) — 解码器中的层数。
  • decoder_num_attention_heads (int, optional, 默认为 2) — 解码器中的注意力头数。
  • decoder_linear_units (int, optional, 默认为1536) — 解码器线性层中的单元数量。
  • speech_decoder_postnet_layers (int, optional, defaults to 5) — 语音解码器后置网络的层数。
  • speech_decoder_postnet_units (int, 可选, 默认为 256) — 语音解码器的后网络层中的单元数量。
  • speech_decoder_postnet_kernel (int, 可选, 默认为 5) — 语音解码器后置网络中的核大小。
  • positionwise_conv_kernel_size (int, optional, defaults to 3) — 位置层中使用的卷积核的大小。
  • encoder_normalize_before (bool, optional, defaults to False) — 指定是否在编码器层之前进行归一化。
  • decoder_normalize_before (bool, 可选, 默认为 False) — 指定是否在解码器层之前进行归一化。
  • encoder_concat_after (bool, optional, defaults to False) — 指定是否在编码器层之后进行连接。
  • decoder_concat_after (bool, 可选, 默认为 False) — 指定是否在解码器层之后进行连接。
  • reduction_factor (int, optional, defaults to 1) — 语音帧率降低的因子。
  • speaking_speed (float, optional, 默认为 1.0) — 生成语音的速度。
  • use_macaron_style_in_conformer (bool, 可选, 默认为 True) — 指定是否在conformer中使用macaron风格。
  • use_cnn_in_conformer (bool, 可选, 默认为 True) — 指定是否在conformer中使用卷积神经网络。
  • encoder_kernel_size (int, optional, defaults to 7) — 编码器中使用的核大小。
  • decoder_kernel_size (int, optional, 默认为 31) — 解码器中使用的核大小。
  • duration_predictor_layers (int, optional, defaults to 2) — 持续时间预测器中的层数。
  • duration_predictor_channels (int, optional, defaults to 256) — 持续时间预测器中的通道数。
  • duration_predictor_kernel_size (int, optional, defaults to 3) — 用于持续时间预测器的内核大小。
  • energy_predictor_layers (int, optional, defaults to 2) — 能量预测器中的层数。
  • energy_predictor_channels (int, optional, defaults to 256) — 能量预测器中的通道数。
  • energy_predictor_kernel_size (int, optional, 默认为 3) — 能量预测器中使用的核大小。
  • energy_predictor_dropout (float, optional, 默认为 0.5) — 能量预测器中的丢弃率。
  • energy_embed_kernel_size (int, optional, defaults to 1) — 能量嵌入层中使用的核大小。
  • energy_embed_dropout (float, optional, defaults to 0.0) — 能量嵌入层的丢弃率。
  • stop_gradient_from_energy_predictor (bool, optional, defaults to False) — 指定是否停止来自能量预测器的梯度。
  • pitch_predictor_layers (int, optional, defaults to 5) — 音高预测器中的层数。
  • pitch_predictor_channels (int, optional, defaults to 256) — 音高预测器中的通道数。
  • pitch_predictor_kernel_size (int, optional, defaults to 5) — 用于音高预测器的内核大小。
  • pitch_predictor_dropout (float, optional, defaults to 0.5) — 音高预测器中的丢弃率。
  • pitch_embed_kernel_size (int, optional, defaults to 1) — 用于音高嵌入层的核大小。
  • pitch_embed_dropout (float, optional, defaults to 0.0) — 在音高嵌入层中的丢弃率。
  • stop_gradient_from_pitch_predictor (bool, optional, defaults to True) — 指定是否停止来自音高预测器的梯度。
  • encoder_dropout_rate (float, optional, 默认为 0.2) — 编码器中的丢弃率。
  • encoder_positional_dropout_rate (float, optional, defaults to 0.2) — 编码器中的位置丢弃率。
  • encoder_attention_dropout_rate (float, optional, 默认为 0.2) — 编码器中的注意力丢弃率。
  • decoder_dropout_rate (float, optional, defaults to 0.2) — 解码器中的丢弃率。
  • decoder_positional_dropout_rate (float, optional, defaults to 0.2) — 解码器中的位置丢弃率。
  • decoder_attention_dropout_rate (float, optional, 默认为 0.2) — 解码器中的注意力丢弃率。
  • duration_predictor_dropout_rate (float, optional, defaults to 0.2) — 持续时间预测器中的丢弃率。
  • speech_decoder_postnet_dropout (float, 可选, 默认为 0.5) — 语音解码器后置网络中的丢弃率。
  • max_source_positions (int, 可选, 默认为 5000) — 如果使用 "relative" 位置嵌入,定义最大源输入位置。
  • use_masking (bool, optional, defaults to True) — 指定是否在模型中使用掩码。
  • use_weighted_masking (bool, 可选, 默认为 False) — 指定是否在模型中使用加权掩码。
  • num_speakers (int, optional) — 说话者数量。如果设置为大于1,假设将提供说话者ID作为输入,并使用说话者ID嵌入层。
  • num_languages (int, 可选) — 语言数量。如果设置为大于1,假设语言ID将作为输入提供,并使用语言ID嵌入层。
  • speaker_embed_dim (int, optional) — 说话者嵌入维度。如果设置为 > 0,假设将提供 speaker_embedding 作为输入。
  • is_encoder_decoder (bool, optional, defaults to True) — 指定模型是否为编码器-解码器。

这是用于存储FastSpeech2ConformerModel配置的配置类。它用于根据指定的参数实例化一个FastSpeech2Conformer模型,定义模型架构。使用默认值实例化配置将产生与espnet/fastspeech2_conformer架构相似的配置。

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

示例:

>>> from transformers import FastSpeech2ConformerModel, FastSpeech2ConformerConfig

>>> # Initializing a FastSpeech2Conformer style configuration
>>> configuration = FastSpeech2ConformerConfig()

>>> # Initializing a model from the FastSpeech2Conformer style configuration
>>> model = FastSpeech2ConformerModel(configuration)

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

FastSpeech2ConformerHifiGanConfig

class transformers.FastSpeech2ConformerHifiGanConfig

< >

( model_in_dim = 80 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]] initializer_range = 0.01 leaky_relu_slope = 0.1 normalize_before = True **kwargs )

参数

  • model_in_dim (int, optional, 默认为 80) — 输入对数梅尔频谱图中的频率仓数量。
  • upsample_initial_channel (int, optional, 默认为 512) — 上采样网络的输入通道数。
  • upsample_rates (Tuple[int]List[int], 可选, 默认为 [8, 8, 2, 2]) — 一个整数元组,定义了上采样网络中每个一维卷积层的步幅。upsample_rates 的长度定义了卷积层的数量,并且必须与 upsample_kernel_sizes 的长度匹配。
  • upsample_kernel_sizes (Tuple[int]List[int], 可选, 默认为 [16, 16, 4, 4]) — 一个整数元组,定义了上采样网络中每个1D卷积层的核大小。upsample_kernel_sizes 的长度定义了卷积层的数量,并且必须与 upsample_rates 的长度匹配。
  • resblock_kernel_sizes (Tuple[int]List[int], 可选, 默认为 [3, 7, 11]) — 一个整数元组,定义了多感受野融合(MRF)模块中1D卷积层的核大小。
  • resblock_dilation_sizes (Tuple[Tuple[int]]List[List[int]], 可选, 默认为 [[1, 3, 5], [1, 3, 5], [1, 3, 5]]) — 一个嵌套的整数元组,定义了多感受野融合(MRF)模块中扩张1D卷积层的扩张率。
  • initializer_range (float, optional, 默认为 0.01) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • leaky_relu_slope (float, optional, defaults to 0.1) — 用于leaky ReLU激活的负斜率角度。
  • normalize_before (bool, optional, defaults to True) — 是否在使用声码器的学习均值和方差进行声码化之前对频谱图进行归一化。

这是用于存储FastSpeech2ConformerHifiGanModel配置的配置类。它用于根据指定的参数实例化一个FastSpeech2Conformer HiFi-GAN声码器模型,定义模型架构。使用默认值实例化配置将产生与espnet/fastspeech2_conformer_hifigan架构类似的配置。

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

示例:

>>> from transformers import FastSpeech2ConformerHifiGan, FastSpeech2ConformerHifiGanConfig

>>> # Initializing a FastSpeech2ConformerHifiGan configuration
>>> configuration = FastSpeech2ConformerHifiGanConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = FastSpeech2ConformerHifiGan(configuration)

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

FastSpeech2ConformerWithHifiGanConfig

transformers.FastSpeech2ConformerWithHifiGanConfig

< >

( model_config: typing.Dict = None vocoder_config: typing.Dict = None **kwargs )

参数

  • model_config (typing.Dict, optional) — 文本到语音模型的配置。
  • vocoder_config (typing.Dict, optional) — 声码器模型的配置。

这是用于存储FastSpeech2ConformerWithHifiGan配置的配置类。它用于根据指定的子模型配置实例化FastSpeech2ConformerWithHifiGanModel模型,定义模型架构。

使用默认值实例化配置将产生类似于FastSpeech2ConformerModel espnet/fastspeech2_conformer 和 FastSpeech2ConformerHifiGan espnet/fastspeech2_conformer_hifigan 架构的配置。

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

model_config (FastSpeech2ConformerConfig, 可选): 文本到语音模型的配置。 vocoder_config (FastSpeech2ConformerHiFiGanConfig, 可选): 声码器模型的配置。

示例:

>>> from transformers import (
...     FastSpeech2ConformerConfig,
...     FastSpeech2ConformerHifiGanConfig,
...     FastSpeech2ConformerWithHifiGanConfig,
...     FastSpeech2ConformerWithHifiGan,
... )

>>> # Initializing FastSpeech2ConformerWithHifiGan sub-modules configurations.
>>> model_config = FastSpeech2ConformerConfig()
>>> vocoder_config = FastSpeech2ConformerHifiGanConfig()

>>> # Initializing a FastSpeech2ConformerWithHifiGan module style configuration
>>> configuration = FastSpeech2ConformerWithHifiGanConfig(model_config.to_dict(), vocoder_config.to_dict())

>>> # Initializing a model (with random weights)
>>> model = FastSpeech2ConformerWithHifiGan(configuration)

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

FastSpeech2ConformerTokenizer

transformers.FastSpeech2ConformerTokenizer

< >

( vocab_file bos_token = '' eos_token = '' pad_token = '' unk_token = '' should_strip_spaces = False **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • bos_token (str, 可选, 默认为 "") — 序列的开始标记。请注意,对于 FastSpeech2,它与 eos_token 相同。
  • eos_token (str, 可选, 默认为 "") — 序列结束标记。请注意,对于FastSpeech2,它与bos_token相同。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • should_strip_spaces (bool, optional, defaults to False) — 是否从令牌列表中去除空格。

构建一个FastSpeech2Conformer分词器。

__call__

< >

( text: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 is_split_into_words: bool = False pad_to_multiple_of: typing.Optional[int] = None padding_side: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True **kwargs ) BatchEncoding

参数

  • text (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair (str, List[str], List[List[str]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair_target (str, List[str], List[List[str]], optional) — 要编码为目标文本的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)的形式提供,你必须设置is_split_into_words=True(以消除与序列批次的歧义)。
  • add_special_tokens (bool, 可选, 默认为 True) — 是否在编码序列时添加特殊标记。这将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入ID中。如果您想自动添加 boseos 标记,这将非常有用。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — Activates and controls padding. Accepts the following values:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • stride (int, 可选, 默认为 0) — 如果设置为一个数字并与 max_length 一起使用,当 return_overflowing_tokens=True 时返回的溢出标记将包含一些来自截断序列末尾的标记,以提供截断序列和溢出序列之间的一些重叠。此参数的值定义了重叠标记的数量。
  • is_split_into_words (bool, 可选, 默认为 False) — 输入是否已经预分词(例如,分成单词)。如果设置为 True,分词器会假设输入已经分成单词(例如,通过空格分割),然后进行分词。这对于NER或分词分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,将序列填充到提供的值的倍数。需要激活padding。 这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用。
  • padding_side (str, optional) — 模型应应用填充的一侧。应在['right', 'left']之间选择。 默认值从同名的类属性中选取。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • return_token_type_ids (bool, optional) — Whether to return token type IDs. If left to the default, will return the token type IDs according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是token type IDs?

  • return_attention_mask (bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是注意力掩码?

  • return_overflowing_tokens (bool, optional, defaults to False) — 是否返回溢出的token序列。如果提供了一对输入id序列(或一批对)并且truncation_strategy = longest_firstTrue,则会引发错误而不是返回溢出的token。
  • return_special_tokens_mask (bool, optional, defaults to False) — 是否返回特殊令牌掩码信息。
  • return_offsets_mapping (bool, optional, defaults to False) — Whether or not to return (char_start, char_end) for each token.

    这仅在继承自PreTrainedTokenizerFast的快速分词器上可用,如果使用Python的分词器,此方法将引发NotImplementedError

  • return_length (bool, optional, defaults to False) — 是否返回编码输入的长度。
  • verbose (bool, optional, defaults to True) — 是否打印更多信息和警告。
  • **kwargs — 传递给 self.tokenize() 方法

返回

BatchEncoding

一个BatchEncoding包含以下字段:

  • input_ids — 要输入模型的令牌ID列表。

    什么是输入ID?

  • token_type_ids — 要输入模型的令牌类型ID列表(当return_token_type_ids=True或 如果“token_type_ids”self.model_input_names中)。

    什么是令牌类型ID?

  • attention_mask — 指定模型应关注哪些令牌的索引列表(当 return_attention_mask=True或如果“attention_mask”self.model_input_names中)。

    什么是注意力掩码?

  • overflowing_tokens — 溢出令牌序列列表(当指定了max_length并且 return_overflowing_tokens=True)。

  • num_truncated_tokens — 截断的令牌数量(当指定了max_length并且 return_overflowing_tokens=True)。

  • special_tokens_mask — 0和1的列表,1表示添加的特殊令牌,0表示 常规序列令牌(当add_special_tokens=Truereturn_special_tokens_mask=True)。

  • length — 输入的长度(当return_length=True

主要方法,用于将一个或多个序列或一个或多个序列对进行标记化并准备供模型使用。

保存词汇表

< >

( save_directory: str filename_prefix: typing.Optional[str] = None ) Tuple(str)

参数

  • save_directory (str) — 保存词汇表的目录。

返回

Tuple(str)

保存文件的路径。

将词汇表和特殊标记文件保存到一个目录中。

解码

< >

( token_ids **kwargs )

batch_decode

< >

( sequences: typing.Union[typing.List[int], typing.List[typing.List[int]], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')] skip_special_tokens: bool = False clean_up_tokenization_spaces: bool = None **kwargs ) List[str]

参数

  • sequences (Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]) — 标记化输入ID的列表。可以使用__call__方法获取。
  • skip_special_tokens (bool, optional, defaults to False) — 是否在解码过程中移除特殊标记。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理分词空格。如果为None,将默认为 self.clean_up_tokenization_spaces.
  • kwargs(额外的关键字参数,可选)— 将被传递给底层模型的特定解码方法。

返回

List[str]

解码后的句子列表。

通过调用decode将token id的列表列表转换为字符串列表。

FastSpeech2ConformerModel

transformers.FastSpeech2ConformerModel

< >

( config: FastSpeech2ConformerConfig )

参数

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

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

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

FastSpeech 2 模块。

这是FastSpeech 2的一个模块,描述在‘FastSpeech 2: Fast and High-Quality End-to-End Text to Speech’中 https://arxiv.org/abs/2006.04558。我们使用在FastPitch: Parallel Text-to-speech with Pitch Prediction中引入的标记平均值,而不是量化的音高和能量。编码器和解码器是Conformers,而不是常规的Transformers。

前进

< >

( input_ids: LongTensor attention_mask: typing.Optional[torch.LongTensor] = None spectrogram_labels: typing.Optional[torch.FloatTensor] = None duration_labels: typing.Optional[torch.LongTensor] = None pitch_labels: typing.Optional[torch.FloatTensor] = None energy_labels: typing.Optional[torch.FloatTensor] = None speaker_ids: typing.Optional[torch.LongTensor] = None lang_ids: typing.Optional[torch.LongTensor] = None speaker_embedding: typing.Optional[torch.FloatTensor] = None return_dict: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None ) transformers.models.fastspeech2_conformer.modeling_fastspeech2_conformer.FastSpeech2ConformerModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — 文本向量的输入序列.
  • attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional, defaults to None) — 用于避免在填充标记索引上执行卷积和注意力的掩码。掩码值在 [0, 1] 中选择:0 表示标记被掩码,1 表示标记未被掩码
  • spectrogram_labels (torch.FloatTensor of shape (batch_size, max_spectrogram_length, num_mel_bins), optional, defaults to None) — 填充目标特征的批次.
  • duration_labels (torch.LongTensor of shape (batch_size, sequence_length + 1), optional, defaults to None) — 填充的持续时间批次.
  • pitch_labels (torch.FloatTensor of shape (batch_size, sequence_length + 1, 1), 可选, 默认为 None) — 批量的填充后的令牌平均音高.
  • energy_labels (torch.FloatTensor of shape (batch_size, sequence_length + 1, 1), optional, defaults to None) — 批量填充的令牌平均能量。
  • speaker_ids (torch.LongTensor of shape (batch_size, 1), optional, defaults to None) — 用于调节模型输出的语音特征的说话者ID。
  • lang_ids (torch.LongTensor of shape (batch_size, 1), optional, defaults to None) — 用于调节模型输出的语音特征的语言ID。
  • speaker_embedding (torch.FloatTensor of shape (batch_size, embedding_dim), optional, defaults to None) — 包含语音特征条件信号的嵌入。
  • return_dict (bool, 可选, 默认为 None) — 是否返回一个 FastSpeech2ConformerModelOutput 而不是一个普通的元组。
  • output_attentions (bool, 可选, 默认为 None) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的 attentions
  • output_hidden_states (bool, 可选, 默认为 None) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states

返回

transformers.models.fastspeech2_conformer.modeling_fastspeech2_conformer.FastSpeech2ConformerModelOutputtuple(torch.FloatTensor)

一个 transformers.models.fastspeech2_conformer.modeling_fastspeech2_conformer.FastSpeech2ConformerModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(FastSpeech2ConformerConfig)和输入。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 频谱图生成损失。

  • spectrogram (torch.FloatTensor 形状为 (batch_size, sequence_length, num_bins)) — 预测的频谱图。

  • encoder_last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size)可选) — 模型编码器最后一层的隐藏状态序列。

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

    编码器在每一层输出处的隐藏状态加上初始嵌入输出。

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

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

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

    解码器在每一层输出处的隐藏状态加上初始嵌入输出。

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

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

  • duration_outputs (torch.LongTensor 形状为 (batch_size, max_text_length + 1)可选) — 持续时间预测器的输出。

  • pitch_outputs (torch.FloatTensor 形状为 (batch_size, max_text_length + 1, 1)可选) — 音高预测器的输出。

  • energy_outputs (torch.FloatTensor 形状为 (batch_size, max_text_length + 1, 1)可选) — 能量预测器的输出。

示例:

>>> from transformers import (
...     FastSpeech2ConformerTokenizer,
...     FastSpeech2ConformerModel,
...     FastSpeech2ConformerHifiGan,
... )

>>> tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
>>> inputs = tokenizer("some text to convert to speech", return_tensors="pt")
>>> input_ids = inputs["input_ids"]

>>> model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer")
>>> output_dict = model(input_ids, return_dict=True)
>>> spectrogram = output_dict["spectrogram"]

>>> vocoder = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan")
>>> waveform = vocoder(spectrogram)
>>> print(waveform.shape)
torch.Size([1, 49664])

FastSpeech2ConformerHifiGan

transformers.FastSpeech2ConformerHifiGan

< >

( config: FastSpeech2ConformerHifiGanConfig )

参数

  • config (FastSpeech2ConformerConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化时不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

HiFi-GAN 语音编码器。 该模型继承自 PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( 频谱图: FloatTensor ) torch.FloatTensor

参数

  • spectrogram (torch.FloatTensor) — 包含对数梅尔频谱图的张量。可以是批量的,形状为(batch_size, sequence_length, config.model_in_dim),也可以是非批量的,形状为(sequence_length, config.model_in_dim).

返回

torch.FloatTensor

包含语音波形的张量。如果输入的频谱图是批处理的,形状将为(batch_size, num_frames,)。如果未批处理,形状将为(num_frames,)

将log-mel频谱图转换为语音波形。传递一批log-mel频谱图将返回一批语音波形。传递单个未批处理的log-mel频谱图将返回单个未批处理的语音波形。

FastSpeech2ConformerWithHifiGan

transformers.FastSpeech2ConformerWithHifiGan

< >

( config: FastSpeech2ConformerWithHifiGanConfig )

参数

带有FastSpeech2ConformerHifiGan声码器头的FastSpeech2ConformerModel,用于执行文本到语音(波形)转换。 该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: LongTensor attention_mask: typing.Optional[torch.LongTensor] = None spectrogram_labels: typing.Optional[torch.FloatTensor] = None duration_labels: typing.Optional[torch.LongTensor] = None pitch_labels: typing.Optional[torch.FloatTensor] = None energy_labels: typing.Optional[torch.FloatTensor] = None speaker_ids: typing.Optional[torch.LongTensor] = None lang_ids: typing.Optional[torch.LongTensor] = None speaker_embedding: typing.Optional[torch.FloatTensor] = None return_dict: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None ) transformers.models.fastspeech2_conformer.modeling_fastspeech2_conformer.FastSpeech2ConformerWithHifiGanOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — 文本向量的输入序列.
  • attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional, defaults to None) — 用于避免在填充标记索引上执行卷积和注意力的掩码。掩码值选择在 [0, 1]:0 表示被掩码的标记,1 表示未被掩码的标记。
  • spectrogram_labels (torch.FloatTensor of shape (batch_size, max_spectrogram_length, num_mel_bins), 可选, 默认为 None) — 填充的目标特征批次.
  • duration_labels (torch.LongTensor of shape (batch_size, sequence_length + 1), optional, defaults to None) — 填充的持续时间批次.
  • pitch_labels (torch.FloatTensor of shape (batch_size, sequence_length + 1, 1), optional, defaults to None) — 批量的填充后的令牌平均音高。
  • energy_labels (torch.FloatTensor of shape (batch_size, sequence_length + 1, 1), 可选, 默认为 None) — 批量的填充后的令牌平均能量.
  • speaker_ids (torch.LongTensor of shape (batch_size, 1), optional, defaults to None) — 用于调节模型输出的语音特征的说话者ID。
  • lang_ids (torch.LongTensor of shape (batch_size, 1), optional, defaults to None) — 用于调节模型输出的语音特征的语言ID。
  • speaker_embedding (torch.FloatTensor of shape (batch_size, embedding_dim), optional, defaults to None) — 包含语音特征条件信号的嵌入。
  • return_dict (bool, 可选, 默认为 None) — 是否返回一个 FastSpeech2ConformerModelOutput 而不是一个普通的元组。
  • output_attentions (bool, 可选, 默认为 None) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的 attentions
  • output_hidden_states (bool, 可选, 默认为 None) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states

返回

transformers.models.fastspeech2_conformer.modeling_fastspeech2_conformer.FastSpeech2ConformerWithHifiGanOutputtuple(torch.FloatTensor)

一个 transformers.models.fastspeech2_conformer.modeling_fastspeech2_conformer.FastSpeech2ConformerWithHifiGanOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置()和输入。

  • waveform (torch.FloatTensor 形状为 (batch_size, audio_length)) — 通过声码器传递预测的梅尔频谱图后生成的语音输出。

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 labels 时返回) — 频谱图生成损失。

  • spectrogram (torch.FloatTensor 形状为 (batch_size, sequence_length, num_bins)) — 预测的频谱图。

  • encoder_last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层的隐藏状态序列。

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

    编码器每层输出的隐藏状态加上初始嵌入输出。

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

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

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

    解码器每层输出的隐藏状态加上初始嵌入输出。

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

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

  • duration_outputs (torch.LongTensor 形状为 (batch_size, max_text_length + 1), 可选) — 持续时间预测器的输出。

  • pitch_outputs (torch.FloatTensor 形状为 (batch_size, max_text_length + 1, 1), 可选) — 音高预测器的输出。

  • energy_outputs (torch.FloatTensor 形状为 (batch_size, max_text_length + 1, 1), 可选) — 能量预测器的输出。

示例:

>>> from transformers import (
...     FastSpeech2ConformerTokenizer,
...     FastSpeech2ConformerWithHifiGan,
... )

>>> tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
>>> inputs = tokenizer("some text to convert to speech", return_tensors="pt")
>>> input_ids = inputs["input_ids"]

>>> model = FastSpeech2ConformerWithHifiGan.from_pretrained("espnet/fastspeech2_conformer_with_hifigan")
>>> output_dict = model(input_ids, return_dict=True)
>>> waveform = output_dict["waveform"]
>>> print(waveform.shape)
torch.Size([1, 49664])
< > Update on GitHub