Text to speech
Text-to-speech (TTS) is the task of creating natural-sounding speech from text, where the speech can be generated in multiple languages and for multiple speakers. Several text-to-speech models are currently available in 🌍 Transformers, such as Bark, MMS, VITS and SpeechT5.
You can easily generate audio using the "text-to-audio"
pipeline (or its alias - "text-to-speech"
). Some models, like Bark, can also be conditioned to generate non-verbal communications such as laughing, sighing and crying, or even add music. Here’s an example of how you would use the "text-to-speech"
pipeline with Bark:
Copied
Here’s a code snippet you can use to listen to the resulting audio in a notebook:
Copied
For more examples on what Bark and other pretrained TTS models can do, refer to our Audio course.
If you are looking to fine-tune a TTS model, you can currently fine-tune SpeechT5 only. SpeechT5 is pre-trained on a combination of speech-to-text and text-to-speech data, allowing it to learn a unified space of hidden representations shared by both text and speech. This means that the same pre-trained model can be fine-tuned for different tasks. Furthermore, SpeechT5 supports multiple speakers through x-vector speaker embeddings.
The remainder of this guide illustrates how to:
Use your refined model for inference in one of two ways: using a pipeline or directly.
Before you begin, make sure you have all the necessary libraries installed:
Copied
Install 🌍Transformers from source as not all the SpeechT5 features have been merged into an official release yet:
Copied
To follow this guide you will need a GPU. If you’re working in a notebook, run the following line to check if a GPU is available:
Copied
We encourage you to log in to your BOINC AI account to upload and share your model with the community. When prompted, enter your token to log in:
Copied
Load the dataset
VoxPopuli is a large-scale multilingual speech corpus consisting of data sourced from 2009-2020 European Parliament event recordings. It contains labelled audio-transcription data for 15 European languages. In this guide, we are using the Dutch language subset, feel free to pick another subset.
Note that VoxPopuli or any other automated speech recognition (ASR) dataset may not be the most suitable option for training TTS models. The features that make it beneficial for ASR, such as excessive background noise, are typically undesirable in TTS. However, finding top-quality, multilingual, and multi-speaker TTS datasets can be quite challenging.
Let’s load the data:
Copied
20968 examples should be sufficient for fine-tuning. SpeechT5 expects audio data to have a sampling rate of 16 kHz, so make sure the examples in the dataset meet this requirement:
Copied
Preprocess the data
Let’s begin by defining the model checkpoint to use and loading the appropriate processor:
Copied
Text cleanup for SpeechT5 tokenization
Start by cleaning up the text data. You’ll need the tokenizer part of the processor to process the text:
Copied
The dataset examples contain raw_text
and normalized_text
features. When deciding which feature to use as the text input, consider that the SpeechT5 tokenizer doesn’t have any tokens for numbers. In normalized_text
the numbers are written out as text. Thus, it is a better fit, and we recommend using normalized_text
as input text.
Because SpeechT5 was trained on the English language, it may not recognize certain characters in the Dutch dataset. If left as is, these characters will be converted to <unk>
tokens. However, in Dutch, certain characters like à
are used to stress syllables. In order to preserve the meaning of the text, we can replace this character with a regular a
.
To identify unsupported tokens, extract all unique characters in the dataset using the SpeechT5Tokenizer
which works with characters as tokens. To do this, write the extract_all_chars
mapping function that concatenates the transcriptions from all examples into one string and converts it to a set of characters. Make sure to set batched=True
and batch_size=-1
in dataset.map()
so that all transcriptions are available at once for the mapping function.
Copied
Now you have two sets of characters: one with the vocabulary from the dataset and one with the vocabulary from the tokenizer. To identify any unsupported characters in the dataset, you can take the difference between these two sets. The resulting set will contain the characters that are in the dataset but not in the tokenizer.
Copied
To handle the unsupported characters identified in the previous step, define a function that maps these characters to valid tokens. Note that spaces are already replaced by ▁
in the tokenizer and don’t need to be handled separately.
Copied
Now that you have dealt with special characters in the text, it’s time to shift focus to the audio data.
Speakers
The VoxPopuli dataset includes speech from multiple speakers, but how many speakers are represented in the dataset? To determine this, we can count the number of unique speakers and the number of examples each speaker contributes to the dataset. With a total of 20,968 examples in the dataset, this information will give us a better understanding of the distribution of speakers and examples in the data.
Copied
By plotting a histogram you can get a sense of how much data there is for each speaker.
Copied
The histogram reveals that approximately one-third of the speakers in the dataset have fewer than 100 examples, while around ten speakers have more than 500 examples. To improve training efficiency and balance the dataset, we can limit the data to speakers with between 100 and 400 examples.
Copied
Let’s check how many speakers remain:
Copied
Let’s see how many examples are left:
Copied
You are left with just under 10,000 examples from approximately 40 unique speakers, which should be sufficient.
Note that some speakers with few examples may actually have more audio available if the examples are long. However, determining the total amount of audio for each speaker requires scanning through the entire dataset, which is a time-consuming process that involves loading and decoding each audio file. As such, we have chosen to skip this step here.
Speaker embeddings
To enable the TTS model to differentiate between multiple speakers, you’ll need to create a speaker embedding for each example. The speaker embedding is an additional input into the model that captures a particular speaker’s voice characteristics. To generate these speaker embeddings, use the pre-trained spkrec-xvect-voxceleb model from SpeechBrain.
Create a function create_speaker_embedding()
that takes an input audio waveform and outputs a 512-element vector containing the corresponding speaker embedding.
Copied
It’s important to note that the speechbrain/spkrec-xvect-voxceleb
model was trained on English speech from the VoxCeleb dataset, whereas the training examples in this guide are in Dutch. While we believe that this model will still generate reasonable speaker embeddings for our Dutch dataset, this assumption may not hold true in all cases.
For optimal results, we recommend training an X-vector model on the target speech first. This will ensure that the model is better able to capture the unique voice characteristics present in the Dutch language.
Processing the dataset
Finally, let’s process the data into the format the model expects. Create a prepare_dataset
function that takes in a single example and uses the SpeechT5Processor
object to tokenize the input text and load the target audio into a log-mel spectrogram. It should also add the speaker embeddings as an additional input.
Copied
Verify the processing is correct by looking at a single example:
Copied
Speaker embeddings should be a 512-element vector:
Copied
The labels should be a log-mel spectrogram with 80 mel bins.
Copied
Side note: If you find this spectrogram confusing, it may be due to your familiarity with the convention of placing low frequencies at the bottom and high frequencies at the top of a plot. However, when plotting spectrograms as an image using the matplotlib library, the y-axis is flipped and the spectrograms appear upside down.
Now apply the processing function to the entire dataset. This will take between 5 and 10 minutes.
Copied
You’ll see a warning saying that some examples in the dataset are longer than the maximum input length the model can handle (600 tokens). Remove those examples from the dataset. Here we go even further and to allow for larger batch sizes we remove anything over 200 tokens.
Copied
Next, create a basic train/test split:
Copied
Data collator
In order to combine multiple examples into a batch, you need to define a custom data collator. This collator will pad shorter sequences with padding tokens, ensuring that all examples have the same length. For the spectrogram labels, the padded portions are replaced with the special value -100
. This special value instructs the model to ignore that part of the spectrogram when calculating the spectrogram loss.
Copied
In SpeechT5, the input to the decoder part of the model is reduced by a factor 2. In other words, it throws away every other timestep from the target sequence. The decoder then predicts a sequence that is twice as long. Since the original target sequence length may be odd, the data collator makes sure to round the maximum length of the batch down to be a multiple of 2.
Copied
Train the model
Load the pre-trained model from the same checkpoint as you used for loading the processor:
Copied
The use_cache=True
option is incompatible with gradient checkpointing. Disable it for training.
Copied
Define the training arguments. Here we are not computing any evaluation metrics during the training process. Instead, we’ll only look at the loss:
Copied
Instantiate the Trainer
object and pass the model, dataset, and data collator to it.
Copied
And with that, you’re ready to start training! Training will take several hours. Depending on your GPU, it is possible that you will encounter a CUDA “out-of-memory” error when you start training. In this case, you can reduce the per_device_train_batch_size
incrementally by factors of 2 and increase gradient_accumulation_steps
by 2x to compensate.
Copied
To be able to use your checkpoint with a pipeline, make sure to save the processor with the checkpoint:
Copied
Push the final model to the 🌍 Hub:
Copied
Inference
Inference with a pipeline
Great, now that you’ve fine-tuned a model, you can use it for inference! First, let’s see how you can use it with a corresponding pipeline. Let’s create a "text-to-speech"
pipeline with your checkpoint:
Copied
Pick a piece of text in Dutch you’d like narrated, e.g.:
Copied
To use SpeechT5 with the pipeline, you’ll need a speaker embedding. Let’s get it from an example in the test dataset:
Copied
Now you can pass the text and speaker embeddings to the pipeline, and it will take care of the rest:
Copied
You can then listen to the result:
Copied
Run inference manually
You can achieve the same inference results without using the pipeline, however, more steps will be required.
Load the model from the 🌍 Hub:
Copied
Pick an example from the test dataset obtain a speaker embedding.
Copied
Define the input text and tokenize it.
Copied
Create a spectrogram with your model:
Copied
Visualize the spectrogram, if you’d like to:
Copied
Finally, use the vocoder to turn the spectrogram into sound.
Copied
In our experience, obtaining satisfactory results from this model can be challenging. The quality of the speaker embeddings appears to be a significant factor. Since SpeechT5 was pre-trained with English x-vectors, it performs best when using English speaker embeddings. If the synthesized speech sounds poor, try using a different speaker embedding.
Increasing the training duration is also likely to enhance the quality of the results. Even so, the speech clearly is Dutch instead of English, and it does capture the voice characteristics of the speaker (compare to the original audio in the example). Another thing to experiment with is the model’s configuration. For example, try using config.reduction_factor = 1
to see if this improves the results.
Finally, it is essential to consider ethical considerations. Although TTS technology has numerous useful applications, it may also be used for malicious purposes, such as impersonating someone’s voice without their knowledge or consent. Please use TTS judiciously and responsibly.
Last updated