Views
No views yet
distil-whisper repository by clicking on the fork button on the reopsitory's pagedistil-whisper repository and add the base repository as a remote. This will allow you to "pull" any upstream changes that are made to the base repository:1git clone https://github.com/<your GitHub handle>/distil-whisper.git
2cd distil-whisper
3git remote add upstream https://github.com/huggingface/distil-whisper.git1cd training
2pip install -e .
3cd ../..bfloat16 on A100 GPUs, float16 on V100 GPUs, etc.):accelerate config1git config --global credential.helper store
2huggingface-cli login1from transformers import WhisperProcessor, WhisperForConditionalGeneration
2from datasets import load_dataset, Audio
3
4model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny", low_cpu_mem_usage=True)
5processor = WhisperProcessor.from_pretrained("openai/whisper-tiny")
6
7model.to("cuda")
8
9common_voice = load_dataset("mozilla-foundation/common_voice_16_1", "en", split="validation", streaming=True)
10common_voice = common_voice.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
11
12inputs = processor(next(iter(common_voice))["audio"]["array"], sampling_rate=16000, return_tensors="pt")
13input_features = inputs.input_features
14
15generated_ids = model.generate(input_features.to("cuda"), max_new_tokens=128)
16pred_text = processor.decode(generated_ids[0], skip_special_tokens=True)
17
18print("Pred text:", pred_text)
19print("Environment set up successful?", generated_ids.shape[-1] == 20)run_pseudo_labelling.py is a flexible inference script that can be used
to generate pseudo-labels under a range of settings, including using both greedy and beam-search. It is also compatible
with 🤗 Datasets streaming mode, allowing users to load massive audio
datasets with no disk space requirements. For more information on streaming mode, the reader is referred to the
blog post: A Complete Guide to Audio Datasets.As of the latest Distil-Whisper release,distil-large-v3, this pseudo-labelling script also performs the added operation of concatenating (or packing) the audio inputs to 30-seconds. Not only does this lead to a WER improvement when using sequential long-form decoding algorithm, but concatenating audios to 30-seconds also improves the throughput during training, since the amount of zero-padding on the audio inputs is minimised.
1#!/usr/bin/env bash
2
3accelerate launch run_pseudo_labelling.py \
4 --model_name_or_path "openai/whisper-large-v3" \
5 --dataset_name "mozilla-foundation/common_voice_16_1" \
6 --dataset_config_name "hi" \
7 --dataset_split_name "train+validation+test" \
8 --text_column_name "sentence" \
9 --id_column_name "path" \
10 --output_dir "./common_voice_16_1_hi_pseudo_labelled" \
11 --wandb_project "distil-whisper-labelling" \
12 --per_device_eval_batch_size 64 \
13 --dtype "bfloat16" \
14 --attn_implementation "sdpa" \
15 --logging_steps 500 \
16 --max_label_length 256 \
17 --concatenate_audio \
18 --preprocessing_batch_size 500 \
19 --preprocessing_num_workers 8 \
20 --dataloader_num_workers 8 \
21 --report_to "wandb" \
22 --language "hi" \
23 --task "transcribe" \
24 --return_timestamps \
25 --streaming False \
26 --generation_num_beams 1 \
27 --push_to_hubconcatenate_audio: whether or not to concatenate (or pack) the audios to 30-second chunks. The latest Distil-Whisper model, distil-large-v3, highlights the WER improvements obtained using the sequential long-form decoding algorithm when concatenated audios are used. Concatenating audios to 30-seconds also improves the throughput during training, since the amount of zero-padding on the audio inputs is minimised. Hence, it is highly recommended to set --concatenate_audio=True.preprocessing_batch_size: the batch size to use when concatenating (or packing) the audios. Using a larger batch size results in a greater portion of audio samples being packed to 30-seconds, at the expense of higher memory consumption. If you exceed your system's RAM when performing the concatenation operation, reduce the preprocessing_batch_size by a factor of 2 to 250 or even 125.preprocessing_num_workers: the number of multiprocessing workers to use when concatenating the audios. Using more workers will result in faster pre-processing, at the expense of higher memory consumption. Ensure you do not exceed the maximum number of CPUs on your device.language: explicitly setting the language token during inference substantially improves the generation performance of the Whisper model, since the model is forced always to predict in the given language. We recommend you set the language to the language you wish to distil the Whisper model on. The only exception is when distilling an English-only model (i.e. where the model id is appended with an .en, e.g. small.en), the language argument should be set to None, since there is no language token used during training/inference.return_timestamps: whether or not to predict timestamps in the pseudo-labels. Timestamp prediction is required should you want your distilled model to be able to predict timestamps at inference time (e.g. for the original OpenAI long-form transcription algorithm). However, the pseudo-labels are marginally less accurate than not using timestamps. We recommend pseudo-labelling with timestamps to ensure the distilled model is as general as possible.attn_implementation: which attention implementation to use for inference. Set to sdpa for PyTorch SDPA, or flash_attn_2 if your hardware supports Flash Attention 2 and you have the package installed.streaming: whether or not to use Datasets' streaming mode. If enabled, the audio data will be streamed from the Hugging Face Hub with no disk space requirements. However, the user is then responsible for adding the pseudo-labels to the dataset script in a follow-up step (see Using Streaming Mode). If set to False, the audio data will be downloaded and pre-processed offline. At the end of pseudo-labelling, the pseudo-labels will be automatically appended to the original dataset, meaning the dataset is ready to be used for the subsequent training step without any additional steps.generation_num_beams: how many beams to use while decoding. In practice, we found the distilled model to perform comparably when the data was pseudo-labelled with generation_num_beams=1 (greedy) or generation_num_beams>1 (beam). This is likely because the WER filter compensates for the lower quality pseudo-labels obtained using greedy search. However, using generation_num_beams=1 gives substantially faster inference time for the pseudo-labelling step, and so we recommend this configuration.--dataset_name with the name of your dataset on the Hub.| Dataset | Languages | Domain | Speaking Style | License | Text Column | ID Column |
|---|---|---|---|---|---|---|
| Multilingual LibriSpeech | 6 | Audiobooks | Narrated | CC-BY-4.0 | "text" | "id" |
| Common Voice 16 | 120 | Wikipedia text & crowd-sourced speech | Narrated | CC0-1.0 | "sentence" | "path" |
| VoxPopuli | 15 | European Parliament recordings | Spontaneous | CC0 | "normalized_text" | "audio_id" |
create_student_model.py can be used to initialise a small student model
from a large teacher model. When initialising a student model with fewer layers than the teacher model, the student is
initialised by copying maximally spaced layers from the teacher, as per the DistilBart
recommendations.distil-whisper-large-v3-hi. We can run the following command to create a repository under this name:huggingface-cli repo create distil-whisper-large-v3-hi1git lfs install
2git clone https://huggingface.co/sanchit-gandhi/distil-whisper-large-v3-hihttps://huggingface.co/<your-user-name>/<your-repo-name>1cd distil-whisper-large-v3-hi
2
3cp ../distil-whisper/training/create_student_model.py .
4cp ../distil-whisper/training/run_distillation.py .1#!/usr/bin/env bash
2
3python create_student_model.py \
4 --teacher_checkpoint "openai/whisper-large-v3" \
5 --encoder_layers 32 \
6 --decoder_layers 2 \
7 --save_dir "./distil-large-v3-init"distil-large-v3-init in our model repository.run_distillation.py is an end-to-end script for loading multiple
datasets, a student model, a teacher model, and performing teacher-student distillation. It uses the loss formulation
from the Distil-Whisper paper, which is a weighted sum of the cross-entropy and
KL-divergence loss terms.../common_voice_16_1_hi_pseudo_labelled), which you can change to the path where your local pseudo-labelled dataset is
saved.+ symbols. Thus, the script generalises
to any number of training datasets.1#!/usr/bin/env bash
2
3accelerate launch run_distillation.py \
4 --model_name_or_path "./distil-large-v3-init" \
5 --teacher_model_name_or_path "openai/whisper-large-v3" \
6 --train_dataset_name "../common_voice_16_1_hi_pseudo_labelled+../common_voice_16_1_hi_pseudo_labelled" \
7 --train_split_name "train+validation" \
8 --text_column_name "sentence+sentence" \
9 --train_dataset_samples "7+4" \
10 --eval_dataset_name "../common_voice_16_1_hi_pseudo_labelled" \
11 --eval_split_name "test" \
12 --eval_text_column_name "sentence" \
13 --eval_steps 1000 \
14 --save_steps 1000 \
15 --warmup_steps 50 \
16 --learning_rate 0.0001 \
17 --lr_scheduler_type "constant_with_warmup" \
18 --timestamp_probability 0.2 \
19 --condition_on_prev_probability 0.2 \
20 --language "hi" \
21 --task "transcribe" \
22 --logging_steps 25 \
23 --save_total_limit 1 \
24 --max_steps 5000 \
25 --wer_threshold 20 \
26 --per_device_train_batch_size 32 \
27 --per_device_eval_batch_size 32 \
28 --dataloader_num_workers 8 \
29 --preprocessing_num_workers 8 \
30 --ddp_timeout 7200 \
31 --dtype "bfloat16" \
32 --attn_implementation "sdpa" \
33 --output_dir "./" \
34 --do_train \
35 --do_eval \
36 --gradient_checkpointing \
37 --overwrite_output_dir \
38 --predict_with_generate \
39 --freeze_encoder \
40 --freeze_embed_positions \
41 --streaming False \
42 --push_to_hub
43accelerate config and select the multi-GPU option, specifying the IDs of the GPUs you wish to use. The
above script can then be run using DDP with no code changes.train_dataset_samples: defines the number of training samples in each dataset. Used to calculate the sampling probabilities in the dataloader. A good starting point is setting the samples to the number of hours of audio data in each split. A more refined strategy is setting it to the number of training samples in each split, however this might require downloading the dataset offline to compute these statistics.wer_threshold: sets the WER threshold between the normalised pseudo-labels and normalised ground truth labels. Any samples with WER > wer_threshold are discarded from the training data. This is beneficial to avoid training the student model on pseudo-labels where Whisper hallucinated or got the predictions grossly wrong. In our English distillation experiments, we found a WER threshold of 10% provides the optimal trade-off between ensuring high-quality transcriptions, and not filtering unnecessary amounts of training data. For multilingual distillation, the threshold should be set in accordance with the WER achieved by the pre-trained model on the test set.streaming: whether or not to use Datasets' streaming mode. Recommended for large datasets, where the audio data can be streamed from the Hugging Face Hub with no disk space requirements.timestamp_probability: the per-sample probability for retaining timestamp tokens in the labels (should they contain them). Retaining some portion of timestamp tokens in the training data is required to ensure the distilled model can predict timestamps at inference time. In our experiments, we found that training on timestamps with high-probability hurts the distilled model's transcription performance. Thus, we recommend setting this to a value below 0.5. Typically, a value of 0.2 works well, giving good transcription and timestamp performance.condition_on_prev_probability: the per-sample probability for conditioning on previous labels. Conditioning on previous tokens is required to ensure the distilled model can be used with the "sequential" long-form transcription algorithm at inference time. We did not experiment with this parameter, but found values around 0.2 to provide adequate performance. OpenAI pre-trained Whisper on with a 50% probability for conditioning on previous tokens. Thus, you might wish to try higher values.freeze_encoder: whether to freeze the entire encoder of the student model during training. Beneficial when the student encoder is copied exactly from the teacher encoder. In this case, the encoder hidden-states from the teacher model are re-used for the student model. Stopping the gradient computation through the encoder and sharing the encoder hidden-states provides a significant memory saving, and can enable up to 2x batch sizes.freeze_embed_positions: whether to freeze the student model's decoder positional embeddings. Using the same embed positions as the teacher model, which is designed to handle context lengths up to 448 tokens, helps the student model retain its input id representation up to the full max input length.dtype: data type (dtype) in which the model computation should be performed. Note that this only controls the dtype of the computations (forward and backward pass), and not the dtype of the parameters or optimiser states.max_steps: defines the total number of optimisation steps (forward + backward pass) during training. To reach convergence, you should use a dataset of at least 1k hours and train for a minimum of 50k steps.lr_scheduler_stype: defines the learning rate schedule, one of constant_with_warmup or linear. When experimenting with a training set-up or training for very few steps (< 5k), using constant_with_warmup is typically beneficial, since the learning rate remains high over the short training run. When performing long training runs (> 5k), using a linear schedule generally results in superior downstream performance of the distilled model.run_eval.py. Unlike the pseudo-labelling
and training scripts, the evaluation script assumes that only one GPU accelerator is used. We can copy the corresponding
evaluation script to the model repository using the following command:cp ../distil-whisper/training/run_eval.py .audio input time : model compute time. A higher RTFx indicates a faster model.run_eval.py can be used to evaluate a trained student model over multiple short-form
validation sets. The following example demonstrates how to evaluate the student model trained in the previous step on
the Common Voice test set (ID) and also the FLEURS test set (OOD). Again, it leverages streaming mode to bypass
the need to download the data offline:1#!/usr/bin/env bash
2
3python run_eval.py \
4 --model_name_or_path "./" \
5 --dataset_name "../common_voice_16_1_hi_pseudo_labelled+google/fleurs" \
6 --dataset_config_name "default+hi_in" \
7 --dataset_split_name "test+test" \
8 --text_column_name "sentence+transcription" \
9 --batch_size 16 \
10 --dtype "bfloat16" \
11 --generation_max_length 256 \
12 --language "hi" \
13 --attn_implementation "sdpa" \
14 --streaming
15model_name_or_path to openai/whisper-large-v3, which
achieves an average WER of TODO% with an RTFx of TODO. Therefore, for a batch size of 16, the student model is a factor of TODO
times faster than the teacher. The WER gap can be closed by training on more data (at least 1k hours) for more training
steps (at least 50k)..generate
method in Transformers.run_eval.py can be used to evaluate the trained student model on an arbitrary number of
long-form evaluation sets using the sequential algorithm. Since we don't have a long-form validation set for Hindi to hand,
in this example we'll evaluate the official Distil-Whisper model distil-large-v3
on the TED-LIUM validation set:1#!/usr/bin/env bash
2
3accelerate launch run_eval.py \
4 --model_name_or_path "distil-whisper/distil-large-v3" \
5 --dataset_name "distil-whisper/tedlium-long-form" \
6 --dataset_config_name "default" \
7 --dataset_split_name "validation" \
8 --text_column_name "text" \
9 --batch_size 16 \
10 --dtype "bfloat16" \
11 --generation_max_length 256 \
12 --language "en" \
13 --attn_implementation "sdpa" \
14 --streaming
15pipeline
class, which provides a wrapper around the .generate
function for long-form inference.run_eval.py can be used to evaluate the trained student model on an arbitrary number of
long-form evaluation sets using the pipeline class. Again, in this example we'll evaluate distil-large-v3 on the
TED-LIUM validation set:1#!/usr/bin/env bash
2
3python run_eval.py \
4 --model_name_or_path "openai/whisper-large-v3" \
5 --dataset_name "distil-whisper/tedlium-long-form" \
6 --dataset_config_name "default" \
7 --dataset_split_name "validation" \
8 --text_column_name "text" \
9 --use_pipeline \
10 --chunk_length_s 25.0 \
11 --language "en" \
12 --return_timestamps \
13 --dtype "bfloat16" \
14 --streaming
15chunk_length_s controls the length of the chunked audio samples. It should be set to match the typical
length of audio the student model was trained on. If unsure about what value of chunk_length_s is optimal for your case,
it is recommended to run a sweep over all possible values. A template script for running a WandB sweep
can be found under run_chunk_length_s_sweep.yaml.1#!/usr/bin/env bash
2
3python run_eval.py \
4 --model_name_or_path "openai/whisper-large-v3" \
5 --assistant_model_name_or_path "./" \
6 --dataset_name "../common_voice_16_1_hi_pseudo_labelled+google/fleurs" \
7 --dataset_config_name "default+hi_in" \
8 --dataset_split_name "test+test" \
9 --text_column_name "sentence+transcription" \
10 --batch_size 16 \
11 --dtype "bfloat16" \
12 --generation_max_length 256 \
13 --language "hi" \
14 --attn_implementation "sdpa" \
15 --streaming
16| Method | Pre-Trained WER / % | Training Data / h |
|---|---|---|
| Fine-tuning | > 20 | < 1000 |
| KD | < 20 | > 1000 |
@misc{gandhi2023distilwhisper,
title={Distil-Whisper: Robust Knowledge Distillation via Large-Scale Pseudo Labelling},
author={Sanchit Gandhi and Patrick von Platen and Alexander M. Rush},
year={2023},
eprint={2311.00430},
archivePrefix={arXiv},
primaryClass={cs.CL}
}