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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.