{ "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": 5, "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": 6, "id": "a2787582-554f-44ce-9f38-4180a5ed6b44", "metadata": {}, "outputs": [], "source": [ "from datasets import IterableDatasetDict\n", "\n", "raw_datasets = IterableDatasetDict()\n", "\n", "raw_datasets[\"train\"] = load_streaming_dataset(\"mozilla-foundation/common_voice_11_0\", \"ja\", split=\"train+validation\", use_auth_token=True) # set split=\"train+validation\" for low-resource\n", "raw_datasets[\"test\"] = load_streaming_dataset(\"mozilla-foundation/common_voice_11_0\", \"ja\", split=\"test\", use_auth_token=True)" ] }, { "cell_type": "markdown", "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605", "metadata": {}, "source": [ "## Prepare Processor and Pre-Process Data" ] }, { "cell_type": "markdown", "id": "601c3099-1026-439e-93e2-5635b3ba5a73", "metadata": {}, "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. 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", "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", "the `processor` and the `model`.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 7, "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6", "metadata": {}, "outputs": [], "source": [ "from transformers import WhisperProcessor\n", "\n", "processor = WhisperProcessor.from_pretrained(\"openai/whisper-small\", language=\"japanese\", task=\"transcribe\")" ] }, { "cell_type": "markdown", "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c", "metadata": {}, "source": [ "### Pre-Process Data" ] }, { "cell_type": "markdown", "id": "bf10cd3e-924e-44fc-8790-46e413de7b3d", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 8, "id": "ab5a13b4-9bd4-4aa0-aef2-b3de9b762988", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'client_id': Value(dtype='string', id=None),\n", " 'path': Value(dtype='string', id=None),\n", " 'audio': Audio(sampling_rate=48000, mono=True, decode=True, id=None),\n", " 'sentence': Value(dtype='string', id=None),\n", " 'up_votes': Value(dtype='int64', id=None),\n", " 'down_votes': Value(dtype='int64', id=None),\n", " 'age': Value(dtype='string', id=None),\n", " 'gender': Value(dtype='string', id=None),\n", " 'accent': Value(dtype='string', id=None),\n", " 'locale': Value(dtype='string', id=None),\n", " 'segment': Value(dtype='string', id=None)}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "raw_datasets[\"train\"].features" ] }, { "cell_type": "markdown", "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd", "metadata": {}, "source": [ "Since our input audio is sampled at 48kHz, we need to _downsample_ it to\n", "16kHz prior to passing it to the Whisper feature extractor, 16kHz being the sampling rate expected by the Whisper model. \n", "\n", "We'll set the audio inputs to the correct sampling rate using dataset's \n", "[`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column)\n", "method. This operation does not change the audio in-place, \n", "but rather signals to `datasets` to resample audio samples _on the fly_ the \n", "first time that they are loaded:" ] }, { "cell_type": "code", "execution_count": 9, "id": "3ab6a724-3d1e-478b-a9e9-d2f85feb6c39", "metadata": {}, "outputs": [], "source": [ "from datasets import Audio\n", "\n", "raw_datasets = raw_datasets.cast_column(\"audio\", Audio(sampling_rate=16000))" ] }, { "cell_type": "markdown", "id": "161322c2-94f3-4d26-9e1d-d9d5202ca3cf", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 10, "id": "d041650e-1c48-4439-87b3-5b6f4a514107", "metadata": {}, "outputs": [], "source": [ "from transformers.models.whisper.english_normalizer import BasicTextNormalizer\n", "\n", "do_lower_case = False\n", "do_remove_punctuation = False\n", "\n", "normalizer = BasicTextNormalizer()" ] }, { "cell_type": "markdown", "id": "bfaa935b-a11d-497c-88c1-0c4d1bb3247b", "metadata": {}, "source": [ "Now we can write a function to prepare our data ready for the model:\n", "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", "2. We use the feature extractor to compute the log-Mel spectrogram input features from our 1-dimensional audio array.\n", "3. We perform any optional pre-processing (lower-case or remove punctuation).\n", "4. We encode the transcriptions to label ids through the use of the tokenizer." ] }, { "cell_type": "code", "execution_count": 44, "id": "c085911c-a10a-41ef-8874-306e0503e9bb", "metadata": {}, "outputs": [], "source": [ "def prepare_dataset(batch):\n", " # load and (possibly) resample audio data to 16kHz\n", " audio = batch[\"audio\"]\n", "\n", " # compute log-Mel input features from input audio array \n", " batch[\"input_features\"] = processor.feature_extractor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_features[0]\n", " # compute input length of audio sample in seconds\n", " batch[\"input_length\"] = len(audio[\"array\"]) / audio[\"sampling_rate\"]\n", " \n", " # optional pre-processing steps\n", " transcription = batch[\"sentence\"]\n", " if do_lower_case:\n", " transcription = transcription.lower()\n", " if do_remove_punctuation:\n", " transcription = normalizer(transcription).strip()\n", " \n", " # encode target text to label ids\n", "# batch[\"labels\"] = processor.tokenizer(transcription).input_ids\n", " batch['labels'] = transcription\n", " return batch" ] }, { "cell_type": "markdown", "id": "70b319fb-2439-4ef6-a70d-a47bf41c4a13", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 45, "id": "a37a7cdb-9013-427f-8de9-6a8d0e9dc684", "metadata": {}, "outputs": [], "source": [ "vectorized_datasets = raw_datasets.map(prepare_dataset, remove_columns=list(next(iter(raw_datasets.values())).features)).with_format(\"torch\")" ] }, { "cell_type": "markdown", "id": "3d59b37e-4950-47ec-9e3e-2cf2ec7fc750", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 46, "id": "1b145699-acfc-4b1d-93a2-a2ad3d62674c", "metadata": {}, "outputs": [], "source": [ "vectorized_datasets[\"train\"] = vectorized_datasets[\"train\"].shuffle(\n", " buffer_size=500,\n", " seed=0,\n", ")" ] }, { "cell_type": "markdown", "id": "666b9ef0-7909-4e1e-a419-87604d233e29", "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": 47, "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": "28e37ac3-b1c5-465b-8586-7cfd8d76b0f1", "metadata": {}, "source": [ "We apply our filter function to all samples of our training dataset through ๐Ÿค— Datasets' `.filter` method:" ] }, { "cell_type": "code", "execution_count": 48, "id": "333f7f6e-6053-4d3b-8924-c733c79b82ac", "metadata": {}, "outputs": [], "source": [ "vectorized_datasets[\"train\"] = vectorized_datasets[\"train\"].filter(\n", " is_audio_in_length_range,\n", " input_columns=[\"input_length\"],\n", ")" ] }, { "cell_type": "code", "execution_count": 49, "id": "bede1184", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Reading metadata...: 6505it [00:00, 35406.66it/s]\n", "Reading metadata...: 4485it [00:00, 19930.24it/s]\n" ] }, { "data": { "text/plain": [ "'ๅคšใ‹ใ‚‰ไธ€ใธใจใ„ใ†ใฎใฏใ€ไธ–็•Œใ‚’ๅ› ๆžœ็š„ใซๆฑบๅฎš่ซ–็š„ใซ่€ƒใˆใ‚‹ใ“ใจใงใ‚ใ‚‹ใ€้ŽๅŽปใ‹ใ‚‰่€ƒใˆใ‚‹ใ“ใจใงใ‚ใ‚‹ใ€ๆฉŸๆขฐ็š„ใซ่€ƒใˆใ‚‹ใ“ใจใงใ‚ใ‚‹ใ€‚'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "xb = next(iter(vectorized_datasets['train']))\n", "xb['labels']" ] }, { "cell_type": "code", "execution_count": 59, "id": "ac1e8d5b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<|startoftranscript|>\n", "<|ja|>\n", "<|transcribe|>\n", "<|notimestamps|>\n", "ๅคš\n", "ใ‹ใ‚‰\n", "ไธ€\n", "ใธ\n", "ใจใ„ใ†\n", "ใฎใฏ\n", "ใ€\n", "ไธ–็•Œ\n", "ใ‚’\n", "ๅ› \n", "ๆžœ\n", "็š„\n", "ใซ\n", "ๆฑบ\n", "ๅฎš\n", "่ซ–\n", "็š„\n", "ใซ\n", "่€ƒ\n", "ใˆใ‚‹\n", "ใ“ใจ\n", "ใง\n", "ใ‚ใ‚‹\n", "ใ€\n", "้ŽๅŽป\n", "ใ‹ใ‚‰\n", "่€ƒ\n", "ใˆใ‚‹\n", "ใ“ใจ\n", "ใง\n", "ใ‚ใ‚‹\n", "ใ€\n", "ๆฉŸ\n", "๏ฟฝ\n", "๏ฟฝ\n", "็š„\n", "ใซ\n", "่€ƒ\n", "ใˆใ‚‹\n", "ใ“ใจ\n", "ใง\n", "ใ‚ใ‚‹\n", "ใ€‚\n", "<|endoftext|>\n" ] } ], "source": [ "idxs = processor.tokenizer(xb['labels']).input_ids\n", "for idx in idxs:\n", " print(processor.tokenizer.decode(idx))" ] }, { "cell_type": "code", "execution_count": 60, "id": "d33cefc4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[ๅคšใ‹ใ‚‰,\n", " ไธ€,\n", " ใธ,\n", " ใจ,\n", " ใ„ใ†,\n", " ใฎ,\n", " ใฏ,\n", " ใ€,\n", " ไธ–็•Œ,\n", " ใ‚’,\n", " ๅ› ๆžœ,\n", " ็š„,\n", " ใซ,\n", " ๆฑบๅฎš,\n", " ่ซ–,\n", " ็š„,\n", " ใซ,\n", " ่€ƒใˆใ‚‹,\n", " ใ“ใจ,\n", " ใง,\n", " ใ‚ใ‚‹,\n", " ใ€,\n", " ้ŽๅŽป,\n", " ใ‹ใ‚‰,\n", " ่€ƒใˆใ‚‹,\n", " ใ“ใจ,\n", " ใง,\n", " ใ‚ใ‚‹,\n", " ใ€,\n", " ๆฉŸๆขฐ,\n", " ็š„,\n", " ใซ,\n", " ่€ƒใˆใ‚‹,\n", " ใ“ใจ,\n", " ใง,\n", " ใ‚ใ‚‹,\n", " ใ€‚]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tagger(xb['labels'])" ] }, { "cell_type": "code", "execution_count": 55, "id": "2cbb82ef", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on method decode in module transformers.tokenization_utils_base:\n", "\n", "decode(token_ids: Union[int, List[int], ForwardRef('np.ndarray'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor')], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True, **kwargs) -> str method of transformers.models.whisper.tokenization_whisper.WhisperTokenizer instance\n", " Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\n", " tokens and clean up tokenization spaces.\n", " \n", " Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n", " \n", " Args:\n", " token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):\n", " List of tokenized input ids. Can be obtained using the `__call__` method.\n", " skip_special_tokens (`bool`, *optional*, defaults to `False`):\n", " Whether or not to remove special tokens in the decoding.\n", " clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):\n", " Whether or not to clean up the tokenization spaces.\n", " kwargs (additional keyword arguments, *optional*):\n", " Will be passed to the underlying model specific decode method.\n", " \n", " Returns:\n", " `str`: The decoded sentence.\n", "\n" ] } ], "source": [ "help(processor.tokenizer.decode)" ] }, { "cell_type": "code", "execution_count": 41, "id": "b4b9bbfc", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'้บฉ ่“ๅญ ใฏ ใ€ ้บฉ ใ‚’ ไธปๆ ๆ–™ ใจ ใ— ใŸ ๆ—ฅๆœฌ ใฎ ่“ๅญ ใ€‚'" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from fugashi import Tagger\n", "\n", "tagger = Tagger('-Owakati')\n", "text = \"้บฉ่“ๅญใฏใ€้บฉใ‚’ไธปๆๆ–™ใจใ—ใŸๆ—ฅๆœฌใฎ่“ๅญใ€‚\"\n", "tagger.parse(text)" ] }, { "cell_type": "code", "execution_count": 43, "id": "833ca62d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[้บฉ, ่“ๅญ, ใฏ, ใ€, ้บฉ, ใ‚’, ไธปๆ, ๆ–™, ใจ, ใ—, ใŸ, ๆ—ฅๆœฌ, ใฎ, ่“ๅญ, ใ€‚]" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tagger(text)" ] }, { "cell_type": "code", "execution_count": null, "id": "7b7854d6", "metadata": {}, "outputs": [], "source": [ "raw_datasets['']" ] }, { "cell_type": "markdown", "id": "263a5a58-0239-4a25-b0df-c625fc9c5810", "metadata": {}, "source": [ "## Training and Evaluation" ] }, { "cell_type": "markdown", "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7", "metadata": {}, "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." ] }, { "cell_type": "markdown", "id": "8d230e6d-624c-400a-bbf5-fa660881df25", "metadata": {}, "source": [ "### Define a Data Collator" ] }, { "cell_type": "markdown", "id": "04def221-0637-4a69-b242-d3f0c1d0ee78", "metadata": {}, "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": 16, "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5", "metadata": {}, "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": {}, "source": [ "Let's initialise the data collator we've just defined:" ] }, { "cell_type": "code", "execution_count": 17, "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": 18, "id": "b22b4011-f31f-4b57-b684-c52332f92890", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "bffdd7b1fed44295954d9eed41a9cfd5", "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": 20, "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "48fee2fd3b2a4a67b3a35666fda4dfe9", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading: 0%| | 0.00/1.97k [00:00\n", " \n", " \n", " [1000/1000 3:35:08, Epoch 7.01/9223372036854775807]\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining LossValidation LossWer
2000.2208000.27811981.117889
4000.1367000.26916873.102568
6000.0338000.27834670.960420
8000.0263000.29878574.734005

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Reading metadata...: 6505it [00:00, 64162.65it/s]\n", "Reading metadata...: 4485it [00:00, 27834.06it/s]\n", "***** Running Evaluation *****\n", " Num examples: Unknown\n", " Batch size = 8\n", "Reading metadata...: 4604it [00:00, 27155.92it/s]\n", "The following columns in the evaluation set don't have a corresponding argument in `WhisperForConditionalGeneration.forward` and have been ignored: input_length. If input_length are not expected by `WhisperForConditionalGeneration.forward`, you can safely ignore this message.\n", "Saving model checkpoint to ./checkpoint-200\n", "Configuration saved in ./checkpoint-200/config.json\n", "Model weights saved in ./checkpoint-200/pytorch_model.bin\n", "Feature extractor saved in ./checkpoint-200/preprocessor_config.json\n", "tokenizer config file saved in ./checkpoint-200/tokenizer_config.json\n", "Special tokens file saved in ./checkpoint-200/special_tokens_map.json\n", "added tokens file saved in ./checkpoint-200/added_tokens.json\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", "Reading metadata...: 6505it [00:00, 44457.32it/s]\n", "Reading metadata...: 4485it [00:00, 29197.09it/s]\n", "***** Running Evaluation *****\n", " Num examples: Unknown\n", " Batch size = 8\n", "Reading metadata...: 4604it [00:00, 34447.62it/s]\n", "The following columns in the evaluation set don't have a corresponding argument in `WhisperForConditionalGeneration.forward` and have been ignored: input_length. If input_length are not expected by `WhisperForConditionalGeneration.forward`, you can safely ignore this message.\n", "Saving model checkpoint to ./checkpoint-400\n", "Configuration saved in ./checkpoint-400/config.json\n", "Model weights saved in ./checkpoint-400/pytorch_model.bin\n", "Feature extractor saved in ./checkpoint-400/preprocessor_config.json\n", "tokenizer config file saved in ./checkpoint-400/tokenizer_config.json\n", "Special tokens file saved in ./checkpoint-400/special_tokens_map.json\n", "added tokens file saved in ./checkpoint-400/added_tokens.json\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", "Reading metadata...: 6505it [00:00, 33208.71it/s]\n", "Reading metadata...: 4485it [00:00, 23213.70it/s]\n", "Reading metadata...: 6505it [00:00, 25768.67it/s]\n", "Reading metadata...: 4485it [00:00, 27756.07it/s]\n", "***** Running Evaluation *****\n", " Num examples: Unknown\n", " Batch size = 8\n", "Reading metadata...: 4604it [00:00, 28855.43it/s]\n", "The following columns in the evaluation set don't have a corresponding argument in `WhisperForConditionalGeneration.forward` and have been ignored: input_length. If input_length are not expected by `WhisperForConditionalGeneration.forward`, you can safely ignore this message.\n", "Saving model checkpoint to ./checkpoint-600\n", "Configuration saved in ./checkpoint-600/config.json\n", "Model weights saved in ./checkpoint-600/pytorch_model.bin\n", "Feature extractor saved in ./checkpoint-600/preprocessor_config.json\n", "tokenizer config file saved in ./checkpoint-600/tokenizer_config.json\n", "Special tokens file saved in ./checkpoint-600/special_tokens_map.json\n", "added tokens file saved in ./checkpoint-600/added_tokens.json\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", "Reading metadata...: 6505it [00:00, 86030.70it/s]\n", "Reading metadata...: 4485it [00:00, 68522.65it/s]\n", "***** Running Evaluation *****\n", " Num examples: Unknown\n", " Batch size = 8\n", "Reading metadata...: 4604it [00:00, 30988.60it/s]\n", "The following columns in the evaluation set don't have a corresponding argument in `WhisperForConditionalGeneration.forward` and have been ignored: input_length. If input_length are not expected by `WhisperForConditionalGeneration.forward`, you can safely ignore this message.\n", "Saving model checkpoint to ./checkpoint-800\n", "Configuration saved in ./checkpoint-800/config.json\n", "Model weights saved in ./checkpoint-800/pytorch_model.bin\n", "Feature extractor saved in ./checkpoint-800/preprocessor_config.json\n", "tokenizer config file saved in ./checkpoint-800/tokenizer_config.json\n", "Special tokens file saved in ./checkpoint-800/special_tokens_map.json\n", "added tokens file saved in ./checkpoint-800/added_tokens.json\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", "Reading metadata...: 6505it [00:00, 36357.17it/s]\n", "Reading metadata...: 4485it [00:00, 30574.75it/s]\n", "Got disconnected from remote data host. Retrying in 5sec [1/20]\n", "Got disconnected from remote data host. Retrying in 5sec [2/20]\n", "Reading metadata...: 6505it [00:00, 31147.16it/s]\n", "Reading metadata...: 4485it [00:00, 22808.34it/s]\n", "***** Running Evaluation *****\n", " Num examples: Unknown\n", " Batch size = 8\n", "Reading metadata...: 4604it [00:00, 28132.71it/s]\n", "The following columns in the evaluation set don't have a corresponding argument in `WhisperForConditionalGeneration.forward` and have been ignored: input_length. If input_length are not expected by `WhisperForConditionalGeneration.forward`, you can safely ignore this message.\n" ] }, { "ename": "KeyboardInterrupt", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[26], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mtrainer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrain\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer.py:1535\u001b[0m, in \u001b[0;36mTrainer.train\u001b[0;34m(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)\u001b[0m\n\u001b[1;32m 1530\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mmodel_wrapped \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mmodel\n\u001b[1;32m 1532\u001b[0m inner_training_loop \u001b[38;5;241m=\u001b[39m find_executable_batch_size(\n\u001b[1;32m 1533\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_inner_training_loop, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_train_batch_size, args\u001b[38;5;241m.\u001b[39mauto_find_batch_size\n\u001b[1;32m 1534\u001b[0m )\n\u001b[0;32m-> 1535\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43minner_training_loop\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1536\u001b[0m \u001b[43m \u001b[49m\u001b[43margs\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1537\u001b[0m \u001b[43m \u001b[49m\u001b[43mresume_from_checkpoint\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mresume_from_checkpoint\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1538\u001b[0m \u001b[43m \u001b[49m\u001b[43mtrial\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtrial\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1539\u001b[0m \u001b[43m \u001b[49m\u001b[43mignore_keys_for_eval\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mignore_keys_for_eval\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1540\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer.py:1860\u001b[0m, in \u001b[0;36mTrainer._inner_training_loop\u001b[0;34m(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)\u001b[0m\n\u001b[1;32m 1857\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstate\u001b[38;5;241m.\u001b[39mepoch \u001b[38;5;241m=\u001b[39m epoch \u001b[38;5;241m+\u001b[39m (step \u001b[38;5;241m+\u001b[39m \u001b[38;5;241m1\u001b[39m) \u001b[38;5;241m/\u001b[39m steps_in_epoch\n\u001b[1;32m 1858\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcontrol \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcallback_handler\u001b[38;5;241m.\u001b[39mon_step_end(args, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstate, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcontrol)\n\u001b[0;32m-> 1860\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_maybe_log_save_evaluate\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtr_loss\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtrial\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mepoch\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mignore_keys_for_eval\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1861\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 1862\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcontrol \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcallback_handler\u001b[38;5;241m.\u001b[39mon_substep_end(args, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstate, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcontrol)\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer.py:2123\u001b[0m, in \u001b[0;36mTrainer._maybe_log_save_evaluate\u001b[0;34m(self, tr_loss, model, trial, epoch, ignore_keys_for_eval)\u001b[0m\n\u001b[1;32m 2117\u001b[0m metrics \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mevaluate(\n\u001b[1;32m 2118\u001b[0m eval_dataset\u001b[38;5;241m=\u001b[39meval_dataset,\n\u001b[1;32m 2119\u001b[0m ignore_keys\u001b[38;5;241m=\u001b[39mignore_keys_for_eval,\n\u001b[1;32m 2120\u001b[0m metric_key_prefix\u001b[38;5;241m=\u001b[39m\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124meval_\u001b[39m\u001b[38;5;132;01m{\u001b[39;00meval_dataset_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m 2121\u001b[0m )\n\u001b[1;32m 2122\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m-> 2123\u001b[0m metrics \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mevaluate\u001b[49m\u001b[43m(\u001b[49m\u001b[43mignore_keys\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mignore_keys_for_eval\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2124\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_report_to_hp_search(trial, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstate\u001b[38;5;241m.\u001b[39mglobal_step, metrics)\n\u001b[1;32m 2126\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcontrol\u001b[38;5;241m.\u001b[39mshould_save:\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer_seq2seq.py:78\u001b[0m, in \u001b[0;36mSeq2SeqTrainer.evaluate\u001b[0;34m(self, eval_dataset, ignore_keys, metric_key_prefix, **gen_kwargs)\u001b[0m\n\u001b[1;32m 73\u001b[0m gen_kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnum_beams\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m (\n\u001b[1;32m 74\u001b[0m gen_kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnum_beams\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;28;01mif\u001b[39;00m gen_kwargs\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnum_beams\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39margs\u001b[38;5;241m.\u001b[39mgeneration_num_beams\n\u001b[1;32m 75\u001b[0m )\n\u001b[1;32m 76\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_gen_kwargs \u001b[38;5;241m=\u001b[39m gen_kwargs\n\u001b[0;32m---> 78\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mevaluate\u001b[49m\u001b[43m(\u001b[49m\u001b[43meval_dataset\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mignore_keys\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mignore_keys\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmetric_key_prefix\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmetric_key_prefix\u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer.py:2819\u001b[0m, in \u001b[0;36mTrainer.evaluate\u001b[0;34m(self, eval_dataset, ignore_keys, metric_key_prefix)\u001b[0m\n\u001b[1;32m 2816\u001b[0m start_time \u001b[38;5;241m=\u001b[39m time\u001b[38;5;241m.\u001b[39mtime()\n\u001b[1;32m 2818\u001b[0m eval_loop \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mprediction_loop \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39margs\u001b[38;5;241m.\u001b[39muse_legacy_prediction_loop \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mevaluation_loop\n\u001b[0;32m-> 2819\u001b[0m output \u001b[38;5;241m=\u001b[39m \u001b[43meval_loop\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2820\u001b[0m \u001b[43m \u001b[49m\u001b[43meval_dataloader\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2821\u001b[0m \u001b[43m \u001b[49m\u001b[43mdescription\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mEvaluation\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2822\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# No point gathering the predictions if there are no metrics, otherwise we defer to\u001b[39;49;00m\n\u001b[1;32m 2823\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# self.args.prediction_loss_only\u001b[39;49;00m\n\u001b[1;32m 2824\u001b[0m \u001b[43m \u001b[49m\u001b[43mprediction_loss_only\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcompute_metrics\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mis\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m 2825\u001b[0m \u001b[43m \u001b[49m\u001b[43mignore_keys\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mignore_keys\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2826\u001b[0m \u001b[43m \u001b[49m\u001b[43mmetric_key_prefix\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmetric_key_prefix\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2827\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2829\u001b[0m total_batch_size \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39margs\u001b[38;5;241m.\u001b[39meval_batch_size \u001b[38;5;241m*\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39margs\u001b[38;5;241m.\u001b[39mworld_size\n\u001b[1;32m 2830\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mmetric_key_prefix\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m_jit_compilation_time\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m output\u001b[38;5;241m.\u001b[39mmetrics:\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer.py:3001\u001b[0m, in \u001b[0;36mTrainer.evaluation_loop\u001b[0;34m(self, dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix)\u001b[0m\n\u001b[1;32m 2998\u001b[0m batch_size \u001b[38;5;241m=\u001b[39m observed_batch_size\n\u001b[1;32m 3000\u001b[0m \u001b[38;5;66;03m# Prediction step\u001b[39;00m\n\u001b[0;32m-> 3001\u001b[0m loss, logits, labels \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mprediction_step\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mprediction_loss_only\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mignore_keys\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mignore_keys\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 3002\u001b[0m inputs_decode \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_prepare_input(inputs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124minput_ids\u001b[39m\u001b[38;5;124m\"\u001b[39m]) \u001b[38;5;28;01mif\u001b[39;00m args\u001b[38;5;241m.\u001b[39minclude_inputs_for_metrics \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m 3004\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_torch_tpu_available():\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/trainer_seq2seq.py:213\u001b[0m, in \u001b[0;36mSeq2SeqTrainer.prediction_step\u001b[0;34m(self, model, inputs, prediction_loss_only, ignore_keys)\u001b[0m\n\u001b[1;32m 211\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m has_labels:\n\u001b[1;32m 212\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcompute_loss_context_manager():\n\u001b[0;32m--> 213\u001b[0m outputs \u001b[38;5;241m=\u001b[39m \u001b[43mmodel\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minputs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 214\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mlabel_smoother \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 215\u001b[0m loss \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mlabel_smoother(outputs, inputs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mlabels\u001b[39m\u001b[38;5;124m\"\u001b[39m])\u001b[38;5;241m.\u001b[39mmean()\u001b[38;5;241m.\u001b[39mdetach()\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/torch/nn/modules/module.py:1190\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1186\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1187\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1188\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1189\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1190\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1191\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1192\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/models/whisper/modeling_whisper.py:1197\u001b[0m, in \u001b[0;36mWhisperForConditionalGeneration.forward\u001b[0;34m(self, input_features, decoder_input_ids, decoder_attention_mask, head_mask, decoder_head_mask, cross_attn_head_mask, encoder_outputs, past_key_values, decoder_inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)\u001b[0m\n\u001b[1;32m 1192\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m decoder_input_ids \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m decoder_inputs_embeds \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 1193\u001b[0m decoder_input_ids \u001b[38;5;241m=\u001b[39m shift_tokens_right(\n\u001b[1;32m 1194\u001b[0m labels, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconfig\u001b[38;5;241m.\u001b[39mpad_token_id, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconfig\u001b[38;5;241m.\u001b[39mdecoder_start_token_id\n\u001b[1;32m 1195\u001b[0m )\n\u001b[0;32m-> 1197\u001b[0m outputs \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmodel\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1198\u001b[0m \u001b[43m \u001b[49m\u001b[43minput_features\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1199\u001b[0m \u001b[43m \u001b[49m\u001b[43mdecoder_input_ids\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_input_ids\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1200\u001b[0m \u001b[43m \u001b[49m\u001b[43mencoder_outputs\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mencoder_outputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1201\u001b[0m \u001b[43m \u001b[49m\u001b[43mdecoder_attention_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_attention_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1202\u001b[0m \u001b[43m \u001b[49m\u001b[43mhead_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mhead_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1203\u001b[0m \u001b[43m \u001b[49m\u001b[43mdecoder_head_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_head_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1204\u001b[0m \u001b[43m \u001b[49m\u001b[43mcross_attn_head_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcross_attn_head_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1205\u001b[0m \u001b[43m \u001b[49m\u001b[43mpast_key_values\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mpast_key_values\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1206\u001b[0m \u001b[43m \u001b[49m\u001b[43mdecoder_inputs_embeds\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_inputs_embeds\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1207\u001b[0m \u001b[43m \u001b[49m\u001b[43muse_cache\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43muse_cache\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1208\u001b[0m \u001b[43m \u001b[49m\u001b[43moutput_attentions\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43moutput_attentions\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1209\u001b[0m \u001b[43m \u001b[49m\u001b[43moutput_hidden_states\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43moutput_hidden_states\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1210\u001b[0m \u001b[43m \u001b[49m\u001b[43mreturn_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mreturn_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1211\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1212\u001b[0m lm_logits \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mproj_out(outputs[\u001b[38;5;241m0\u001b[39m])\n\u001b[1;32m 1214\u001b[0m loss \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/torch/nn/modules/module.py:1190\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1186\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1187\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1188\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1189\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1190\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1191\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1192\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/models/whisper/modeling_whisper.py:1066\u001b[0m, in \u001b[0;36mWhisperModel.forward\u001b[0;34m(self, input_features, decoder_input_ids, decoder_attention_mask, head_mask, decoder_head_mask, cross_attn_head_mask, encoder_outputs, past_key_values, decoder_inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict)\u001b[0m\n\u001b[1;32m 1059\u001b[0m encoder_outputs \u001b[38;5;241m=\u001b[39m BaseModelOutput(\n\u001b[1;32m 1060\u001b[0m last_hidden_state\u001b[38;5;241m=\u001b[39mencoder_outputs[\u001b[38;5;241m0\u001b[39m],\n\u001b[1;32m 1061\u001b[0m hidden_states\u001b[38;5;241m=\u001b[39mencoder_outputs[\u001b[38;5;241m1\u001b[39m] \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(encoder_outputs) \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m1\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 1062\u001b[0m attentions\u001b[38;5;241m=\u001b[39mencoder_outputs[\u001b[38;5;241m2\u001b[39m] \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(encoder_outputs) \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 1063\u001b[0m )\n\u001b[1;32m 1065\u001b[0m \u001b[38;5;66;03m# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)\u001b[39;00m\n\u001b[0;32m-> 1066\u001b[0m decoder_outputs \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecoder\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1067\u001b[0m \u001b[43m \u001b[49m\u001b[43minput_ids\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_input_ids\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1068\u001b[0m \u001b[43m \u001b[49m\u001b[43mattention_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_attention_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1069\u001b[0m \u001b[43m \u001b[49m\u001b[43mencoder_hidden_states\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mencoder_outputs\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1070\u001b[0m \u001b[43m \u001b[49m\u001b[43mhead_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_head_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1071\u001b[0m \u001b[43m \u001b[49m\u001b[43mcross_attn_head_mask\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcross_attn_head_mask\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1072\u001b[0m \u001b[43m \u001b[49m\u001b[43mpast_key_values\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mpast_key_values\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1073\u001b[0m \u001b[43m \u001b[49m\u001b[43minputs_embeds\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecoder_inputs_embeds\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1074\u001b[0m \u001b[43m \u001b[49m\u001b[43muse_cache\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43muse_cache\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1075\u001b[0m \u001b[43m \u001b[49m\u001b[43moutput_attentions\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43moutput_attentions\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1076\u001b[0m \u001b[43m \u001b[49m\u001b[43moutput_hidden_states\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43moutput_hidden_states\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1077\u001b[0m \u001b[43m \u001b[49m\u001b[43mreturn_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mreturn_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1078\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1080\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m return_dict:\n\u001b[1;32m 1081\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m decoder_outputs \u001b[38;5;241m+\u001b[39m encoder_outputs\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/torch/nn/modules/module.py:1190\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1186\u001b[0m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[1;32m 1187\u001b[0m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[1;32m 1188\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[1;32m 1189\u001b[0m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[0;32m-> 1190\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1191\u001b[0m \u001b[38;5;66;03m# Do not call functions when jit is used\u001b[39;00m\n\u001b[1;32m 1192\u001b[0m full_backward_hooks, non_full_backward_hooks \u001b[38;5;241m=\u001b[39m [], []\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/models/whisper/modeling_whisper.py:866\u001b[0m, in \u001b[0;36mWhisperDecoder.forward\u001b[0;34m(self, input_ids, attention_mask, encoder_hidden_states, head_mask, cross_attn_head_mask, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict)\u001b[0m\n\u001b[1;32m 863\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m inputs_embeds \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 864\u001b[0m inputs_embeds \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39membed_tokens(input_ids)\n\u001b[0;32m--> 866\u001b[0m attention_mask \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_prepare_decoder_attention_mask\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 867\u001b[0m \u001b[43m \u001b[49m\u001b[43mattention_mask\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minput_shape\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minputs_embeds\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpast_key_values_length\u001b[49m\n\u001b[1;32m 868\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 870\u001b[0m \u001b[38;5;66;03m# embed positions\u001b[39;00m\n\u001b[1;32m 871\u001b[0m positions \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39membed_positions(input_ids, past_key_values_length\u001b[38;5;241m=\u001b[39mpast_key_values_length)\n", "File \u001b[0;32m~/.venv/lib/python3.8/site-packages/transformers/models/whisper/modeling_whisper.py:758\u001b[0m, in \u001b[0;36mWhisperDecoder._prepare_decoder_attention_mask\u001b[0;34m(self, attention_mask, input_shape, inputs_embeds, past_key_values_length)\u001b[0m\n\u001b[1;32m 755\u001b[0m combined_attention_mask \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m 757\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m input_shape[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m] \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m1\u001b[39m:\n\u001b[0;32m--> 758\u001b[0m combined_attention_mask \u001b[38;5;241m=\u001b[39m \u001b[43m_make_causal_mask\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 759\u001b[0m \u001b[43m \u001b[49m\u001b[43minput_shape\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minputs_embeds\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdtype\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpast_key_values_length\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mpast_key_values_length\u001b[49m\n\u001b[1;32m 760\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mto\u001b[49m\u001b[43m(\u001b[49m\u001b[43minputs_embeds\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdevice\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 762\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m attention_mask \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 763\u001b[0m \u001b[38;5;66;03m# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\u001b[39;00m\n\u001b[1;32m 764\u001b[0m expanded_attn_mask \u001b[38;5;241m=\u001b[39m _expand_mask(attention_mask, inputs_embeds\u001b[38;5;241m.\u001b[39mdtype, tgt_len\u001b[38;5;241m=\u001b[39minput_shape[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m])\n", "\u001b[0;31mKeyboardInterrupt\u001b[0m: " ] } ], "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": 27, "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\": \"ja\",\n", " \"model_name\": \"Whisper Small Japanese - 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": 28, "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" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a47d7e61b9144723a4208cc4cc492eee", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Upload file pytorch_model.bin: 0%| | 32.0k/922M [00:00 main\n", "\n", "Dropping the following result as it does not have all the necessary fields:\n", "{'task': {'name': 'Automatic Speech Recognition', 'type': 'automatic-speech-recognition'}, 'dataset': {'name': 'Common Voice 11.0', 'type': 'mozilla-foundation/common_voice_11_0', 'config': 'ja', 'split': 'test', 'args': 'ja'}}\n", "To https://huggingface.co/kimbochen/whisper-small-jp\n", " 0ff52f0..22e3a01 main -> main\n", "\n" ] }, { "data": { "text/plain": [ "'https://huggingface.co/kimbochen/whisper-small-jp/commit/0ff52f0f1d63daf816427096a83f7bbf8f3892eb'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "trainer.push_to_hub(**kwargs)" ] }, { "cell_type": "code", "execution_count": 28, "id": "4df1603c-ef35-40f1-ae57-3214441073c8", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "PyTorch: setting up devices\n" ] } ], "source": [ "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", " max_steps=1000,\n", " num_train_epochs=-1,\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": "code", "execution_count": 29, "id": "afc2b554-7171-48c7-95aa-b7e61b70ab20", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ubuntu/whisper-small-jp/./ is already a clone of https://huggingface.co/kimbochen/whisper-small-jp. Make sure you pull the latest changes with `repo.git_pull()`.\n", "max_steps is given, it will override any value given in num_train_epochs\n", "Using cuda_amp half precision backend\n" ] } ], "source": [ "trainer = Seq2SeqTrainer(\n", " args=training_args,\n", " model=model,\n", " train_dataset=vectorized_datasets[\"train\"],\n", " eval_dataset=vectorized_datasets[\"test\"],\n", " data_collator=data_collator,\n", " compute_metrics=compute_metrics,\n", " tokenizer=processor,\n", " callbacks=[ShuffleCallback()],\n", ")" ] }, { "cell_type": "code", "execution_count": 30, "id": "b029a1d8-24de-46e7-b067-0f900b1db342", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Loading model from checkpoint-4000.\n", "/home/ubuntu/.venv/lib/python3.8/site-packages/transformers/optimization.py:306: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning\n", " warnings.warn(\n", "***** Running training *****\n", " Num examples = 64000\n", " Num Epochs = 9223372036854775807\n", " Instantaneous batch size per device = 64\n", " Total train batch size (w. parallel, distributed & accumulation) = 64\n", " Gradient Accumulation steps = 1\n", " Total optimization steps = 1000\n", " Number of trainable parameters = 241734912\n", " Continuing training from checkpoint, will skip to saved global_step\n", " Continuing training from epoch 4\n", " Continuing training from global step 4000\n", " Will skip the first 4 epochs then the first 0 batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` flag to your launch command, but you will resume the training on data already seen by your model.\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "01337298313740d98d3cc75b6d5e3ff7", "version_major": 2, "version_minor": 0 }, "text/plain": [ "0it [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "\n", "Reading metadata...: 0it [00:00, ?it/s]\u001b[A\n", "Reading metadata...: 6505it [00:00, 34246.80it/s]\n", "The following columns in the training set don't have a corresponding argument in `WhisperForConditionalGeneration.forward` and have been ignored: input_length. If input_length are not expected by `WhisperForConditionalGeneration.forward`, you can safely ignore this message.\n", "\n", "Reading metadata...: 6505it [00:00, 84823.64it/s]\n", "\n", "Reading metadata...: 6505it [00:00, 88617.62it/s]\n", "\n", "Reading metadata...: 6505it [00:00, 90289.78it/s]\n", "\n", "Reading metadata...: 6505it [00:00, 91816.92it/s]\n" ] }, { "data": { "text/html": [ "\n", "

\n", " \n", " \n", " [1000/1000 00:00, Epoch 4/9223372036854775807]\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining LossValidation Loss

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "\n", "\n", "Training completed. Do not forget to share your model on huggingface.co/models =)\n", "\n", "\n", "Loading best model from ./checkpoint-4000 (score: 88.31039863810469).\n" ] }, { "data": { "text/plain": [ "TrainOutput(global_step=4001, training_loss=8.343380785802548e-08, metrics={'train_runtime': 169.0541, 'train_samples_per_second': 378.577, 'train_steps_per_second': 5.915, 'total_flos': 7.363747084345344e+19, 'train_loss': 8.343380785802548e-08, 'epoch': 4.0})" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "trainer.train(\"checkpoint-4000\")" ] } ], "metadata": { "kernelspec": { "display_name": "wspsr", "language": "python", "name": "wspsr" }, "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 }