int8 training for automatic speech recognition
Last updated
Last updated
Quantization reduces the precision of floating point data types, decreasing the memory required to store model weights. However, quantization degrades inference performance because you lose information when you reduce the precision. 8-bit or int8
quantization uses only a quarter precision, but it does not degrade performance because it doesn’t just drop the bits or data. Instead, int8
quantization rounds from one data type to another.
💡 Read the paper to learn more, or you can take a look at the corresponding for a gentler introduction.
This guide will show you how to train a model for multilingual automatic speech recognition (ASR) using a combination of int8
quantization and LoRA. You’ll train Whisper for multilingual ASR on Marathi from the dataset.
Before you start, make sure you have all the necessary libraries installed:
Copied
Let’s take care of some of the setup first so you can start training faster later. Set the CUDA_VISIBLE_DEVICES
to 0
to use the first GPU on your machine. Then you can specify the model name (either a Hub model repository id or a path to a directory containing the model), language and language abbreviation to train on, the task type, and the dataset name:
Copied
You can also log in to your BOINC AI account to save and share your trained model on the Hub if you’d like:
Copied
Copied
Let’s prepare the dataset for training. Load a feature extractor, tokenizer, and processor. You should also pass the language and task to the tokenizer and processor so they know how to process the inputs:
Copied
Copied
Copied
Once you’ve cleaned up the dataset, you can write a function to generate the correct model inputs. The function should:
Resample the audio inputs to 16kHZ by loading the audio
column.
Compute the input features from the audio array
using the feature extractor.
Tokenize the sentence
column to the input labels.
Copied
Copied
Finally, create a DataCollator
class to pad the labels in each batch to the maximum length, and replace padding with -100
so they’re ignored by the loss function. Then initialize an instance of the data collator:
Copied
Copied
You should configure forced_decoder_ids=None
because no tokens are used before sampling, and you won’t need to suppress any tokens during generation either:
Copied
casts all the non int8
modules to full precision (fp32
) for stability
adds a forward hook to the input embedding layer to calculate the gradients of the input hidden states
enables gradient checkpointing for more memory-efficient training
Copied
r
, the dimension of the low-rank matrices
lora_alpha
, scaling factor for the weight matrices
target_modules
, the name of the attention matrices to apply LoRA to (q_proj
and v_proj
, or query and value in this case)
lora_dropout
, dropout probability of the LoRA layers
bias
, set to none
💡 The weight matrix is scaled by lora_alpha/r
, and a higher lora_alpha
value assigns more weight to the LoRA activations. For performance, we recommend setting bias to None
first, and then lora_only
, before trying all
.
Copied
Copied
Copied
Copied
Copied
Copied
Copied
Copied
Let’s test the model out now!
Copied
Copied
Then use the pipeline with autocast as a context manager on the audio sample:
Copied
The dataset contains many hours of recorded speech in many different languages. This guide uses the language as an example, but feel free to use any other language you’re interested in.
Initialize a structure, and load the train
(load both the train+validation
split into train
) and test
splits from the dataset into it:
You’ll only be training on the sentence
and audio
columns, so you can remove the rest of the metadata with :
If you look at the sampling_rate
, you’ll see the audio was sampled at 48kHz. The Whisper model was pretrained on audio inputs at 16kHZ which means you’ll need to downsample the audio inputs to match what the model was pretrained on. Downsample the audio by using the method on the audio
column, and set the sampling_rate
to 16kHz. The audio input is resampled on the fly the next time you call it:
Apply the prepare_dataset
function to the dataset with the function, and set the num_proc
argument to 2
to enable multiprocessing (if map
hangs, then set num_proc=1
):
Now that the dataset is ready, you can turn your attention to the model. Start by loading the pretrained model from , and make sure to set the load_in_8bit
argument to True
to enable int8
quantization. The device_map=auto
argument automatically determines how to load and store the model weights:
To get the model ready for int8
quantization, use the utility function to handle the following:
Let’s also apply LoRA to the training to make it even more efficient. Load a and configure the following parameters:
After you set up the , wrap it and the base model with the get_peft_model()
function to create a . Print out the number of trainable parameters to see how much more efficient LoRA is compared to fully training the model!
Now you’re ready to define some training hyperparameters in the class, such as where to save the model to, batch size, learning rate, and number of epochs to train for. The doesn’t have the same signature as the base model, so you’ll need to explicitly set remove_unused_columns=False
and label_names=["labels"]
.
It is also a good idea to write a custom to save model checkpoints during training:
Pass the Seq2SeqTrainingArguments
, model, datasets, data collator, tokenizer, and callback to the . You can optionally set model.config.use_cache = False
to silence any warnings. Once everything is ready, call to start training!
(WER) is a common metric for evaluating ASR models. Load the WER metric from 🤗 Evaluate:
Write a loop to evaluate the model performance. Set the model to evaluation mode first, and write the loop with because int8
training requires autocasting. Then, pass a batch of examples to the model to evaluate. Get the decoded predictions and labels, and add them as a batch to the WER metric before calling compute
to get the final WER score:
Once you’re happy with your results, you can upload your model to the Hub with the method:
Instantiate the model configuration from , and from here, you can use the configuration to load the base and , tokenizer, processor, and feature extractor. Remember to define the language
and task
in the tokenizer, processor, and forced_decoder_ids
:
Load an audio sample (you can listen to it in the ) to transcribe, and the :