{ "cells": [ { "cell_type": "markdown", "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6", "metadata": { "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6" }, "source": [ "# Fine-Tune Whisper For Multilingual ASR with 🤗 Transformers" ] }, { "cell_type": "code", "execution_count": 1, "id": "adbcd467-b895-4db4-aab7-21a5fa73d1d5", "metadata": {}, "outputs": [ { "ename": "ModuleNotFoundError", "evalue": "No module named 'datasets'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtyping\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mAny\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mDict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mList\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mOptional\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mUnion\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mdatasets\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mdatasets\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mDatasetDict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mIterableDatasetDict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minterleave_datasets\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mload_dataset\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'datasets'" ] } ], "source": [ "import logging\n", "import os\n", "import sys\n", "from dataclasses import dataclass, field\n", "from typing import Any, Dict, List, Optional, Union\n", "\n", "import datasets\n", "import torch\n", "from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset\n", "from torch.utils.data import IterableDataset\n", "\n", "def load_multiple_streaming_datasets(\n", " dataset_names: List,\n", " dataset_config_names: List,\n", " splits: Optional[List] = None,\n", " text_column_names: Optional[List] = None,\n", " sampling_rate: Optional[int] = 16000,\n", " stopping_strategy: Optional[str] = \"first_exhausted\",\n", " **kwargs\n", ") -> IterableDataset:\n", "\n", " if len(dataset_names) != len(dataset_config_names):\n", " raise ValueError(\n", " f\"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and\"\n", " f\" {len(dataset_config_names)} configs.\"\n", " )\n", "\n", " if splits is not None and len(splits) != len(dataset_names):\n", " raise ValueError(\n", " f\"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits.\"\n", " )\n", "\n", " if text_column_names is not None and len(text_column_names) != len(dataset_names):\n", " raise ValueError(\n", " f\"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and\"\n", " f\" {len(text_column_names)} text column names.\"\n", " )\n", "\n", " splits = splits if splits is not None else [\"train\" for i in range(len(dataset_names))]\n", " text_column_names = (\n", " text_column_names if text_column_names is not None else [\"text\" for i in range(len(dataset_names))]\n", " )\n", "\n", " all_datasets = []\n", " # iterate over the datasets we want to interleave\n", " for i, dataset_name in enumerate(dataset_names):\n", " dataset = load_dataset(dataset_name, dataset_config_names[i], split=splits[i], streaming=True, **kwargs)\n", " # resample to specified sampling rate\n", " dataset = dataset.cast_column(\"audio\", Audio(sampling_rate))\n", " # normalise columns to [\"audio\", \"sentence\"]\n", " if text_column_names[i] != \"sentence\":\n", " dataset = dataset.rename_column(text_column_names[i], \"sentence\")\n", " dataset = dataset.remove_columns(set(dataset.features.keys()) - set([\"audio\", \"sentence\"]))\n", " all_datasets.append(dataset)\n", "\n", " interleaved_dataset = interleave_datasets(all_datasets, stopping_strategy=stopping_strategy)\n", " return interleaved_dataset\n", "\n", "\n", "\n", "dataset_names = [\"mozilla-foundation/common_voice_11_0\", \"arbml/mgb2_speech\", ]\n", "dataset_config_names = [\"ar\", \"ar\", ]\n", "text_column_names = [\"sentence\", \"text\",]\n", "splits = [\"train\",\"train\"]\n", "\n", "ds = load_multiple_streaming_datasets(\n", " dataset_names,\n", " dataset_config_names=dataset_config_names,\n", " text_column_names=text_column_names,\n", " use_auth_token=True\n", " )\n" ] }, { "cell_type": "code", "execution_count": null, "id": "edf35b20-4872-4e14-bc5c-cc4e1a4eec37", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a", "metadata": { "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a" }, "source": [ "In this Colab, we present a step-by-step guide on how to fine-tune Whisper \n", "for any multilingual ASR dataset using Hugging Face 🤗 Transformers. This is a \n", "more \"hands-on\" version of the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). \n", "For a more in-depth explanation of Whisper, the Common Voice dataset and the theory behind fine-tuning, the reader is advised to refer to the blog post." ] }, { "cell_type": "markdown", "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e", "metadata": { "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e" }, "source": [ "## Introduction" ] }, { "cell_type": "markdown", "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0", "metadata": { "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0" }, "source": [ "Whisper is a pre-trained model for automatic speech recognition (ASR) \n", "published in [September 2022](https://openai.com/blog/whisper/) by the authors \n", "Alec Radford et al. from OpenAI. Unlike many of its predecessors, such as \n", "[Wav2Vec 2.0](https://arxiv.org/abs/2006.11477), which are pre-trained \n", "on un-labelled audio data, Whisper is pre-trained on a vast quantity of \n", "**labelled** audio-transcription data, 680,000 hours to be precise. \n", "This is an order of magnitude more data than the un-labelled audio data used \n", "to train Wav2Vec 2.0 (60,000 hours). What is more, 117,000 hours of this \n", "pre-training data is multilingual ASR data. This results in checkpoints \n", "that can be applied to over 96 languages, many of which are considered \n", "_low-resource_.\n", "\n", "When scaled to 680,000 hours of labelled pre-training data, Whisper models \n", "demonstrate a strong ability to generalise to many datasets and domains.\n", "The pre-trained checkpoints achieve competitive results to state-of-the-art \n", "ASR systems, with near 3% word error rate (WER) on the test-clean subset of \n", "LibriSpeech ASR and a new state-of-the-art on TED-LIUM with 4.7% WER (_c.f._ \n", "Table 8 of the [Whisper paper](https://cdn.openai.com/papers/whisper.pdf)).\n", "The extensive multilingual ASR knowledge acquired by Whisper during pre-training \n", "can be leveraged for other low-resource languages; through fine-tuning, the \n", "pre-trained checkpoints can be adapted for specific datasets and languages \n", "to further improve upon these results. We'll show just how Whisper can be fine-tuned \n", "for low-resource languages in this Colab." ] }, { "cell_type": "markdown", "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72", "metadata": { "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72" }, "source": [ "
\n", "\"Trulli\"\n", "
Figure 1: Whisper model. The architecture \n", "follows the standard Transformer-based encoder-decoder model. A \n", "log-Mel spectrogram is input to the encoder. The last encoder \n", "hidden states are input to the decoder via cross-attention mechanisms. The \n", "decoder autoregressively predicts text tokens, jointly conditional on the \n", "encoder hidden states and previously predicted tokens. Figure source: \n", "OpenAI Whisper Blog.
\n", "
" ] }, { "cell_type": "markdown", "id": "21b6316e-8a55-4549-a154-66d3da2ab74a", "metadata": { "id": "21b6316e-8a55-4549-a154-66d3da2ab74a" }, "source": [ "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", "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 a low-resource language \n", "taken from the [Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n", "dataset. We'll show that with as little as 8 hours of fine-tuning data, we can achieve \n", "strong performance in this language." ] }, { "cell_type": "markdown", "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a", "metadata": { "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a" }, "source": [ "------------------------------------------------------------------------\n", "\n", "\\\\({}^1\\\\) The name Whisper follows from the acronym “WSPSR”, which stands for “Web-scale Supervised Pre-training for Speech Recognition”." ] }, { "cell_type": "markdown", "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0", "metadata": { "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0" }, "source": [ "## Load Dataset" ] }, { "cell_type": "markdown", "id": "674429c5-0ab4-4adf-975b-621bb69eca38", "metadata": { "id": "674429c5-0ab4-4adf-975b-621bb69eca38" }, "source": [ "Using 🤗 Datasets, downloading and preparing data is extremely simple. \n", "We can download and prepare the Common Voice splits in just one line of code. \n", "\n", "First, 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 download the data locally.\n", "\n", "Since Arabic is very low-resource, we'll combine the `train` and `validation` \n", "splits to give approximately 8 hours of training data. We'll use the 4 hours \n", "of `test` data as our held-out test set:" ] }, { "cell_type": "code", "execution_count": null, "id": "5de15d70", "metadata": {}, "outputs": [], "source": [ "model_name = \"openai/whisper-small\"" ] }, { "cell_type": "code", "execution_count": null, "id": "a2787582-554f-44ce-9f38-4180a5ed6b44", "metadata": { "id": "a2787582-554f-44ce-9f38-4180a5ed6b44" }, "outputs": [], "source": [ "from datasets import load_dataset, DatasetDict\n", "\n", "common_voice = DatasetDict()\n", "\n", "common_voice[\"train\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"train+validation\", use_auth_token=True)\n", "common_voice[\"test\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"test\", use_auth_token=True)\n", "\n", "print(common_voice)" ] }, { "cell_type": "markdown", "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f", "metadata": { "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f" }, "source": [ "Most ASR datasets only provide input audio samples (`audio`) and the \n", "corresponding transcribed text (`sentence`). Common Voice contains additional \n", "metadata information, such as `accent` and `locale`, which we can disregard for ASR.\n", "Keeping the notebook as general as possible, we only consider the input audio and\n", "transcribed text for fine-tuning, discarding the additional metadata information:" ] }, { "cell_type": "code", "execution_count": null, "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce", "metadata": { "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce" }, "outputs": [], "source": [ "common_voice = common_voice.remove_columns([\"accent\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"path\", \"segment\", \"up_votes\"])\n", "\n", "print(common_voice)" ] }, { "cell_type": "markdown", "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605", "metadata": { "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605" }, "source": [ "## Prepare Feature Extractor, Tokenizer and Data" ] }, { "cell_type": "markdown", "id": "601c3099-1026-439e-93e2-5635b3ba5a73", "metadata": { "id": "601c3099-1026-439e-93e2-5635b3ba5a73" }, "source": [ "The ASR pipeline can be de-composed into three stages: \n", "1) A feature extractor which pre-processes the raw audio-inputs\n", "2) The model which performs the sequence-to-sequence mapping \n", "3) A tokenizer which post-processes the model outputs to text format\n", "\n", "In 🤗 Transformers, the Whisper model has an associated feature extractor and tokenizer, \n", "called [WhisperFeatureExtractor](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperFeatureExtractor)\n", "and [WhisperTokenizer](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperTokenizer) \n", "respectively.\n", "\n", "We'll go through details for setting-up the feature extractor and tokenizer one-by-one!" ] }, { "cell_type": "markdown", "id": "560332eb-3558-41a1-b500-e83a9f695f84", "metadata": { "id": "560332eb-3558-41a1-b500-e83a9f695f84" }, "source": [ "### Load WhisperFeatureExtractor" ] }, { "cell_type": "markdown", "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365", "metadata": { "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365" }, "source": [ "The Whisper feature extractor performs two operations:\n", "1. Pads / truncates the audio inputs to 30s: any audio inputs shorter than 30s are padded to 30s with silence (zeros), and those longer that 30s are truncated to 30s\n", "2. Converts the audio inputs to _log-Mel spectrogram_ input features, a visual representation of the audio and the form of the input expected by the Whisper model" ] }, { "cell_type": "markdown", "id": "589d9ec1-d12b-4b64-93f7-04c63997da19", "metadata": { "id": "589d9ec1-d12b-4b64-93f7-04c63997da19" }, "source": [ "
\n", "\"Trulli\"\n", "
Figure 2: Conversion of sampled audio array to log-Mel spectrogram.\n", "Left: sampled 1-dimensional audio signal. Right: corresponding log-Mel spectrogram. Figure source:\n", "Google SpecAugment Blog.\n", "
" ] }, { "cell_type": "markdown", "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa", "metadata": { "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa" }, "source": [ "We'll load the feature extractor from the pre-trained checkpoint with the default values:" ] }, { "cell_type": "code", "execution_count": null, "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5", "metadata": { "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5" }, "outputs": [], "source": [ "from transformers import WhisperFeatureExtractor\n", "\n", "feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name)" ] }, { "cell_type": "markdown", "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb", "metadata": { "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb" }, "source": [ "### Load WhisperTokenizer" ] }, { "cell_type": "markdown", "id": "2bc82609-a9fb-447a-a2af-99597c864029", "metadata": { "id": "2bc82609-a9fb-447a-a2af-99597c864029" }, "source": [ "The Whisper model outputs a sequence of _token ids_. The tokenizer maps each of these token ids to their corresponding text string. For Arabic, we can load the pre-trained tokenizer and use it for fine-tuning without any further modifications. We simply have to \n", "specify the target language and the task. These arguments inform the \n", "tokenizer to prefix the language and task tokens to the start of encoded \n", "label sequences:" ] }, { "cell_type": "code", "execution_count": null, "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6", "metadata": { "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6", "outputId": "5c004b44-86e7-4e00-88be-39e0af5eed69" }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "90d056e20b3e4f14ae0199a1a4ab1bb0", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading: 0%| | 0.00/829 [00:00 1 will enable multiprocessing. If the `.map` method hangs with multiprocessing, set `num_proc=1` and process the dataset sequentially." ] }, { "cell_type": "code", "execution_count": null, "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b", "metadata": { "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b" }, "outputs": [], "source": [ "common_voice = common_voice.map(prepare_dataset, remove_columns=common_voice.column_names[\"train\"], num_proc=2)" ] }, { "cell_type": "markdown", "id": "54ce0fdb-7218-4a4d-b175-383980fec0df", "metadata": {}, "source": [ "Finally, we filter any training data with audio samples longer than 30s. These samples would otherwise be truncated by the Whisper feature-extractor which could affect the stability of training. We define a function that returns `True` for samples that are less than 30s, and `False` for those that are longer:" ] }, { "cell_type": "code", "execution_count": null, "id": "01cb25ef-4bb0-4325-9461-f59198acadf6", "metadata": {}, "outputs": [], "source": [ "max_input_length = 30.0\n", "\n", "def is_audio_in_length_range(length):\n", " return length < max_input_length" ] }, { "cell_type": "markdown", "id": "30e676a8-7ca8-4850-8c5d-5b2b00d13fba", "metadata": {}, "source": [ "We apply our filter function to all samples of our training dataset through 🤗 Datasets' `.filter` method:" ] }, { "cell_type": "code", "execution_count": null, "id": "333f7f6e-6053-4d3b-8924-c733c79b82ac", "metadata": {}, "outputs": [], "source": [ "common_voice[\"train\"] = common_voice[\"train\"].filter(\n", " is_audio_in_length_range,\n", " input_columns=[\"input_length\"],\n", ")" ] }, { "cell_type": "markdown", "id": "263a5a58-0239-4a25-b0df-c625fc9c5810", "metadata": { "id": "263a5a58-0239-4a25-b0df-c625fc9c5810" }, "source": [ "## Training and Evaluation" ] }, { "cell_type": "markdown", "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7", "metadata": { "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7" }, "source": [ "Now that we've prepared our data, we're ready to dive into the training pipeline. \n", "The [🤗 Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer)\n", "will do much of the heavy lifting for us. All we have to do is:\n", "\n", "- Define a data collator: the data collator takes our pre-processed data and prepares PyTorch tensors ready for the model.\n", "\n", "- Evaluation metrics: during evaluation, we want to evaluate the model using the [word error rate (WER)](https://huggingface.co/metrics/wer) metric. We need to define a `compute_metrics` function that handles this computation.\n", "\n", "- Load a pre-trained checkpoint: we need to load a pre-trained checkpoint and configure it correctly for training.\n", "\n", "- Define the training configuration: this will be used by the 🤗 Trainer to define the training schedule.\n", "\n", "Once we've fine-tuned the model, we will evaluate it on the test data to verify that we have correctly trained it \n", "to transcribe speech in Arabic." ] }, { "cell_type": "markdown", "id": "8d230e6d-624c-400a-bbf5-fa660881df25", "metadata": { "id": "8d230e6d-624c-400a-bbf5-fa660881df25" }, "source": [ "### Define a Data Collator" ] }, { "cell_type": "markdown", "id": "04def221-0637-4a69-b242-d3f0c1d0ee78", "metadata": { "id": "04def221-0637-4a69-b242-d3f0c1d0ee78" }, "source": [ "The data collator for a sequence-to-sequence speech model is unique in the sense that it \n", "treats the `input_features` and `labels` independently: the `input_features` must be \n", "handled by the feature extractor and the `labels` by the tokenizer.\n", "\n", "The `input_features` are already padded to 30s and converted to a log-Mel spectrogram \n", "of fixed dimension by action of the feature extractor, so all we have to do is convert the `input_features`\n", "to batched PyTorch tensors. We do this using the feature extractor's `.pad` method with `return_tensors=pt`.\n", "\n", "The `labels` on the other hand are un-padded. We first pad the sequences\n", "to the maximum length in the batch using the tokenizer's `.pad` method. The padding tokens \n", "are then replaced by `-100` so that these tokens are **not** taken into account when \n", "computing the loss. We then cut the BOS token from the start of the label sequence as we \n", "append it later during training.\n", "\n", "We can leverage the `WhisperProcessor` we defined earlier to perform both the \n", "feature extractor and the tokenizer operations:" ] }, { "cell_type": "code", "execution_count": null, "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5", "metadata": { "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5" }, "outputs": [], "source": [ "import torch\n", "\n", "from dataclasses import dataclass\n", "from typing import Any, Dict, List, Union\n", "\n", "@dataclass\n", "class DataCollatorSpeechSeq2SeqWithPadding:\n", " processor: Any\n", "\n", " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> 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": { "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86" }, "source": [ "Let's initialise the data collator we've just defined:" ] }, { "cell_type": "code", "execution_count": null, "id": "fc834702-c0d3-4a96-b101-7b87be32bf42", "metadata": { "id": "fc834702-c0d3-4a96-b101-7b87be32bf42" }, "outputs": [], "source": [ "data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)" ] }, { "cell_type": "markdown", "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698", "metadata": { "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698" }, "source": [ "### Evaluation Metrics" ] }, { "cell_type": "markdown", "id": "66fee1a7-a44c-461e-b047-c3917221572e", "metadata": { "id": "66fee1a7-a44c-461e-b047-c3917221572e" }, "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": null, "id": "b22b4011-f31f-4b57-b684-c52332f92890", "metadata": { "id": "b22b4011-f31f-4b57-b684-c52332f92890" }, "outputs": [], "source": [ "import evaluate\n", "\n", "metric = evaluate.load(\"wer\")" ] }, { "cell_type": "markdown", "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508", "metadata": { "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508" }, "source": [ "We then simply have to define a function that takes our model \n", "predictions and returns the WER metric. This function, called\n", "`compute_metrics`, first replaces `-100` with the `pad_token_id`\n", "in the `label_ids` (undoing the step we applied in the \n", "data collator to ignore padded tokens correctly in the loss).\n", "It then decodes the predicted and label ids to strings. Finally,\n", "it computes the WER between the predictions and reference labels. \n", "Here, we have the option of evaluating with the 'normalised' transcriptions \n", "and predictions. We recommend you set this to `True` to benefit from the WER \n", "improvement obtained by normalising the transcriptions." ] }, { "cell_type": "code", "execution_count": null, "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52", "metadata": { "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52" }, "outputs": [], "source": [ "# evaluate with the 'normalised' WER\n", "do_normalize_eval = True\n", "\n", "def compute_metrics(pred):\n", " pred_ids = pred.predictions\n", " label_ids = pred.label_ids\n", "\n", " # replace -100 with the pad_token_id\n", " label_ids[label_ids == -100] = processor.tokenizer.pad_token_id\n", "\n", " # we do not want to group tokens when computing the metrics\n", " pred_str = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=True)\n", " label_str = processor.tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n", "\n", " if do_normalize_eval:\n", " pred_str = [normalizer(pred) for pred in pred_str]\n", " label_str = [normalizer(label) for label in label_str]\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": { "id": "daf2a825-6d9f-4a23-b145-c37c0039075b" }, "source": [ "### Load a Pre-Trained Checkpoint" ] }, { "cell_type": "markdown", "id": "437a97fa-4864-476b-8abc-f28b8166cfa5", "metadata": { "id": "437a97fa-4864-476b-8abc-f28b8166cfa5" }, "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": null, "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f", "metadata": { "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f" }, "outputs": [], "source": [ "from transformers import WhisperForConditionalGeneration\n", "\n", "model = WhisperForConditionalGeneration.from_pretrained(model_name)" ] }, { "cell_type": "markdown", "id": "a15ead5f-2277-4a39-937b-585c2497b2df", "metadata": { "id": "a15ead5f-2277-4a39-937b-585c2497b2df" }, "source": [ "Override generation arguments - no tokens are forced as decoder outputs (see [`forced_decoder_ids`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.forced_decoder_ids)), no tokens are suppressed during generation (see [`suppress_tokens`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.suppress_tokens)). Set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible:" ] }, { "cell_type": "code", "execution_count": null, "id": "62038ba3-88ed-4fce-84db-338f50dcd04f", "metadata": { "id": "62038ba3-88ed-4fce-84db-338f50dcd04f" }, "outputs": [], "source": [ "model.config.forced_decoder_ids = None\n", "model.config.suppress_tokens = []\n", "model.config.use_cache = False" ] }, { "cell_type": "markdown", "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06", "metadata": { "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06" }, "source": [ "### Define the Training Configuration" ] }, { "cell_type": "markdown", "id": "c21af1e9-0188-4134-ac82-defc7bdcc436", "metadata": { "id": "c21af1e9-0188-4134-ac82-defc7bdcc436" }, "source": [ "In the final step, we define all the parameters related to training. For more detail on the training arguments, refer to the Seq2SeqTrainingArguments [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments)." ] }, { "cell_type": "code", "execution_count": null, "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a", "metadata": { "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a" }, "outputs": [], "source": [ "from transformers import Seq2SeqTrainingArguments\n", "\n", "training_args = Seq2SeqTrainingArguments(\n", " output_dir=\"./\",\n", " per_device_train_batch_size=64,\n", " gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size\n", " learning_rate=1e-5,\n", " warmup_steps=500,\n", " max_steps=5000,\n", " gradient_checkpointing=True,\n", " fp16=True,\n", " evaluation_strategy=\"steps\",\n", " per_device_eval_batch_size=8,\n", " predict_with_generate=True,\n", " generation_max_length=225,\n", " save_steps=1000,\n", " eval_steps=1000,\n", " logging_steps=25,\n", " report_to=[\"tensorboard\"],\n", " load_best_model_at_end=True,\n", " metric_for_best_model=\"wer\",\n", " greater_is_better=False,\n", " push_to_hub=True,\n", ")" ] }, { "cell_type": "markdown", "id": "b3a944d8-3112-4552-82a0-be25988b3857", "metadata": { "id": "b3a944d8-3112-4552-82a0-be25988b3857" }, "source": [ "**Note**: if one does not want to upload the model checkpoints to the Hub, \n", "set `push_to_hub=False`." ] }, { "cell_type": "markdown", "id": "bac29114-d226-4f54-97cf-8718c9f94e1e", "metadata": { "id": "bac29114-d226-4f54-97cf-8718c9f94e1e" }, "source": [ "We can forward the training arguments to the 🤗 Trainer along with our model,\n", "dataset, data collator and `compute_metrics` function:" ] }, { "cell_type": "code", "execution_count": null, "id": "d546d7fe-0543-479a-b708-2ebabec19493", "metadata": { "id": "d546d7fe-0543-479a-b708-2ebabec19493" }, "outputs": [], "source": [ "from transformers import Seq2SeqTrainer\n", "\n", "trainer = Seq2SeqTrainer(\n", " args=training_args,\n", " model=model,\n", " train_dataset=common_voice[\"train\"],\n", " eval_dataset=common_voice[\"test\"],\n", " data_collator=data_collator,\n", " compute_metrics=compute_metrics,\n", " tokenizer=processor.feature_extractor,\n", ")" ] }, { "cell_type": "markdown", "id": "uOrRhDGtN5S4", "metadata": { "id": "uOrRhDGtN5S4" }, "source": [ "We'll save the processor object once before starting training. Since the processor is not trainable, it won't change over the course of training:" ] }, { "cell_type": "code", "execution_count": null, "id": "-2zQwMfEOBJq", "metadata": { "id": "-2zQwMfEOBJq" }, "outputs": [], "source": [ "processor.save_pretrained(training_args.output_dir)" ] }, { "cell_type": "markdown", "id": "7f404cf9-4345-468c-8196-4bd101d9bd51", "metadata": { "id": "7f404cf9-4345-468c-8196-4bd101d9bd51" }, "source": [ "### Training" ] }, { "cell_type": "markdown", "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112", "metadata": { "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112" }, "source": [ "Training will take approximately 5-10 hours depending on your GPU. The peak GPU memory for the given training configuration is approximately 36GB. \n", "Depending on your GPU, it is possible that you will encounter a CUDA `\"out-of-memory\"` error when you launch training. \n", "In this case, you can reduce the `per_device_train_batch_size` incrementally by factors of 2 \n", "and employ [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.gradient_accumulation_steps)\n", "to compensate.\n", "\n", "To launch training, simply execute:" ] }, { "cell_type": "code", "execution_count": null, "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de", "metadata": { "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de" }, "outputs": [], "source": [ "trainer.train()" ] }, { "cell_type": "markdown", "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3", "metadata": { "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3" }, "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": null, "id": "c704f91e-241b-48c9-b8e0-f0da396a9663", "metadata": { "id": "c704f91e-241b-48c9-b8e0-f0da396a9663" }, "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\": \"ar\",\n", " \"model_name\": \"Whisper Small ar - Zaid Alyafeai\", # a 'pretty' name for your model\n", " \"finetuned_from\": model_name,\n", " \"tasks\": \"automatic-speech-recognition\",\n", " \"tags\": \"whisper-event\",\n", "}" ] }, { "cell_type": "markdown", "id": "090d676a-f944-4297-a938-a40eda0b2b68", "metadata": { "id": "090d676a-f944-4297-a938-a40eda0b2b68" }, "source": [ "The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command and save the preprocessor object we created:" ] }, { "cell_type": "code", "execution_count": null, "id": "d7030622-caf7-4039-939b-6195cdaa2585", "metadata": { "id": "d7030622-caf7-4039-939b-6195cdaa2585" }, "outputs": [], "source": [ "trainer.push_to_hub(**kwargs)" ] }, { "cell_type": "markdown", "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba", "metadata": { "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba" }, "source": [ "## Closing Remarks" ] }, { "cell_type": "markdown", "id": "7f737783-2870-4e35-aa11-86a42d7d997a", "metadata": { "id": "7f737783-2870-4e35-aa11-86a42d7d997a" }, "source": [ "In this blog, we covered a step-by-step guide on fine-tuning Whisper for multilingual ASR \n", "using 🤗 Datasets, Transformers and the Hugging Face Hub. For more details on the Whisper model, the Common Voice dataset and the theory behind fine-tuning, refere to the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). If you're interested in fine-tuning other \n", "Transformers models, both for English and multilingual ASR, be sure to check out the \n", "examples scripts at [examples/pytorch/speech-recognition](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition)." ] } ], "metadata": { "colab": { "include_colab_link": true, "provenance": [] }, "kernelspec": { "display_name": "Python 3", "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" }, "vscode": { "interpreter": { "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac" } } }, "nbformat": 4, "nbformat_minor": 5 }