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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"# Fine-Tune Whisper With 🤗 Transformers and Streaming Mode"
|
9 |
+
]
|
10 |
+
},
|
11 |
+
{
|
12 |
+
"cell_type": "markdown",
|
13 |
+
"id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a",
|
14 |
+
"metadata": {},
|
15 |
+
"source": [
|
16 |
+
"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."
|
17 |
+
]
|
18 |
+
},
|
19 |
+
{
|
20 |
+
"cell_type": "markdown",
|
21 |
+
"id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e",
|
22 |
+
"metadata": {},
|
23 |
+
"source": [
|
24 |
+
"## Introduction"
|
25 |
+
]
|
26 |
+
},
|
27 |
+
{
|
28 |
+
"cell_type": "markdown",
|
29 |
+
"id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0",
|
30 |
+
"metadata": {},
|
31 |
+
"source": [
|
32 |
+
"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",
|
33 |
+
"\n",
|
34 |
+
"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",
|
35 |
+
"\n",
|
36 |
+
"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",
|
37 |
+
"\n",
|
38 |
+
"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",
|
39 |
+
"\n",
|
40 |
+
"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."
|
41 |
+
]
|
42 |
+
},
|
43 |
+
{
|
44 |
+
"cell_type": "markdown",
|
45 |
+
"id": "1c87f76e-47be-4a5d-bc52-7b1c2e9d4f5a",
|
46 |
+
"metadata": {},
|
47 |
+
"source": [
|
48 |
+
"<figure>\n",
|
49 |
+
"<img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/streaming.gif\" alt=\"Trulli\" style=\"width:100%\">\n",
|
50 |
+
"<figcaption align = \"center\"><b>Figure 1:</b> Streaming mode. The dataset is divided into smaller subsets, with subsets loaded progressively as we iterate over the dataset. </figcaption>\n",
|
51 |
+
"</figure>"
|
52 |
+
]
|
53 |
+
},
|
54 |
+
{
|
55 |
+
"cell_type": "markdown",
|
56 |
+
"id": "21b6316e-8a55-4549-a154-66d3da2ab74a",
|
57 |
+
"metadata": {},
|
58 |
+
"source": [
|
59 |
+
"This notebook provides a guide to fine-tuning on the task of _speech recognition_, which involves learning a\n",
|
60 |
+
"mapping from speech to text. Speech recognition is divided into two categories: English-only or multilingual (all other languages). \n",
|
61 |
+
"This notebook applies to both categories, with pointers for changing between languages and datasets.\n",
|
62 |
+
"\n",
|
63 |
+
"As for our model, we'll fine-tune the Whisper model released in [September 2022](https://openai.com/blog/whisper/) by the authors \n",
|
64 |
+
"Alec Radford et al. from OpenAI. Whisper is an encoder-decoder model pre-trained on 680k hours of labelled audio-transcription data. \n",
|
65 |
+
"It achieves strong performance on many speech recognition and speech translation datasets without fine-tuning. With fine-tuning, \n",
|
66 |
+
"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",
|
67 |
+
"reader is advised to read the blog post [Fine-Tune Whisper with 🤗 Transformers](https://huggingface.co/blog/fine-tune-whisper#introduction).\n",
|
68 |
+
"\n",
|
69 |
+
"The Whisper checkpoints come in five configurations of varying model sizes.\n",
|
70 |
+
"The smallest four are trained on either English-only or multilingual data.\n",
|
71 |
+
"The largest checkpoint is multilingual only. All nine of the pre-trained checkpoints \n",
|
72 |
+
"are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The \n",
|
73 |
+
"checkpoints are summarised in the following table with links to the models on the Hub:\n",
|
74 |
+
"\n",
|
75 |
+
"| Size | Layers | Width | Heads | Parameters | English-only | Multilingual |\n",
|
76 |
+
"|--------|--------|-------|-------|------------|------------------------------------------------------|---------------------------------------------------|\n",
|
77 |
+
"| tiny | 4 | 384 | 6 | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny.) |\n",
|
78 |
+
"| base | 6 | 512 | 8 | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |\n",
|
79 |
+
"| small | 12 | 768 | 12 | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |\n",
|
80 |
+
"| medium | 24 | 1024 | 16 | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |\n",
|
81 |
+
"| large | 32 | 1280 | 20 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |\n",
|
82 |
+
"\n",
|
83 |
+
"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",
|
84 |
+
"\n",
|
85 |
+
"For demonstration purposes, we'll fine-tune the multilingual version of the \n",
|
86 |
+
"[`\"small\"`](https://huggingface.co/openai/whisper-small) checkpoint with 244M params (~= 1GB). \n",
|
87 |
+
"As for our data, we'll train and evaluate our system on 400 hours of multilingual speech recognition data\n",
|
88 |
+
"taken from the [Common Voice 11](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n",
|
89 |
+
"dataset. We'll show how we can train a model on 400 hours of training data using the default disk space \n",
|
90 |
+
"that comes with a standard GPU device or Google Colab."
|
91 |
+
]
|
92 |
+
},
|
93 |
+
{
|
94 |
+
"cell_type": "markdown",
|
95 |
+
"id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0",
|
96 |
+
"metadata": {},
|
97 |
+
"source": [
|
98 |
+
"## Load Dataset with Streaming"
|
99 |
+
]
|
100 |
+
},
|
101 |
+
{
|
102 |
+
"cell_type": "markdown",
|
103 |
+
"id": "b17a4763-4381-4157-ae38-b04a8b5f1c43",
|
104 |
+
"metadata": {},
|
105 |
+
"source": [
|
106 |
+
"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!"
|
107 |
+
]
|
108 |
+
},
|
109 |
+
{
|
110 |
+
"cell_type": "code",
|
111 |
+
"execution_count": null,
|
112 |
+
"id": "065a8cf7-e54f-4ac3-900e-609c80714fca",
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [],
|
115 |
+
"source": [
|
116 |
+
"from datasets import interleave_datasets, load_dataset\n",
|
117 |
+
"\n",
|
118 |
+
"def load_streaming_dataset(dataset_name, dataset_config_name, split, **kwargs):\n",
|
119 |
+
" if \"+\" in split:\n",
|
120 |
+
" # load multiple splits separated by the `+` symbol *with* streaming mode\n",
|
121 |
+
" dataset_splits = [load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=True, **kwargs) for split_name in split.split(\"+\")]\n",
|
122 |
+
" # interleave multiple splits to form one dataset\n",
|
123 |
+
" interleaved_dataset = interleave_datasets(dataset_splits)\n",
|
124 |
+
" return interleaved_dataset\n",
|
125 |
+
" else:\n",
|
126 |
+
" # load a single split *with* streaming mode\n",
|
127 |
+
" dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=True, **kwargs)\n",
|
128 |
+
" return dataset"
|
129 |
+
]
|
130 |
+
},
|
131 |
+
{
|
132 |
+
"cell_type": "markdown",
|
133 |
+
"id": "674429c5-0ab4-4adf-975b-621bb69eca38",
|
134 |
+
"metadata": {},
|
135 |
+
"source": [
|
136 |
+
"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",
|
137 |
+
"\n",
|
138 |
+
"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",
|
139 |
+
"\n",
|
140 |
+
"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."
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": null,
|
146 |
+
"id": "a2787582-554f-44ce-9f38-4180a5ed6b44",
|
147 |
+
"metadata": {},
|
148 |
+
"outputs": [],
|
149 |
+
"source": [
|
150 |
+
"from datasets import IterableDatasetDict\n",
|
151 |
+
"\n",
|
152 |
+
"raw_datasets = IterableDatasetDict()\n",
|
153 |
+
"\n",
|
154 |
+
"raw_datasets[\"train\"] = load_streaming_dataset(\"mozilla-foundation/common_voice_11_0\", \"es\", split=\"train\", use_auth_token=True) # set split=\"train+validation\" for low-resource\n",
|
155 |
+
"raw_datasets[\"test\"] = load_streaming_dataset(\"mozilla-foundation/common_voice_11_0\", \"es\", split=\"test\", use_auth_token=True)"
|
156 |
+
]
|
157 |
+
},
|
158 |
+
{
|
159 |
+
"cell_type": "markdown",
|
160 |
+
"id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605",
|
161 |
+
"metadata": {},
|
162 |
+
"source": [
|
163 |
+
"## Prepare Processor and Pre-Process Data"
|
164 |
+
]
|
165 |
+
},
|
166 |
+
{
|
167 |
+
"cell_type": "markdown",
|
168 |
+
"id": "601c3099-1026-439e-93e2-5635b3ba5a73",
|
169 |
+
"metadata": {},
|
170 |
+
"source": [
|
171 |
+
"The ASR pipeline can be de-composed into three stages: \n",
|
172 |
+
"1) A feature extractor which pre-processes the raw audio-inputs\n",
|
173 |
+
"2) The model which performs the sequence-to-sequence mapping \n",
|
174 |
+
"3) A tokenizer which post-processes the model outputs to text format\n",
|
175 |
+
"\n",
|
176 |
+
"In 🤗 Transformers, the Whisper model has an associated feature extractor and tokenizer, \n",
|
177 |
+
"called [WhisperFeatureExtractor](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperFeatureExtractor)\n",
|
178 |
+
"and [WhisperTokenizer](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperTokenizer) \n",
|
179 |
+
"respectively. To make our lives simple, these two objects are wrapped under a single class, called the [WhisperProcessor](https://huggingface.co/docs/transformers/model_doc/whisper#transformers.WhisperProcessor). We can call the WhisperProcessor to perform \n",
|
180 |
+
"both the audio pre-processing and the text token post-processing. In doing so, we only need to keep track of two objects during training: \n",
|
181 |
+
"the `processor` and the `model`.\n",
|
182 |
+
"\n",
|
183 |
+
"If using a multilingual checkpoint, you should set the `\"language\"` to your target text language. You should also set the task to `\"transcribe\"` for speech recogntition and `\"translate\"` for speech translation. These arguments modify the behaviour of the tokenizer - they should be set correctly to ensure the target labels are encoded properly. These arguments should be omitted for English-only fine-tuning."
|
184 |
+
]
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"cell_type": "code",
|
188 |
+
"execution_count": null,
|
189 |
+
"id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6",
|
190 |
+
"metadata": {},
|
191 |
+
"outputs": [],
|
192 |
+
"source": [
|
193 |
+
"from transformers import WhisperProcessor\n",
|
194 |
+
"\n",
|
195 |
+
"processor = WhisperProcessor.from_pretrained(\"openai/whisper-small\", language=\"Spanish\", task=\"transcribe\")"
|
196 |
+
]
|
197 |
+
},
|
198 |
+
{
|
199 |
+
"cell_type": "markdown",
|
200 |
+
"id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c",
|
201 |
+
"metadata": {},
|
202 |
+
"source": [
|
203 |
+
"### Pre-Process Data"
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"cell_type": "markdown",
|
208 |
+
"id": "bf10cd3e-924e-44fc-8790-46e413de7b3d",
|
209 |
+
"metadata": {},
|
210 |
+
"source": [
|
211 |
+
"Let's have a look at the dataset features. Pay particular attention to the `\"audio\"` column - this details the sampling rate of our audio inputs:"
|
212 |
+
]
|
213 |
+
},
|
214 |
+
{
|
215 |
+
"cell_type": "code",
|
216 |
+
"execution_count": null,
|
217 |
+
"id": "ab5a13b4-9bd4-4aa0-aef2-b3de9b762988",
|
218 |
+
"metadata": {},
|
219 |
+
"outputs": [],
|
220 |
+
"source": [
|
221 |
+
"raw_datasets[\"train\"].features"
|
222 |
+
]
|
223 |
+
},
|
224 |
+
{
|
225 |
+
"cell_type": "markdown",
|
226 |
+
"id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd",
|
227 |
+
"metadata": {},
|
228 |
+
"source": [
|
229 |
+
"Since our input audio is sampled at 48kHz, we need to _downsample_ it to\n",
|
230 |
+
"16kHz prior to passing it to the Whisper feature extractor, 16kHz being the sampling rate expected by the Whisper model. \n",
|
231 |
+
"\n",
|
232 |
+
"We'll set the audio inputs to the correct sampling rate using dataset's \n",
|
233 |
+
"[`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column)\n",
|
234 |
+
"method. This operation does not change the audio in-place, \n",
|
235 |
+
"but rather signals to `datasets` to resample audio samples _on the fly_ the \n",
|
236 |
+
"first time that they are loaded:"
|
237 |
+
]
|
238 |
+
},
|
239 |
+
{
|
240 |
+
"cell_type": "code",
|
241 |
+
"execution_count": null,
|
242 |
+
"id": "3ab6a724-3d1e-478b-a9e9-d2f85feb6c39",
|
243 |
+
"metadata": {},
|
244 |
+
"outputs": [],
|
245 |
+
"source": [
|
246 |
+
"from datasets import Audio\n",
|
247 |
+
"\n",
|
248 |
+
"raw_datasets = raw_datasets.cast_column(\"audio\", Audio(sampling_rate=16000))"
|
249 |
+
]
|
250 |
+
},
|
251 |
+
{
|
252 |
+
"cell_type": "markdown",
|
253 |
+
"id": "161322c2-94f3-4d26-9e1d-d9d5202ca3cf",
|
254 |
+
"metadata": {},
|
255 |
+
"source": [
|
256 |
+
"We'll define our pre-processing strategy. We advise that you **do not** lower-case the transcriptions or remove punctuation unless mixing different datasets. This will enable you to fine-tune Whisper models that can predict punctuation and casing. Later, you will see how we can evaluate the predictions without punctuation or casing, so that the models benefit from the WER improvement obtained by normalising the transcriptions while still predicting fully formatted transcriptions."
|
257 |
+
]
|
258 |
+
},
|
259 |
+
{
|
260 |
+
"cell_type": "code",
|
261 |
+
"execution_count": null,
|
262 |
+
"id": "d041650e-1c48-4439-87b3-5b6f4a514107",
|
263 |
+
"metadata": {},
|
264 |
+
"outputs": [],
|
265 |
+
"source": [
|
266 |
+
"from transformers.models.whisper.english_normalizer import BasicTextNormalizer\n",
|
267 |
+
"\n",
|
268 |
+
"do_lower_case = False\n",
|
269 |
+
"do_remove_punctuation = False\n",
|
270 |
+
"\n",
|
271 |
+
"normalizer = BasicTextNormalizer()"
|
272 |
+
]
|
273 |
+
},
|
274 |
+
{
|
275 |
+
"cell_type": "markdown",
|
276 |
+
"id": "bfaa935b-a11d-497c-88c1-0c4d1bb3247b",
|
277 |
+
"metadata": {},
|
278 |
+
"source": [
|
279 |
+
"Now we can write a function to prepare our data ready for the model:\n",
|
280 |
+
"1. We load and resample the audio data by calling `batch[\"audio\"]`. As explained above, 🤗 Datasets performs any necessary resampling operations on the fly.\n",
|
281 |
+
"2. We use the feature extractor to compute the log-Mel spectrogram input features from our 1-dimensional audio array.\n",
|
282 |
+
"3. We perform any optional pre-processing (lower-case or remove punctuation).\n",
|
283 |
+
"4. We encode the transcriptions to label ids through the use of the tokenizer."
|
284 |
+
]
|
285 |
+
},
|
286 |
+
{
|
287 |
+
"cell_type": "code",
|
288 |
+
"execution_count": null,
|
289 |
+
"id": "c085911c-a10a-41ef-8874-306e0503e9bb",
|
290 |
+
"metadata": {},
|
291 |
+
"outputs": [],
|
292 |
+
"source": [
|
293 |
+
"def prepare_dataset(batch):\n",
|
294 |
+
" # load and (possibly) resample audio data to 16kHz\n",
|
295 |
+
" audio = batch[\"audio\"]\n",
|
296 |
+
"\n",
|
297 |
+
" # compute log-Mel input features from input audio array \n",
|
298 |
+
" batch[\"input_features\"] = processor.feature_extractor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_features[0]\n",
|
299 |
+
" # compute input length of audio sample in seconds\n",
|
300 |
+
" batch[\"input_length\"] = len(audio[\"array\"]) / audio[\"sampling_rate\"]\n",
|
301 |
+
" \n",
|
302 |
+
" # optional pre-processing steps\n",
|
303 |
+
" transcription = batch[\"sentence\"]\n",
|
304 |
+
" if do_lower_case:\n",
|
305 |
+
" transcription = transcription.lower()\n",
|
306 |
+
" if do_remove_punctuation:\n",
|
307 |
+
" transcription = normalizer(transcription).strip()\n",
|
308 |
+
" \n",
|
309 |
+
" # encode target text to label ids\n",
|
310 |
+
" batch[\"labels\"] = processor.tokenizer(transcription).input_ids\n",
|
311 |
+
" return batch"
|
312 |
+
]
|
313 |
+
},
|
314 |
+
{
|
315 |
+
"cell_type": "markdown",
|
316 |
+
"id": "70b319fb-2439-4ef6-a70d-a47bf41c4a13",
|
317 |
+
"metadata": {},
|
318 |
+
"source": [
|
319 |
+
"We can apply the data preparation function to all of our training examples using 🤗 Datasets' `.map` method. We'll remove all of the columns from the raw training data, leaving just the `input_features` and `labels` defined in the `prepare_dataset` function:"
|
320 |
+
]
|
321 |
+
},
|
322 |
+
{
|
323 |
+
"cell_type": "code",
|
324 |
+
"execution_count": null,
|
325 |
+
"id": "a37a7cdb-9013-427f-8de9-6a8d0e9dc684",
|
326 |
+
"metadata": {},
|
327 |
+
"outputs": [],
|
328 |
+
"source": [
|
329 |
+
"vectorized_datasets = raw_datasets.map(prepare_dataset, remove_columns=list(next(iter(raw_datasets.values())).features)).with_format(\"torch\")"
|
330 |
+
]
|
331 |
+
},
|
332 |
+
{
|
333 |
+
"cell_type": "markdown",
|
334 |
+
"id": "3d59b37e-4950-47ec-9e3e-2cf2ec7fc750",
|
335 |
+
"metadata": {},
|
336 |
+
"source": [
|
337 |
+
"We can now define how we shuffle the data in the train split. The size of the subset we load is set by the variable `buffer_size`. You can increase or decrease this depending on your memory constraints. In this example, the `buffer_size` is set to 500, meaning 500 samples are loaded before shuffling across the subset. The larger we set this value, the closer to True offline shuffling. The `seed` is set for reproducibility:"
|
338 |
+
]
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"cell_type": "code",
|
342 |
+
"execution_count": null,
|
343 |
+
"id": "1b145699-acfc-4b1d-93a2-a2ad3d62674c",
|
344 |
+
"metadata": {},
|
345 |
+
"outputs": [],
|
346 |
+
"source": [
|
347 |
+
"vectorized_datasets[\"train\"] = vectorized_datasets[\"train\"].shuffle(\n",
|
348 |
+
" buffer_size=500,\n",
|
349 |
+
" seed=0,\n",
|
350 |
+
")"
|
351 |
+
]
|
352 |
+
},
|
353 |
+
{
|
354 |
+
"cell_type": "markdown",
|
355 |
+
"id": "666b9ef0-7909-4e1e-a419-87604d233e29",
|
356 |
+
"metadata": {},
|
357 |
+
"source": [
|
358 |
+
"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:"
|
359 |
+
]
|
360 |
+
},
|
361 |
+
{
|
362 |
+
"cell_type": "code",
|
363 |
+
"execution_count": null,
|
364 |
+
"id": "01cb25ef-4bb0-4325-9461-f59198acadf6",
|
365 |
+
"metadata": {},
|
366 |
+
"outputs": [],
|
367 |
+
"source": [
|
368 |
+
"max_input_length = 30.0\n",
|
369 |
+
"\n",
|
370 |
+
"def is_audio_in_length_range(length):\n",
|
371 |
+
" return length < max_input_length"
|
372 |
+
]
|
373 |
+
},
|
374 |
+
{
|
375 |
+
"cell_type": "markdown",
|
376 |
+
"id": "28e37ac3-b1c5-465b-8586-7cfd8d76b0f1",
|
377 |
+
"metadata": {},
|
378 |
+
"source": [
|
379 |
+
"We apply our filter function to all samples of our training dataset through 🤗 Datasets' `.filter` method:"
|
380 |
+
]
|
381 |
+
},
|
382 |
+
{
|
383 |
+
"cell_type": "code",
|
384 |
+
"execution_count": null,
|
385 |
+
"id": "333f7f6e-6053-4d3b-8924-c733c79b82ac",
|
386 |
+
"metadata": {},
|
387 |
+
"outputs": [],
|
388 |
+
"source": [
|
389 |
+
"vectorized_datasets[\"train\"] = vectorized_datasets[\"train\"].filter(\n",
|
390 |
+
" is_audio_in_length_range,\n",
|
391 |
+
" input_columns=[\"input_length\"],\n",
|
392 |
+
")"
|
393 |
+
]
|
394 |
+
},
|
395 |
+
{
|
396 |
+
"cell_type": "markdown",
|
397 |
+
"id": "263a5a58-0239-4a25-b0df-c625fc9c5810",
|
398 |
+
"metadata": {},
|
399 |
+
"source": [
|
400 |
+
"## Training and Evaluation"
|
401 |
+
]
|
402 |
+
},
|
403 |
+
{
|
404 |
+
"cell_type": "markdown",
|
405 |
+
"id": "a693e768-c5a6-453f-89a1-b601dcf7daf7",
|
406 |
+
"metadata": {},
|
407 |
+
"source": [
|
408 |
+
"Now that we've prepared our data, we're ready to dive into the training pipeline. \n",
|
409 |
+
"The [🤗 Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer)\n",
|
410 |
+
"will do much of the heavy lifting for us. All we have to do is:\n",
|
411 |
+
"\n",
|
412 |
+
"- Define a data collator: the data collator takes our pre-processed data and prepares PyTorch tensors ready for the model.\n",
|
413 |
+
"\n",
|
414 |
+
"- 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",
|
415 |
+
"\n",
|
416 |
+
"- Load a pre-trained checkpoint: we need to load a pre-trained checkpoint and configure it correctly for training.\n",
|
417 |
+
"\n",
|
418 |
+
"- Define the training configuration: this will be used by the 🤗 Trainer to define the training schedule."
|
419 |
+
]
|
420 |
+
},
|
421 |
+
{
|
422 |
+
"cell_type": "markdown",
|
423 |
+
"id": "8d230e6d-624c-400a-bbf5-fa660881df25",
|
424 |
+
"metadata": {},
|
425 |
+
"source": [
|
426 |
+
"### Define a Data Collator"
|
427 |
+
]
|
428 |
+
},
|
429 |
+
{
|
430 |
+
"cell_type": "markdown",
|
431 |
+
"id": "04def221-0637-4a69-b242-d3f0c1d0ee78",
|
432 |
+
"metadata": {},
|
433 |
+
"source": [
|
434 |
+
"The data collator for a sequence-to-sequence speech model is unique in the sense that it \n",
|
435 |
+
"treats the `input_features` and `labels` independently: the `input_features` must be \n",
|
436 |
+
"handled by the feature extractor and the `labels` by the tokenizer.\n",
|
437 |
+
"\n",
|
438 |
+
"The `input_features` are already padded to 30s and converted to a log-Mel spectrogram \n",
|
439 |
+
"of fixed dimension by action of the feature extractor, so all we have to do is convert the `input_features`\n",
|
440 |
+
"to batched PyTorch tensors. We do this using the feature extractor's `.pad` method with `return_tensors=pt`.\n",
|
441 |
+
"\n",
|
442 |
+
"The `labels` on the other hand are un-padded. We first pad the sequences\n",
|
443 |
+
"to the maximum length in the batch using the tokenizer's `.pad` method. The padding tokens \n",
|
444 |
+
"are then replaced by `-100` so that these tokens are **not** taken into account when \n",
|
445 |
+
"computing the loss. We then cut the BOS token from the start of the label sequence as we \n",
|
446 |
+
"append it later during training.\n",
|
447 |
+
"\n",
|
448 |
+
"We can leverage the `WhisperProcessor` we defined earlier to perform both the \n",
|
449 |
+
"feature extractor and the tokenizer operations:"
|
450 |
+
]
|
451 |
+
},
|
452 |
+
{
|
453 |
+
"cell_type": "code",
|
454 |
+
"execution_count": null,
|
455 |
+
"id": "8326221e-ec13-4731-bb4e-51e5fc1486c5",
|
456 |
+
"metadata": {},
|
457 |
+
"outputs": [],
|
458 |
+
"source": [
|
459 |
+
"import torch\n",
|
460 |
+
"\n",
|
461 |
+
"from dataclasses import dataclass\n",
|
462 |
+
"from typing import Any, Dict, List, Union\n",
|
463 |
+
"\n",
|
464 |
+
"@dataclass\n",
|
465 |
+
"class DataCollatorSpeechSeq2SeqWithPadding:\n",
|
466 |
+
" processor: Any\n",
|
467 |
+
"\n",
|
468 |
+
" def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
|
469 |
+
" # split inputs and labels since they have to be of different lengths and need different padding methods\n",
|
470 |
+
" # first treat the audio inputs by simply returning torch tensors\n",
|
471 |
+
" input_features = [{\"input_features\": feature[\"input_features\"]} for feature in features]\n",
|
472 |
+
" batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
|
473 |
+
"\n",
|
474 |
+
" # get the tokenized label sequences\n",
|
475 |
+
" label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n",
|
476 |
+
" # pad the labels to max length\n",
|
477 |
+
" labels_batch = self.processor.tokenizer.pad(label_features, return_tensors=\"pt\")\n",
|
478 |
+
"\n",
|
479 |
+
" # replace padding with -100 to ignore loss correctly\n",
|
480 |
+
" labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
|
481 |
+
"\n",
|
482 |
+
" # if bos token is appended in previous tokenization step,\n",
|
483 |
+
" # cut bos token here as it's append later anyways\n",
|
484 |
+
" if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():\n",
|
485 |
+
" labels = labels[:, 1:]\n",
|
486 |
+
"\n",
|
487 |
+
" batch[\"labels\"] = labels\n",
|
488 |
+
"\n",
|
489 |
+
" return batch"
|
490 |
+
]
|
491 |
+
},
|
492 |
+
{
|
493 |
+
"cell_type": "markdown",
|
494 |
+
"id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86",
|
495 |
+
"metadata": {},
|
496 |
+
"source": [
|
497 |
+
"Let's initialise the data collator we've just defined:"
|
498 |
+
]
|
499 |
+
},
|
500 |
+
{
|
501 |
+
"cell_type": "code",
|
502 |
+
"execution_count": null,
|
503 |
+
"id": "fc834702-c0d3-4a96-b101-7b87be32bf42",
|
504 |
+
"metadata": {},
|
505 |
+
"outputs": [],
|
506 |
+
"source": [
|
507 |
+
"data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)"
|
508 |
+
]
|
509 |
+
},
|
510 |
+
{
|
511 |
+
"cell_type": "markdown",
|
512 |
+
"id": "d62bb2ab-750a-45e7-82e9-61d6f4805698",
|
513 |
+
"metadata": {},
|
514 |
+
"source": [
|
515 |
+
"### Evaluation Metrics"
|
516 |
+
]
|
517 |
+
},
|
518 |
+
{
|
519 |
+
"cell_type": "markdown",
|
520 |
+
"id": "66fee1a7-a44c-461e-b047-c3917221572e",
|
521 |
+
"metadata": {},
|
522 |
+
"source": [
|
523 |
+
"We'll use the word error rate (WER) metric, the 'de-facto' metric for assessing \n",
|
524 |
+
"ASR systems. For more information, refer to the WER [docs](https://huggingface.co/metrics/wer). We'll load the WER metric from 🤗 Evaluate:"
|
525 |
+
]
|
526 |
+
},
|
527 |
+
{
|
528 |
+
"cell_type": "code",
|
529 |
+
"execution_count": null,
|
530 |
+
"id": "b22b4011-f31f-4b57-b684-c52332f92890",
|
531 |
+
"metadata": {},
|
532 |
+
"outputs": [],
|
533 |
+
"source": [
|
534 |
+
"import evaluate\n",
|
535 |
+
"\n",
|
536 |
+
"metric = evaluate.load(\"wer\")"
|
537 |
+
]
|
538 |
+
},
|
539 |
+
{
|
540 |
+
"cell_type": "markdown",
|
541 |
+
"id": "509f96d7-3f11-4f37-add9-f74a0c44f3fc",
|
542 |
+
"metadata": {},
|
543 |
+
"source": [
|
544 |
+
"We then simply have to define a function that takes our model \n",
|
545 |
+
"predictions and returns the WER metric. This function, called\n",
|
546 |
+
"`compute_metrics`, first replaces `-100` with the `pad_token_id`\n",
|
547 |
+
"in the `label_ids` (undoing the step we applied in the \n",
|
548 |
+
"data collator to ignore padded tokens correctly in the loss).\n",
|
549 |
+
"It then decodes the predicted and label ids to strings. Finally,\n",
|
550 |
+
"it computes the WER between the predictions and reference labels. \n",
|
551 |
+
"Here, we have the option of evaluating with the 'normalised' transcriptions \n",
|
552 |
+
"and predictions. We recommend you set this to `True` to benefit from the WER \n",
|
553 |
+
"improvement obtained by normalising the transcriptions."
|
554 |
+
]
|
555 |
+
},
|
556 |
+
{
|
557 |
+
"cell_type": "code",
|
558 |
+
"execution_count": null,
|
559 |
+
"id": "a11d1bfc-9e28-460f-a287-72d8f7bc1acb",
|
560 |
+
"metadata": {},
|
561 |
+
"outputs": [],
|
562 |
+
"source": [
|
563 |
+
"# evaluate with the 'normalised' WER\n",
|
564 |
+
"do_normalize_eval = True\n",
|
565 |
+
"\n",
|
566 |
+
"def compute_metrics(pred):\n",
|
567 |
+
" pred_ids = pred.predictions\n",
|
568 |
+
" label_ids = pred.label_ids\n",
|
569 |
+
"\n",
|
570 |
+
" # replace -100 with the pad_token_id\n",
|
571 |
+
" label_ids[label_ids == -100] = processor.tokenizer.pad_token_id\n",
|
572 |
+
"\n",
|
573 |
+
" # we do not want to group tokens when computing the metrics\n",
|
574 |
+
" pred_str = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=True)\n",
|
575 |
+
" label_str = processor.tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n",
|
576 |
+
"\n",
|
577 |
+
" if do_normalize_eval:\n",
|
578 |
+
" pred_str = [normalizer(pred) for pred in pred_str]\n",
|
579 |
+
" label_str = [normalizer(label) for label in label_str]\n",
|
580 |
+
"\n",
|
581 |
+
" wer = 100 * metric.compute(predictions=pred_str, references=label_str)\n",
|
582 |
+
"\n",
|
583 |
+
" return {\"wer\": wer}"
|
584 |
+
]
|
585 |
+
},
|
586 |
+
{
|
587 |
+
"cell_type": "markdown",
|
588 |
+
"id": "daf2a825-6d9f-4a23-b145-c37c0039075b",
|
589 |
+
"metadata": {},
|
590 |
+
"source": [
|
591 |
+
"### Load a Pre-Trained Checkpoint"
|
592 |
+
]
|
593 |
+
},
|
594 |
+
{
|
595 |
+
"cell_type": "markdown",
|
596 |
+
"id": "437a97fa-4864-476b-8abc-f28b8166cfa5",
|
597 |
+
"metadata": {},
|
598 |
+
"source": [
|
599 |
+
"Now let's load the pre-trained Whisper `small` checkpoint. Again, this \n",
|
600 |
+
"is trivial through use of 🤗 Transformers!"
|
601 |
+
]
|
602 |
+
},
|
603 |
+
{
|
604 |
+
"cell_type": "code",
|
605 |
+
"execution_count": null,
|
606 |
+
"id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f",
|
607 |
+
"metadata": {},
|
608 |
+
"outputs": [],
|
609 |
+
"source": [
|
610 |
+
"from transformers import WhisperForConditionalGeneration\n",
|
611 |
+
"\n",
|
612 |
+
"model = WhisperForConditionalGeneration.from_pretrained(\"openai/whisper-small\")"
|
613 |
+
]
|
614 |
+
},
|
615 |
+
{
|
616 |
+
"cell_type": "markdown",
|
617 |
+
"id": "a15ead5f-2277-4a39-937b-585c2497b2df",
|
618 |
+
"metadata": {},
|
619 |
+
"source": [
|
620 |
+
"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:"
|
621 |
+
]
|
622 |
+
},
|
623 |
+
{
|
624 |
+
"cell_type": "code",
|
625 |
+
"execution_count": null,
|
626 |
+
"id": "62038ba3-88ed-4fce-84db-338f50dcd04f",
|
627 |
+
"metadata": {},
|
628 |
+
"outputs": [],
|
629 |
+
"source": [
|
630 |
+
"model.config.forced_decoder_ids = None\n",
|
631 |
+
"model.config.suppress_tokens = []\n",
|
632 |
+
"model.config.use_cache = False"
|
633 |
+
]
|
634 |
+
},
|
635 |
+
{
|
636 |
+
"cell_type": "markdown",
|
637 |
+
"id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06",
|
638 |
+
"metadata": {},
|
639 |
+
"source": [
|
640 |
+
"### Define the Training Configuration"
|
641 |
+
]
|
642 |
+
},
|
643 |
+
{
|
644 |
+
"cell_type": "markdown",
|
645 |
+
"id": "c21af1e9-0188-4134-ac82-defc7bdcc436",
|
646 |
+
"metadata": {},
|
647 |
+
"source": [
|
648 |
+
"In the final step, we define all the parameters related to training. Here, you can set the `max_steps` to train for longer. For more detail on the training arguments, refer to the Seq2SeqTrainingArguments [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments)."
|
649 |
+
]
|
650 |
+
},
|
651 |
+
{
|
652 |
+
"cell_type": "code",
|
653 |
+
"execution_count": null,
|
654 |
+
"id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a",
|
655 |
+
"metadata": {},
|
656 |
+
"outputs": [],
|
657 |
+
"source": [
|
658 |
+
"from transformers import Seq2SeqTrainingArguments\n",
|
659 |
+
"\n",
|
660 |
+
"training_args = Seq2SeqTrainingArguments(\n",
|
661 |
+
" output_dir=\"./\",\n",
|
662 |
+
" per_device_train_batch_size=64,\n",
|
663 |
+
" gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size\n",
|
664 |
+
" learning_rate=1e-5,\n",
|
665 |
+
" warmup_steps=500,\n",
|
666 |
+
" max_steps=5000,\n",
|
667 |
+
" gradient_checkpointing=True,\n",
|
668 |
+
" fp16=True,\n",
|
669 |
+
" evaluation_strategy=\"steps\",\n",
|
670 |
+
" per_device_eval_batch_size=8,\n",
|
671 |
+
" predict_with_generate=True,\n",
|
672 |
+
" generation_max_length=225,\n",
|
673 |
+
" save_steps=1000,\n",
|
674 |
+
" eval_steps=1000,\n",
|
675 |
+
" logging_steps=25,\n",
|
676 |
+
" report_to=[\"tensorboard\"],\n",
|
677 |
+
" load_best_model_at_end=True,\n",
|
678 |
+
" metric_for_best_model=\"wer\",\n",
|
679 |
+
" greater_is_better=False,\n",
|
680 |
+
" push_to_hub=True,\n",
|
681 |
+
")"
|
682 |
+
]
|
683 |
+
},
|
684 |
+
{
|
685 |
+
"cell_type": "markdown",
|
686 |
+
"id": "b3a944d8-3112-4552-82a0-be25988b3857",
|
687 |
+
"metadata": {},
|
688 |
+
"source": [
|
689 |
+
"**Note**: if one does not want to upload the model checkpoints to the Hub, \n",
|
690 |
+
"set `push_to_hub=False`."
|
691 |
+
]
|
692 |
+
},
|
693 |
+
{
|
694 |
+
"cell_type": "markdown",
|
695 |
+
"id": "393c883e-3e50-492c-bd58-f51dbf15ee56",
|
696 |
+
"metadata": {},
|
697 |
+
"source": [
|
698 |
+
"We then define a custom [Callback](https://huggingface.co/docs/transformers/main_classes/callback) that is called by the 🤗 Trainer on the end of each epoch. The Callback reinitialises and reshuffles the streaming dataset at the beginning of each new epoch - this gives different shuffling across our subsets for every epoch."
|
699 |
+
]
|
700 |
+
},
|
701 |
+
{
|
702 |
+
"cell_type": "code",
|
703 |
+
"execution_count": null,
|
704 |
+
"id": "3ac16b62-b3c0-4c68-8f3d-9ecf471534b2",
|
705 |
+
"metadata": {},
|
706 |
+
"outputs": [],
|
707 |
+
"source": [
|
708 |
+
"from transformers import TrainerCallback\n",
|
709 |
+
"from transformers.trainer_pt_utils import IterableDatasetShard\n",
|
710 |
+
"from torch.utils.data import IterableDataset\n",
|
711 |
+
"\n",
|
712 |
+
"# trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch\n",
|
713 |
+
"class ShuffleCallback(TrainerCallback):\n",
|
714 |
+
" def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):\n",
|
715 |
+
" if isinstance(train_dataloader.dataset, IterableDatasetShard):\n",
|
716 |
+
" pass # set_epoch() is handled by the Trainer\n",
|
717 |
+
" elif isinstance(train_dataloader.dataset, IterableDataset):\n",
|
718 |
+
" train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)"
|
719 |
+
]
|
720 |
+
},
|
721 |
+
{
|
722 |
+
"cell_type": "markdown",
|
723 |
+
"id": "bac29114-d226-4f54-97cf-8718c9f94e1e",
|
724 |
+
"metadata": {},
|
725 |
+
"source": [
|
726 |
+
"We can forward the training arguments to the 🤗 Trainer along with our model,\n",
|
727 |
+
"dataset, data collator, `compute_metrics` function and custom callback:"
|
728 |
+
]
|
729 |
+
},
|
730 |
+
{
|
731 |
+
"cell_type": "code",
|
732 |
+
"execution_count": null,
|
733 |
+
"id": "d546d7fe-0543-479a-b708-2ebabec19493",
|
734 |
+
"metadata": {},
|
735 |
+
"outputs": [],
|
736 |
+
"source": [
|
737 |
+
"from transformers import Seq2SeqTrainer\n",
|
738 |
+
"\n",
|
739 |
+
"trainer = Seq2SeqTrainer(\n",
|
740 |
+
" args=training_args,\n",
|
741 |
+
" model=model,\n",
|
742 |
+
" train_dataset=vectorized_datasets[\"train\"],\n",
|
743 |
+
" eval_dataset=vectorized_datasets[\"test\"],\n",
|
744 |
+
" data_collator=data_collator,\n",
|
745 |
+
" compute_metrics=compute_metrics,\n",
|
746 |
+
" tokenizer=processor,\n",
|
747 |
+
" callbacks=[ShuffleCallback()],\n",
|
748 |
+
")"
|
749 |
+
]
|
750 |
+
},
|
751 |
+
{
|
752 |
+
"cell_type": "markdown",
|
753 |
+
"id": "67ab88c3-7091-4e51-8ad5-f5cacbe18449",
|
754 |
+
"metadata": {},
|
755 |
+
"source": [
|
756 |
+
"We'll save the model and processor to the output directory before training:"
|
757 |
+
]
|
758 |
+
},
|
759 |
+
{
|
760 |
+
"cell_type": "code",
|
761 |
+
"execution_count": null,
|
762 |
+
"id": "a1ccb9ed-cbc8-4419-91c0-651e9424b672",
|
763 |
+
"metadata": {},
|
764 |
+
"outputs": [],
|
765 |
+
"source": [
|
766 |
+
"model.save_pretrained(training_args.output_dir)\n",
|
767 |
+
"processor.save_pretrained(training_args.output_dir)"
|
768 |
+
]
|
769 |
+
},
|
770 |
+
{
|
771 |
+
"cell_type": "markdown",
|
772 |
+
"id": "7f404cf9-4345-468c-8196-4bd101d9bd51",
|
773 |
+
"metadata": {},
|
774 |
+
"source": [
|
775 |
+
"### Training"
|
776 |
+
]
|
777 |
+
},
|
778 |
+
{
|
779 |
+
"cell_type": "markdown",
|
780 |
+
"id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112",
|
781 |
+
"metadata": {},
|
782 |
+
"source": [
|
783 |
+
"Training will take approximately 5-10 hours depending on your GPU. The peak GPU memory for the given training configuration is approximately 36GB. \n",
|
784 |
+
"Depending on your GPU, it is possible that you will encounter a CUDA `\"out-of-memory\"` error when you launch training. \n",
|
785 |
+
"In this case, you can reduce the `per_device_train_batch_size` incrementally by factors of 2 \n",
|
786 |
+
"and employ [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.gradient_accumulation_steps)\n",
|
787 |
+
"to compensate.\n",
|
788 |
+
"\n",
|
789 |
+
"To launch training, simply execute:"
|
790 |
+
]
|
791 |
+
},
|
792 |
+
{
|
793 |
+
"cell_type": "code",
|
794 |
+
"execution_count": null,
|
795 |
+
"id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de",
|
796 |
+
"metadata": {},
|
797 |
+
"outputs": [],
|
798 |
+
"source": [
|
799 |
+
"trainer.train()"
|
800 |
+
]
|
801 |
+
},
|
802 |
+
{
|
803 |
+
"cell_type": "markdown",
|
804 |
+
"id": "747c6a6e",
|
805 |
+
"metadata": {
|
806 |
+
"pycharm": {
|
807 |
+
"name": "#%% md\n"
|
808 |
+
}
|
809 |
+
},
|
810 |
+
"source": [
|
811 |
+
"(note that training may take some time to commence as we load the first training data samples with streaming mode)"
|
812 |
+
]
|
813 |
+
},
|
814 |
+
{
|
815 |
+
"cell_type": "markdown",
|
816 |
+
"id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3",
|
817 |
+
"metadata": {},
|
818 |
+
"source": [
|
819 |
+
"We can label our checkpoint with the `whisper-event` tag on push by setting the appropriate key-word arguments (kwargs):"
|
820 |
+
]
|
821 |
+
},
|
822 |
+
{
|
823 |
+
"cell_type": "code",
|
824 |
+
"execution_count": null,
|
825 |
+
"id": "6dd0e310-9b07-4133-ac14-2ed2d7524e22",
|
826 |
+
"metadata": {},
|
827 |
+
"outputs": [],
|
828 |
+
"source": [
|
829 |
+
"kwargs = {\n",
|
830 |
+
" \"dataset_tags\": \"mozilla-foundation/common_voice_11_0\",\n",
|
831 |
+
" \"dataset\": \"Common Voice 11.0\", # a 'pretty' name for the training dataset\n",
|
832 |
+
" \"language\": \"es\",\n",
|
833 |
+
" \"model_name\": \"Whisper Small Es - Sanchit Gandhi\", # a 'pretty' name for your model\n",
|
834 |
+
" \"finetuned_from\": \"openai/whisper-small\",\n",
|
835 |
+
" \"tasks\": \"automatic-speech-recognition\",\n",
|
836 |
+
" \"tags\": \"whisper-event\",\n",
|
837 |
+
"}"
|
838 |
+
]
|
839 |
+
},
|
840 |
+
{
|
841 |
+
"cell_type": "markdown",
|
842 |
+
"id": "090d676a-f944-4297-a938-a40eda0b2b68",
|
843 |
+
"metadata": {},
|
844 |
+
"source": [
|
845 |
+
"The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command:"
|
846 |
+
]
|
847 |
+
},
|
848 |
+
{
|
849 |
+
"cell_type": "code",
|
850 |
+
"execution_count": null,
|
851 |
+
"id": "95737cda-c5dd-4887-a4d0-dfcb0d61d977",
|
852 |
+
"metadata": {},
|
853 |
+
"outputs": [],
|
854 |
+
"source": [
|
855 |
+
"trainer.push_to_hub(**kwargs)"
|
856 |
+
]
|
857 |
+
}
|
858 |
+
],
|
859 |
+
"metadata": {
|
860 |
+
"kernelspec": {
|
861 |
+
"display_name": "Python 3 (ipykernel)",
|
862 |
+
"language": "python",
|
863 |
+
"name": "python3"
|
864 |
+
},
|
865 |
+
"language_info": {
|
866 |
+
"codemirror_mode": {
|
867 |
+
"name": "ipython",
|
868 |
+
"version": 3
|
869 |
+
},
|
870 |
+
"file_extension": ".py",
|
871 |
+
"mimetype": "text/x-python",
|
872 |
+
"name": "python",
|
873 |
+
"nbconvert_exporter": "python",
|
874 |
+
"pygments_lexer": "ipython3",
|
875 |
+
"version": "3.8.9"
|
876 |
+
}
|
877 |
+
},
|
878 |
+
"nbformat": 4,
|
879 |
+
"nbformat_minor": 5
|
880 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=1.7
|
2 |
+
torchaudio
|
3 |
+
git+https://github.com/huggingface/transformers
|
4 |
+
git+https://github.com/huggingface/datasets
|
5 |
+
librosa
|
6 |
+
jiwer
|
7 |
+
evaluate>=0.3.0
|
8 |
+
more-itertools
|
9 |
+
tensorboard
|