{ "cells": [ { "cell_type": "markdown", "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6", "metadata": {}, "source": [ "# Fine-Tune Whisper With πŸ€— Transformers and Streaming Mode" ] }, { "cell_type": "markdown", "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a", "metadata": {}, "source": [ "In this Colab, we present a step-by-step guide on fine-tuning Whisper with Hugging Face πŸ€— Transformers on 400 hours of speech data! Using streaming mode, we'll show how you can train a speech recongition model on any dataset, irrespective of size. With streaming mode, storage requirements are no longer a consideration: you can train a model on whatever dataset you want, even if it's download size exceeds your devices disk space. How can this be possible? It simply seems too good to be true! Well, rest assured it's not πŸ˜‰ Carry on reading to find out more." ] }, { "cell_type": "markdown", "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e", "metadata": {}, "source": [ "## Introduction" ] }, { "cell_type": "markdown", "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0", "metadata": {}, "source": [ "Speech recognition datasets are large. A typical speech dataset consists of approximately 100 hours of audio-transcription data, requiring upwards of 130GB of storage space for download and preparation. For most ASR researchers, this is already at the upper limit of what is feasible for disk space. So what happens when we want to train on a larger dataset? The full [LibriSpeech](https://huggingface.co/datasets/librispeech_asr) dataset consists of 960 hours of audio data. Kensho's [SPGISpeech](https://huggingface.co/datasets/kensho/spgispeech) contains 5,000 hours of audio data. ML Commons [People's Speech](https://huggingface.co/datasets/MLCommons/peoples_speech) contains **30,000+** hours of audio data! Do we need to bite the bullet and buy additional storage? Or is there a way we can train on all of these datasets with no disk drive requirements?\n", "\n", "When training machine learning systems, we rarely use the entire dataset at once. We typically _batch_ our data into smaller subsets of data, and pass these incrementally through our training pipeline. This is because we train our system on an accelerator device, such as a GPU or TPU, which has a memory limit typically around 16GB. We have to fit our model, optimiser and training data all on the same accelerator device, so we usually have to divide the dataset up into smaller batches and move them from the CPU to the GPU when required.\n", "\n", "Consequently, we don't require the entire dataset to be downloaded at once; we simply need the batch of data that we pass to our model at any one go. We can leverage this principle of partial dataset loading when preparing our dataset: rather than downloading the entire dataset at the start, we can load each piece of data as and when we need it. For each batch, we load the relevant data from a remote server and pass it through the training pipeline. For the next batch, we load the next items and again pass them through the training pipeline. At no point do we have to save data to our disk drive, we simply load them in memory and use them in our pipeline. In doing so, we only ever need as much memory as each individual batch requires.\n", "\n", "This is analogous to downloading a TV show versus streaming it πŸ“Ί When we download a TV show, we download the entire video offline and save it to our disk. Compare this to when we stream a TV show. Here, we don't download any part of the video to memory, but iterate over the video file and load each part in real-time as required. It's this same principle that we can apply to our ML training pipeline! We want to iterate over the dataset and load each sample of data as required.\n", "\n", "While the principle of partial dataset loading sounds ideal, it also seems **pretty** difficult to do. Luckily for us, πŸ€— Datasets allows us to do this with minimal code changes! We'll make use of the principle of [_streaming_](https://huggingface.co/docs/datasets/stream), depicted graphically in Figure 1. Streaming does exactly this: the data is loaded progressively as we iterate over the dataset, meaning it is only loaded as and when we need it. If you're familiar with πŸ€— Transformers and Datasets, the content of this notebook will be very familiar, with some small extensions to support streaming mode." ] }, { "cell_type": "markdown", "id": "1c87f76e-47be-4a5d-bc52-7b1c2e9d4f5a", "metadata": {}, "source": [ "
\n", "\"Trulli\"\n", "
Figure 1: Streaming mode. The dataset is divided into smaller subsets, with subsets loaded progressively as we iterate over the dataset.
\n", "
" ] }, { "cell_type": "markdown", "id": "21b6316e-8a55-4549-a154-66d3da2ab74a", "metadata": {}, "source": [ "This notebook provides a guide to fine-tuning on the task of _speech recognition_, which involves learning a\n", "mapping from speech to text. Speech recognition is divided into two categories: English-only or multilingual (all other languages). \n", "This notebook applies to both categories, with pointers for changing between languages and datasets.\n", "\n", "As for our model, we'll fine-tune the Whisper model released in [September 2022](https://openai.com/blog/whisper/) by the authors \n", "Alec Radford et al. from OpenAI. Whisper is an encoder-decoder model pre-trained on 680k hours of labelled audio-transcription data. \n", "It achieves strong performance on many speech recognition and speech translation datasets without fine-tuning. With fine-tuning, \n", "we aim to improve upon these results further, with many SoTA results up for grabs! For a full explanation on the Whisper model, the \n", "reader is advised to read the blog post [Fine-Tune Whisper with πŸ€— Transformers](https://huggingface.co/blog/fine-tune-whisper#introduction).\n", "\n", "The Whisper checkpoints come in five configurations of varying model sizes.\n", "The smallest four are trained on either English-only or multilingual data.\n", "The largest checkpoint is multilingual only. All nine of the pre-trained checkpoints \n", "are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The \n", "checkpoints are summarised in the following table with links to the models on the Hub:\n", "\n", "| Size | Layers | Width | Heads | Parameters | English-only | Multilingual |\n", "|--------|--------|-------|-------|------------|------------------------------------------------------|---------------------------------------------------|\n", "| tiny | 4 | 384 | 6 | 39 M | [βœ“](https://huggingface.co/openai/whisper-tiny.en) | [βœ“](https://huggingface.co/openai/whisper-tiny.) |\n", "| base | 6 | 512 | 8 | 74 M | [βœ“](https://huggingface.co/openai/whisper-base.en) | [βœ“](https://huggingface.co/openai/whisper-base) |\n", "| small | 12 | 768 | 12 | 244 M | [βœ“](https://huggingface.co/openai/whisper-small.en) | [βœ“](https://huggingface.co/openai/whisper-small) |\n", "| medium | 24 | 1024 | 16 | 769 M | [βœ“](https://huggingface.co/openai/whisper-medium.en) | [βœ“](https://huggingface.co/openai/whisper-medium) |\n", "| large | 32 | 1280 | 20 | 1550 M | x | [βœ“](https://huggingface.co/openai/whisper-large) |\n", "\n", "When fine-tuning on an English dataset for speech recognition, it is recommeneded to select one of the English-only checkpoints. For any other language, it is recommended to select a multilingual checkpoint.\n", "\n", "For demonstration purposes, we'll fine-tune the multilingual version of the \n", "[`\"small\"`](https://huggingface.co/openai/whisper-small) checkpoint with 244M params (~= 1GB). \n", "As for our data, we'll train and evaluate our system on 400 hours of multilingual speech recognition data\n", "taken from the [Common Voice 11](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n", "dataset. We'll show how we can train a model on 400 hours of training data using the default disk space \n", "that comes with a standard GPU device or Google Colab." ] }, { "cell_type": "markdown", "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0", "metadata": {}, "source": [ "## Load Dataset with Streaming" ] }, { "cell_type": "markdown", "id": "b17a4763-4381-4157-ae38-b04a8b5f1c43", "metadata": {}, "source": [ "This is where the magic happens! We'll first write a wrapper function around πŸ€— Datasets `load_dataset` method. This function downloads the required splits using streaming mode by forcing `streaming=True` in the `load_dataset` method. Multiple splits can be combined (interleaved) by concatenating them with the \"+\" symbol when specifying the split name, e.g. `split=train+validation` will return a single split with the training and validation splits interleaved together. The function has the same arguments and key-word arguments as πŸ€— Datasets `load_dataset` method, so we can use it in exactly the same way!" ] }, { "cell_type": "code", "execution_count": 1, "id": "065a8cf7-e54f-4ac3-900e-609c80714fca", "metadata": {}, "outputs": [], "source": [ "from datasets import interleave_datasets, load_dataset\n", "\n", "def load_streaming_dataset(dataset_name, dataset_config_name, split, **kwargs):\n", " if \"+\" in split:\n", " # load multiple splits separated by the `+` symbol *with* streaming mode\n", " dataset_splits = [load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=True, **kwargs) for split_name in split.split(\"+\")]\n", " # interleave multiple splits to form one dataset\n", " interleaved_dataset = interleave_datasets(dataset_splits)\n", " return interleaved_dataset\n", " else:\n", " # load a single split *with* streaming mode\n", " dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=True, **kwargs)\n", " return dataset" ] }, { "cell_type": "markdown", "id": "674429c5-0ab4-4adf-975b-621bb69eca38", "metadata": {}, "source": [ "We'll train our system on the Spanish split of [Common Voice 11](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0). We can see how much training data we have by viewing the [language page](https://commonvoice.mozilla.org/en/datasets) on the Common Voice website. The Spanish split has over 400 hours of labelled training data - that's enourmous! More than we could ever fit on a Google Colab or a standard workstation. But with streaming mode, we'll only download data as and when we need it, making training on this dataset possible!\n", "\n", "Since Spanish is relatively high-resource, we'll only use the `train` split for training and the `test` split for evaluation. If you're training on a low-resource language, such as the Hindi split of Common Voice 11, it's worth combining the `train` and `validation` splits to give a larger training set. You can achieve this by setting: `split=\"train+validation\"` for the training split.\n", "\n", "If you're using a gated dataset, like Common Voice 11, ensure you have accepted the terms of use on the Hugging Face Hub: [mozilla-foundation/common_voice_11_0](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0). Once you have accepted the terms, you will have full access to the dataset and be able to load the data locally." ] }, { "cell_type": "code", "execution_count": 2, "id": "a2787582-554f-44ce-9f38-4180a5ed6b44", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ecce3a630cdb4ebab217a88a0163b257", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading builder script: 0%| | 0.00/8.30k [00:00 Dict[str, torch.Tensor]:\n", " # split inputs and labels since they have to be of different lengths and need different padding methods\n", " # first treat the audio inputs by simply returning torch tensors\n", " input_features = [{\"input_features\": feature[\"input_features\"]} for feature in features]\n", " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n", "\n", " # get the tokenized label sequences\n", " label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n", " # pad the labels to max length\n", " labels_batch = self.processor.tokenizer.pad(label_features, return_tensors=\"pt\")\n", "\n", " # replace padding with -100 to ignore loss correctly\n", " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n", "\n", " # if bos token is appended in previous tokenization step,\n", " # cut bos token here as it's append later anyways\n", " if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():\n", " labels = labels[:, 1:]\n", "\n", " batch[\"labels\"] = labels\n", "\n", " return batch" ] }, { "cell_type": "markdown", "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86", "metadata": {}, "source": [ "Let's initialise the data collator we've just defined:" ] }, { "cell_type": "code", "execution_count": 13, "id": "fc834702-c0d3-4a96-b101-7b87be32bf42", "metadata": {}, "outputs": [], "source": [ "data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)" ] }, { "cell_type": "markdown", "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698", "metadata": {}, "source": [ "### Evaluation Metrics" ] }, { "cell_type": "markdown", "id": "66fee1a7-a44c-461e-b047-c3917221572e", "metadata": {}, "source": [ "We'll use the word error rate (WER) metric, the 'de-facto' metric for assessing \n", "ASR systems. For more information, refer to the WER [docs](https://huggingface.co/metrics/wer). We'll load the WER metric from πŸ€— Evaluate:" ] }, { "cell_type": "code", "execution_count": 14, "id": "b22b4011-f31f-4b57-b684-c52332f92890", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "bafc0b31fe9a4d239eedc348d5521dfc", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading builder script: 0%| | 0.00/4.49k [00:00 0]\n", " label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]\n", "\n", " wer = 100 * metric.compute(predictions=pred_str, references=label_str)\n", "\n", " return {\"wer\": wer}" ] }, { "cell_type": "markdown", "id": "daf2a825-6d9f-4a23-b145-c37c0039075b", "metadata": {}, "source": [ "###Β Load a Pre-Trained Checkpoint" ] }, { "cell_type": "markdown", "id": "437a97fa-4864-476b-8abc-f28b8166cfa5", "metadata": {}, "source": [ "Now let's load the pre-trained Whisper `small` checkpoint. Again, this \n", "is trivial through use of πŸ€— Transformers!" ] }, { "cell_type": "code", "execution_count": 16, "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e1d5d79e596a416aa96bde21be6fb551", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading: 0%| | 0.00/1.97k [00:00\n", " \n", " \n", " [ 35/5000 03:29 < 8:46:02, 0.16 it/s, Epoch 0.01/9223372036854775807]\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining LossValidation Loss

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "trainer.train()" ] }, { "cell_type": "markdown", "id": "747c6a6e", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "(note that training may take some time to commence as we load the first training data samples with streaming mode)" ] }, { "cell_type": "markdown", "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3", "metadata": {}, "source": [ "We can label our checkpoint with the `whisper-event` tag on push by setting the appropriate key-word arguments (kwargs):" ] }, { "cell_type": "code", "execution_count": 40, "id": "6dd0e310-9b07-4133-ac14-2ed2d7524e22", "metadata": {}, "outputs": [], "source": [ "kwargs = {\n", " \"dataset_tags\": \"mozilla-foundation/common_voice_11_0\",\n", " \"dataset\": \"Common Voice 11.0\", # a 'pretty' name for the training dataset\n", " \"language\": \"zh\",\n", " \"model_name\": \"Whisper Small Chinese - Kimbo Chen\", # a 'pretty' name for your model\n", " \"finetuned_from\": \"openai/whisper-small\",\n", " \"tasks\": \"automatic-speech-recognition\",\n", " \"tags\": \"whisper-event\",\n", "}" ] }, { "cell_type": "markdown", "id": "090d676a-f944-4297-a938-a40eda0b2b68", "metadata": {}, "source": [ "The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command:" ] }, { "cell_type": "code", "execution_count": 41, "id": "95737cda-c5dd-4887-a4d0-dfcb0d61d977", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Saving model checkpoint to ./\n", "Configuration saved in ./config.json\n", "Model weights saved in ./pytorch_model.bin\n", "Feature extractor saved in ./preprocessor_config.json\n", "tokenizer config file saved in ./tokenizer_config.json\n", "Special tokens file saved in ./special_tokens_map.json\n", "added tokens file saved in ./added_tokens.json\n", "Several commits (2) will be pushed upstream.\n", "The progress bars may be unreliable.\n", "To https://huggingface.co/kimbochen/whisper-small-zh-tw\n", " 61dfe27..a94bfc3 main -> main\n", "\n" ] }, { "data": { "text/plain": [ "'https://huggingface.co/kimbochen/whisper-small-zh-tw/commit/a94bfc3cbb71b83e10525899df53ee0d4db96e32'" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "trainer.push_to_hub(**kwargs)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 5 }