Urdu-ASR-SOTA / notebook.ipynb
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "LBSYoWbi-45k"
},
"source": [
"# **Fine-tuning XLS-R for Multi-Lingual ASR with πŸ€— Transformers**\n",
"\n",
"***New (11/2021)***: *This blog post has been updated to feature XLSR's successor, called [XLS-R](https://huggingface.co/models?other=xls_r)*."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nT_QrfWtsxIz"
},
"source": [
"## Notebook Setup"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wcHuXIaWyHZU"
},
"source": [
"First, let's try to get a good GPU in our colab! With Google Colab's free version it's sadly becoming much harder to get access to a good GPU. With Google Colab Pro, however, one should easily get either a V100 or P100 GPU."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "YELVqGxMxnbG",
"outputId": "70b5afa4-6790-4c60-821b-dd6600c8e092"
},
"outputs": [],
"source": [
"gpu_info = !nvidia-smi\n",
"gpu_info = '\\n'.join(gpu_info)\n",
"if gpu_info.find('failed') >= 0:\n",
" print('Not connected to a GPU')\n",
"else:\n",
" print(gpu_info)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "e335hPmdtASZ"
},
"source": [
"Before we start, let's install `datasets` and `transformers`. Also, we need the `torchaudio` to load audio files and `jiwer` to evaluate our fine-tuned model using the [word error rate (WER)](https://huggingface.co/metrics/wer) metric ${}^1$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c8eh87Hoee5d"
},
"outputs": [],
"source": [
"%%capture\n",
"!pip install datasets\n",
"!pip install -U datasets\n",
"!pip install -U transformers\n",
"!pip install huggingface_hub\n",
"!pip install torchaudio\n",
"!pip install jiwer\n",
"!pip install mlflow\n",
"!pip install fastds\n",
"!pip install dvc\n",
"!pip install dagshub"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7FRuaqUOVLCt"
},
"outputs": [],
"source": [
"!fds clone https://dagshub.com/kingabzpro/Urdu-ASR-SOTA.git /content/Urdu-ASR"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Mn9swf6EQ9Vd"
},
"source": [
"\n",
"\n",
"\n",
"---\n",
"\n",
"${}^1$ In the [paper](https://arxiv.org/pdf/2006.13979.pdf), the model was evaluated using the phoneme error rate (PER), but by far the most common metric in ASR is the word error rate (WER). To keep this notebook as general as possible we decided to evaluate the model using WER."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0mW-C1Nt-j7k"
},
"source": [
"## Prepare Data, Tokenizer, Feature Extractor"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BeBosnY9BH3e"
},
"source": [
"ASR models transcribe speech to text, which means that we both need a feature extractor that processes the speech signal to the model's input format, *e.g.* a feature vector, and a tokenizer that processes the model's output format to text. \n",
"\n",
"In πŸ€— Transformers, the XLS-R model is thus accompanied by both a tokenizer, called [Wav2Vec2CTCTokenizer](https://huggingface.co/transformers/master/model_doc/wav2vec2.html#wav2vec2ctctokenizer), and a feature extractor, called [Wav2Vec2FeatureExtractor](https://huggingface.co/transformers/master/model_doc/wav2vec2.html#wav2vec2featureextractor).\n",
"\n",
"Let's start by creating the tokenizer to decode the predicted output classes to the output transcription."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sEXEWEJGQPqD"
},
"source": [
"### Create `Wav2Vec2CTCTokenizer`"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tWmMikuNEKl_"
},
"source": [
"A pre-trained XLS-R model maps the speech signal to a sequence of context representations as illustrated in the figure above. However, for speech recognition the model has to to map this sequence of context representations to its corresponding transcription which means that a linear layer has to be added on top of the transformer block (shown in yellow in the diagram above). This linear layer is used to classifies each context representation to a token class analogous how, *e.g.*, after pretraining a linear layer is added on top of BERT's embeddings for further classification - *cf.* with *'BERT'* section of this [blog post](https://huggingface.co/blog/warm-starting-encoder-decoder)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "v5oRE8XjIUH3"
},
"source": [
"The output size of this layer corresponds to the number of tokens in the vocabulary, which does **not** depend onXLS-R's pretraining task, but only on the labeled dataset used for fine-tuning. So in the first step, we will take a look at the chosen dataset of Common Voice and define a vocabulary based on the transcriptions."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "idBczw8mWzgt"
},
"source": [
"First, let's go to Common Voice [official website](https://commonvoice.mozilla.org/en/datasets) and pick a language to fine-tune XLS-R on. For this notebook, we will use Turkish. \n",
"\n",
"For each language-specific dataset, you can find a language code corresponding to your chosen language. On [Common Voice](https://commonvoice.mozilla.org/en/datasets), look for the field \"Version\". The language code then corresponds to the prefix before the underscore. For Urdu, *e.g.* the language code is `\"ur\"`.\n",
"\n",
"Great, now we can use πŸ€— Datasets' simple API to download the data. The dataset name is `\"common_voice\"`, the configuration name corresponds to the language code, which is `\"ur\"` in our case."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bee4g9rpLxll"
},
"source": [
"Common Voice has many different splits including `invalidated`, which refers to data that was not rated as \"clean enough\" to be considered useful. In this notebook, we will only make use of the splits `\"train\"`, `\"validation\"` and `\"test\"`. \n",
"\n",
"Because the Turkish dataset is so small, we will merge both the validation and training data into a training dataset and only use the test data for validation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "QypfbmGCXQrF",
"outputId": "36f9026c-e027-4aac-cdf4-26e8ce7c46e8"
},
"outputs": [],
"source": [
"%cd /content/Urdu-ASR"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "2MMXcWFFgCXU",
"outputId": "37926a80-2de4-4c17-b14a-994c2fdca267"
},
"outputs": [],
"source": [
"from datasets import load_dataset, load_metric, Audio\n",
"\n",
"common_voice_train = load_dataset(\"Data\", \"ur\", delimiter=\"\\t\", split=\"train+validation\")\n",
"common_voice_test = load_dataset(\"Data\", \"ur\",delimiter=\"\\t\" ,split=\"test\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ri5y5N_HMANq"
},
"source": [
"Many ASR datasets only provide the target text, `'sentence'` for each audio array `'audio'` and file `'path'`. Common Voice actually provides much more information about each audio file, such as the `'accent'`, etc. Keeping the notebook as general as possible, we only consider the transcribed text for fine-tuning.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kbyq6lDgQc2a"
},
"outputs": [],
"source": [
"common_voice_train = common_voice_train.remove_columns([\"accents\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"segment\", \"up_votes\"])\n",
"common_voice_test = common_voice_test.remove_columns([\"accents\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"segment\", \"up_votes\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Go9Hq4e4NDT9"
},
"source": [
"Let's write a short function to display some random samples of the dataset and run it a couple of times to get a feeling for the transcriptions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QL4nSK5yR-Qh"
},
"outputs": [],
"source": [
"def cleaning(text):\n",
" if not isinstance(text, str):\n",
" return None\n",
"\n",
" return normalizer({\"sentence\": text}, return_dict=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "72737oog2F6U"
},
"outputs": [],
"source": [
"from datasets import ClassLabel\n",
"import random\n",
"import pandas as pd\n",
"from IPython.display import display, HTML\n",
"\n",
"def show_random_elements(dataset, num_examples=10):\n",
" assert num_examples <= len(dataset), \"Can't pick more elements than there are in the dataset.\"\n",
" picks = []\n",
" for _ in range(num_examples):\n",
" pick = random.randint(0, len(dataset)-1)\n",
" while pick in picks:\n",
" pick = random.randint(0, len(dataset)-1)\n",
" picks.append(pick)\n",
" \n",
" df = pd.DataFrame(dataset[picks])\n",
" display(HTML(df.to_html()))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 363
},
"id": "K_JUmf3G3b9S",
"outputId": "e6ecb9f8-241b-451e-ae6d-14d8dbbc27cd"
},
"outputs": [],
"source": [
"show_random_elements(common_voice_train, num_examples=10)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fowcOllGNNju"
},
"source": [
"Alright! The transcriptions look fairly clean. Having translated the transcribed sentences, it seems that the language corresponds more to written-out text than noisy dialogue. This makes sense considering that [Common Voice](https://huggingface.co/datasets/common_voice) is a crowd-sourced read speech corpus."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vq7OR50LN49m"
},
"source": [
"We can see that the transcriptions contain some special characters, such as `,.?!;:`. Without a language model, it is much harder to classify speech chunks to such special characters because they don't really correspond to a characteristic sound unit. *E.g.*, the letter `\"s\"` has a more or less clear sound, whereas the special character `\".\"` does not.\n",
"Also in order to understand the meaning of a speech signal, it is usually not necessary to include special characters in the transcription.\n",
"\n",
"Let's simply remove all characters that don't contribute to the meaning of a word and cannot really be represented by an acoustic sound and normalize the text."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "svKzVJ_hQGK6"
},
"outputs": [],
"source": [
"import re\n",
"import unicodedata\n",
"# chars_to_remove_regex = \"\"\"[\\!\\Ψ›\\،\\Ω«\\؟\\Ϋ”\\Ωͺ\\\"\\'\\:\\-\\β€˜\\’]\"\"\"\n",
"\n",
"def normalize_text(batch):\n",
" \"\"\"DO ADAPT FOR YOUR USE CASE. this function normalizes the target text.\"\"\"\n",
"\n",
" chars_to_ignore_regex = \"\"\"[\\!\\Ψ›\\،\\Ω«\\؟\\Ϋ”\\Ωͺ\\\"\\'\\:\\-\\β€˜\\’]\"\"\" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training\n",
" batch[\"sentence\"] = re.sub(chars_to_ignore_regex, \"\", batch[\"sentence\"].lower())\n",
" batch[\"sentence\"] = unicodedata.normalize(\"NFKC\", batch[\"sentence\"])\n",
"\n",
" # In addition, we can normalize the target text, e.g. removing new lines characters etc...\n",
" # note that order is important here!\n",
" # token_sequences_to_ignore = [\"\\n\\n\", \"\\n\", \" \", \" \"]\n",
"\n",
" # for t in token_sequences_to_ignore:\n",
" # batch[\"sentence\"] = \" \".join(batch[\"sentence\"].split(t))\n",
"\n",
" return batch"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XIHocAuTQbBR"
},
"outputs": [],
"source": [
"# common_voice_train = common_voice_train.map(cleaning)\n",
"# common_voice_test = common_voice_test.map(cleaning)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "6dJq58N4SZ5f",
"outputId": "e4e17870-62aa-46f8-eb2a-222164fd6032"
},
"outputs": [],
"source": [
"common_voice_train = common_voice_train.map(normalize_text)\n",
"common_voice_test = common_voice_test.map(normalize_text)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FwlkCjSHZ6T5"
},
"outputs": [],
"source": [
"def path_adjust(batch):\n",
" batch[\"path\"] = \"Data/ur/clips/\"+str(batch[\"path\"])\n",
" return batch"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "rWlDGlQwaWC-",
"outputId": "90ecf72c-4bf4-476e-d749-ef2fa3c98ee0"
},
"outputs": [],
"source": [
"common_voice_train = common_voice_train.map(path_adjust)\n",
"common_voice_test = common_voice_test.map(path_adjust)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TxnVS9gIhIma"
},
"source": [
"Let's look at the processed text labels again."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 363
},
"id": "RBDRAAYxRE6n",
"outputId": "51d58128-c199-48d9-d201-b9d2500a9053"
},
"outputs": [],
"source": [
"show_random_elements(common_voice_train.remove_columns([\"path\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3ORHDb2Th2TW"
},
"source": [
"In CTC, it is common to classify speech chunks into letters, so we will do the same here. \n",
"Let's extract all distinct letters of the training and test data and build our vocabulary from this set of letters.\n",
"\n",
"We write a mapping function that concatenates all transcriptions into one long transcription and then transforms the string into a set of chars. \n",
"It is important to pass the argument `batched=True` to the `map(...)` function so that the mapping function has access to all transcriptions at once."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LwCshNbbeRZR"
},
"outputs": [],
"source": [
"def extract_all_chars(batch):\n",
" all_text = \" \".join(batch[\"sentence\"])\n",
" vocab = list(set(all_text))\n",
" return {\"vocab\": [vocab], \"all_text\": [all_text]}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 81,
"referenced_widgets": [
"f36ef2953a78471f83668cc5b2dd3939",
"ddead8fbf3c049d9ba2f9230d3679dcd",
"b7b3f286421e4dfc9c31f6773f41a476",
"44ba7b2c76c34d3ca9a18b55cc22e1d0",
"972c7d2625c941aebcb703a05f36707d",
"fc082dad8009470aa0941f04b95a3dcc",
"184cd1a0e9ae44c1a2800cb34cf21f6e",
"e954f23548624e6dabd8416652033d82",
"e465fc21596a4e8ca0a88785135342f2",
"818ee624f78949d89d9a5db63c5d6d57",
"0802e170d72e4ff999697bf8ffd2c597",
"68175a4447a749a8a795355c8d1760f5",
"74a4b915a4c14c9f88c6c6915fef43aa",
"d3ee69375f624322945585683abd15d0",
"8a4f576b565940f48ee0141337eea9ad",
"c10ec5576e4540e2b3a80687c6a35203",
"cadb48a2a4f140bab83864f9a8bdc101",
"da985e2f1e604db69cffa3029b8ef3fa",
"957c2385c4d9492889dd1e563059a2eb",
"bd9423d7fd79440cba90b829e9f83f37",
"ed41e4dfba004526926e7f902b9bd4be",
"b720ea4e8f574bf9963d7a587fddcb1e"
]
},
"id": "_m6uUjjcfbjH",
"outputId": "09f290ad-ef91-425a-f16a-5f265ee679d6"
},
"outputs": [],
"source": [
"vocab_train = common_voice_train.map(extract_all_chars, batched=True, batch_size=-1, keep_in_memory=True, remove_columns=common_voice_train.column_names)\n",
"vocab_test = common_voice_test.map(extract_all_chars, batched=True, batch_size=-1, keep_in_memory=True, remove_columns=common_voice_test.column_names)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7oVgE8RZSJNP"
},
"source": [
"Now, we create the union of all distinct letters in the training dataset and test dataset and convert the resulting list into an enumerated dictionary."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aQfneNsmlJI0"
},
"outputs": [],
"source": [
"vocab_list = list(set(vocab_train[\"vocab\"][0]) | set(vocab_test[\"vocab\"][0]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "_0kRndSvqaKk",
"outputId": "e2e3d448-9e8e-4de8-8c9a-f5b8f59004cb"
},
"outputs": [],
"source": [
"vocab_dict = {v: k for k, v in enumerate(sorted(vocab_list))}\n",
"vocab_dict"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "npbIbBoLgaFX"
},
"outputs": [],
"source": [
"vocab_dict[\"|\"] = vocab_dict[\" \"]\n",
"del vocab_dict[\" \"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_9yCWg4Sd0cb"
},
"source": [
"Finally, we also add a padding token that corresponds to CTC's \"*blank token*\". The \"blank token\" is a core component of the CTC algorithm. For more information, please take a look at the \"Alignment\" section [here](https://distill.pub/2017/ctc/)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "znF0bNunsjbl",
"outputId": "6b49557d-206e-4080-b82f-260391fa5be0"
},
"outputs": [],
"source": [
"vocab_dict[\"<unk>\"] = len(vocab_dict)\n",
"vocab_dict[\"<pad>\"] = len(vocab_dict)\n",
"vocab_dict[\"<s>\"] = len(vocab_dict)\n",
"vocab_dict[\"</s>\"] = len(vocab_dict)\n",
"len(vocab_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SFPGfet8U5sL"
},
"source": [
"Cool, now our vocabulary is complete and consists of 39 tokens, which means that the linear layer that we will add on top of the pretrained XLS-R checkpoint will have an output dimension of 39."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1CujRgBNVRaD"
},
"source": [
"Let's now save the vocabulary as a json file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ehyUoh9vk191"
},
"outputs": [],
"source": [
"import json\n",
"with open('vocab.json', 'w') as vocab_file:\n",
" json.dump(vocab_dict, vocab_file)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SHJDaKlIVVim"
},
"source": [
"In a final step, we use the json file to load the vocabulary into an instance of the `Wav2Vec2CTCTokenizer` class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xriFGEWQkO4M"
},
"outputs": [],
"source": [
"from transformers import Wav2Vec2CTCTokenizer\n",
"\n",
"tokenizer = Wav2Vec2CTCTokenizer(\"./vocab.json\", unk_token=\"<unk>\", pad_token=\"<pad>\", word_delimiter_token=\"|\", bos_token = \"<s>\", eos_token = \"</s>\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SwQM8lH_GGuP"
},
"source": [
"Great, you can see the just created repository under `https://huggingface.co/<your-username>/wav2vec2-large-xls-r-300m-tr-colab`"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mYcIiR2FQ96i"
},
"source": [
"### Create `Wav2Vec2FeatureExtractor`"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Y6mDEyW719rx"
},
"source": [
"Speech is a continuous signal and to be treated by computers, it first has to be discretized, which is usually called **sampling**. The sampling rate hereby plays an important role in that it defines how many data points of the speech signal are measured per second. Therefore, sampling with a higher sampling rate results in a better approximation of the *real* speech signal but also necessitates more values per second.\n",
"\n",
"A pretrained checkpoint expects its input data to have been sampled more or less from the same distribution as the data it was trained on. The same speech signals sampled at two different rates have a very different distribution, *e.g.*, doubling the sampling rate results in data points being twice as long. Thus, \n",
"before fine-tuning a pretrained checkpoint of an ASR model, it is crucial to verify that the sampling rate of the data that was used to pretrain the model matches the sampling rate of the dataset used to fine-tune the model.\n",
"\n",
"XLS-R was pretrained on audio data of [Babel](http://www.reading.ac.uk/AcaDepts/ll/speechlab/babel/r), \n",
"[Multilingual LibriSpeech (MLS)](https://huggingface.co/datasets/multilingual_librispeech), [Common Voice](https://huggingface.co/datasets/common_voice), [VoxPopuli](https://arxiv.org/abs/2101.00390), and [VoxLingua107](https://arxiv.org/abs/2011.12998) at a sampling rate of 16kHz. Common Voice, in its original form, has a sampling rate of 48kHz, thus we will have to downsample the fine-tuning data to 16kHz in the following.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KuUbPW7oV-B5"
},
"source": [
"A `Wav2Vec2FeatureExtractor` object requires the following parameters to be instantiated:\n",
"\n",
"- `feature_size`: Speech models take a sequence of feature vectors as an input. While the length of this sequence obviously varies, the feature size should not. In the case of Wav2Vec2, the feature size is 1 because the model was trained on the raw speech signal ${}^2$.\n",
"- `sampling_rate`: The sampling rate at which the model is trained on.\n",
"- `padding_value`: For batched inference, shorter inputs need to be padded with a specific value\n",
"- `do_normalize`: Whether the input should be *zero-mean-unit-variance* normalized or not. Usually, speech models perform better when normalizing the input\n",
"- `return_attention_mask`: Whether the model should make use of an `attention_mask` for batched inference. In general, XLS-R models checkpoints should **always** use the `attention_mask`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kAR0-2KLkopp"
},
"outputs": [],
"source": [
"from transformers import Wav2Vec2FeatureExtractor\n",
"\n",
"feature_extractor = Wav2Vec2FeatureExtractor(feature_size=1, sampling_rate=16000, padding_value=0.0, do_normalize=True, return_attention_mask=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qUETetgqYC3W"
},
"source": [
"Great, XLS-R's feature extraction pipeline is thereby fully defined!\n",
"\n",
"For improved user-friendliness, the feature extractor and tokenizer are *wrapped* into a single `Wav2Vec2Processor` class so that one only needs a `model` and `processor` object."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KYZtoW-tlZgl"
},
"outputs": [],
"source": [
"from transformers import Wav2Vec2Processor,AutoProcessor, AutoModelForCTC\n",
"\n",
"processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DrKnYuvDIoOO"
},
"source": [
"Next, we can prepare the dataset."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YFmShnl7RE35"
},
"source": [
"### Preprocess Data\n",
"\n",
"So far, we have not looked at the actual values of the speech signal but just the transcription. In addition to `sentence`, our datasets include two more column names `path` and `audio`. `path` states the absolute path of the audio file. Let's take a look.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "T6ndIjHGFp0W"
},
"source": [
"XLS-R expects the input in the format of a 1-dimensional array of 16 kHz. This means that the audio file has to be loaded and resampled.\n",
"\n",
" Thankfully, `datasets` does this automatically by calling the other column `audio`. Let try it out. "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WUUTgI1bGHW-"
},
"source": [
"Great, we can see that the audio file has automatically been loaded. This is thanks to the new [`\"Audio\"` feature](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=audio#datasets.Audio) introduced in `datasets == 4.13.3`, which loads and resamples audio files on-the-fly upon calling.\n",
"\n",
"In the example above we can see that the audio data is loaded with a sampling rate of 48kHz whereas 16kHz are expected by the model. We can set the audio feature to the correct sampling rate by making use of [`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rrv65aj7G95i"
},
"outputs": [],
"source": [
"common_voice_train = common_voice_train.cast_column(\"path\", Audio(sampling_rate=16_000))\n",
"common_voice_test = common_voice_test.cast_column(\"path\", Audio(sampling_rate=16_000))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PcnO4x-NGBEi"
},
"source": [
"Let's take a look at `\"audio\"` again."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "aKtkc1o_HWHC",
"outputId": "41f7071a-7a05-493d-cf3e-96708c4fec59"
},
"outputs": [],
"source": [
"common_voice_train[0][\"path\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SOckzFd4Mbzq"
},
"source": [
"This seemed to have worked! Let's listen to a couple of audio files to better understand the dataset and verify that the audio was correctly loaded. \n",
"\n",
"**Note**: *You can click the following cell a couple of times to listen to different speech samples.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 93
},
"id": "dueM6U7Ev0OA",
"outputId": "9d0fce47-1d84-4f67-d190-9ec58f0d7c0b"
},
"outputs": [],
"source": [
"import IPython.display as ipd\n",
"import numpy as np\n",
"import random\n",
"\n",
"rand_int = random.randint(0, len(common_voice_train)-1)\n",
"\n",
"print(common_voice_train[rand_int][\"sentence\"])\n",
"ipd.Audio(data=common_voice_train[rand_int][\"path\"][\"array\"], autoplay=True, rate=16000)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gY8m3vARHYTa"
},
"source": [
"It seems like the data is now correctly loaded and resampled. "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1MaL9J2dNVtG"
},
"source": [
"It can be heard, that the speakers change along with their speaking rate, accent, and background environment, etc. Overall, the recordings sound acceptably clear though, which is to be expected from a crowd-sourced read speech corpus.\n",
"\n",
"Let's do a final check that the data is correctly prepared, by printing the shape of the speech input, its transcription, and the corresponding sampling rate.\n",
"\n",
"**Note**: *You can click the following cell a couple of times to verify multiple samples.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1Po2g7YPuRTx",
"outputId": "ee7c2161-39c7-4782-ed01-f799ff8800ef"
},
"outputs": [],
"source": [
"rand_int = random.randint(0, len(common_voice_train)-1)\n",
"\n",
"print(\"Target text:\", common_voice_train[rand_int][\"sentence\"])\n",
"print(\"Input array shape:\", common_voice_train[rand_int][\"path\"][\"array\"].shape)\n",
"print(\"Sampling rate:\", common_voice_train[rand_int][\"path\"][\"sampling_rate\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "M9teZcSwOBJ4"
},
"source": [
"Good! Everything looks fine - the data is a 1-dimensional array, the sampling rate always corresponds to 16kHz, and the target text is normalized."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "k3Pbn5WvOYZF"
},
"source": [
"Finally, we can leverage `Wav2Vec2Processor` to process the data to the format expected by `Wav2Vec2ForCTC` for training. To do so let's make use of Dataset's [`map(...)`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=map#datasets.DatasetDict.map) function.\n",
"\n",
"First, we load and resample the audio data, simply by calling `batch[\"audio\"]`.\n",
"Second, we extract the `input_values` from the loaded audio file. In our case, the `Wav2Vec2Processor` only normalizes the data. For other speech models, however, this step can include more complex feature extraction, such as [Log-Mel feature extraction](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum). \n",
"Third, we encode the transcriptions to label ids.\n",
"\n",
"**Note**: This mapping function is a good example of how the `Wav2Vec2Processor` class should be used. In \"normal\" context, calling `processor(...)` is redirected to `Wav2Vec2FeatureExtractor`'s call method. When wrapping the processor into the `as_target_processor` context, however, the same method is redirected to `Wav2Vec2CTCTokenizer`'s call method.\n",
"For more information please check the [docs](https://huggingface.co/transformers/master/model_doc/wav2vec2.html#transformers.Wav2Vec2Processor.__call__)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eJY7I0XAwe9p"
},
"outputs": [],
"source": [
"def prepare_dataset(batch):\n",
" audio = batch[\"path\"]\n",
"\n",
" # batched output is \"un-batched\"\n",
" batch[\"input_values\"] = processor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_values[0]\n",
" batch[\"input_length\"] = len(batch[\"input_values\"])\n",
" \n",
" with processor.as_target_processor():\n",
" batch[\"labels\"] = processor(batch[\"sentence\"]).input_ids\n",
" return batch"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "q6Pg_WR3OGAP"
},
"source": [
"Let's apply the data preparation function to all examples."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 81,
"referenced_widgets": [
"1149c8d876b8434db67f23f8d0cf4e54",
"acdbfc9bae2f40689944317666bd33ba",
"80cbdf747dfe45939c266bf31e7042d8",
"a19d35352882473e88e7cd9900f04b18",
"5bd22dfd12084f1381137dc9bf0d26eb",
"5411fe5b9c994caeacb21abd6bd82374",
"c80c0d69b86f470d8f5e9922d696404d",
"b58e9a584f734e718a857cdbdb671cba",
"e21e3d3ba70147b09dd025986c88264d",
"e11b5cd77825455587255870b5bfbd52",
"7888cf9b3dd04c6e86be0cc691915063",
"7d780bbaf63c4398bcb4cdd7b7a420f8",
"005bfde85ca84ac2baeecca8b29e8128",
"be3bfc1639014762af07c228030d2f49",
"2e52b247ac7140e1b009141a20e0e4e0",
"9be9f0c4290a446c883bfce80da460fe",
"3bd607444dc6462089423e0044c49e16",
"8c4a4c3b2c4441b1b945d249b2c3d765",
"5379091c1a344d9382b4fd50e675b11e",
"6b75b166f7fc4a71b710f6be726a955b",
"9d951e2829464ae3bcbd596352e3af2d",
"e6ae489f1dcf48eb9f154dfc4a6e38a7"
]
},
"id": "-np9xYK-wl8q",
"outputId": "1b0dfd2f-1eb3-4c45-c0cf-34bcf6976093"
},
"outputs": [],
"source": [
"common_voice_train = common_voice_train.map(prepare_dataset, remove_columns=common_voice_train.column_names)\n",
"common_voice_test = common_voice_test.map(prepare_dataset, remove_columns=common_voice_test.column_names)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nKcEWHvKI1by"
},
"source": [
"**Note**: Currently `datasets` make use of [`torchaudio`](https://pytorch.org/audio/stable/index.html) and [`librosa`](https://librosa.org/doc/latest/index.html) for audio loading and resampling. If you wish to implement your own costumized data loading/sampling, feel free to just make use of the `\"path\"` column instead and disregard the `\"audio\"` column."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "24CxHd5ewI4T"
},
"source": [
"Long input sequences require a lot of memory. XLS-R is based on `self-attention` the memory requirement scales quadratically with the input length for long input sequences (*cf.* with [this](https://www.reddit.com/r/MachineLearning/comments/genjvb/d_why_is_the_maximum_input_sequence_length_of/) reddit post). In case this demo crashes with an \"Out-of-memory\" error for you, you might want to uncomment the following lines to filter all sequences that are longer than 5 seconds for training."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tdHfbUJ_09iA"
},
"outputs": [],
"source": [
"#max_input_length_in_sec = 5.0\n",
"#common_voice_train = common_voice_train.filter(lambda x: x < max_input_length_in_sec * processor.feature_extractor.sampling_rate, input_columns=[\"input_length\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1ZWDCCKqwcfS"
},
"source": [
"Awesome, now we are ready to start training!"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gYlQkKVoRUos"
},
"source": [
"## Training\n",
"\n",
"The data is processed so that we are ready to start setting up the training pipeline. We will make use of πŸ€—'s [Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer) for which we essentially need to do the following:\n",
"\n",
"- Define a data collator. In contrast to most NLP models, XLS-R has a much larger input length than output length. *E.g.*, a sample of input length 50000 has an output length of no more than 100. Given the large input sizes, it is much more efficient to pad the training batches dynamically meaning that all training samples should only be padded to the longest sample in their batch and not the overall longest sample. Therefore, fine-tuning XLS-R requires a special padding data collator, which we will define below\n",
"\n",
"- Evaluation metric. During training, the model should be evaluated on the word error rate. We should define a `compute_metrics` function accordingly\n",
"\n",
"- Load a pretrained checkpoint. We need to load a pretrained checkpoint and configure it correctly for training.\n",
"\n",
"- Define the training configuration.\n",
"\n",
"After having fine-tuned the model, we will correctly evaluate it on the test data and verify that it has indeed learned to correctly transcribe speech."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Slk403unUS91"
},
"source": [
"### Set-up Trainer\n",
"\n",
"Let's start by defining the data collator. The code for the data collator was copied from [this example](https://github.com/huggingface/transformers/blob/7e61d56a45c19284cfda0cee8995fb552f6b1f4e/examples/pytorch/speech-recognition/run_speech_recognition_ctc.py#L219).\n",
"\n",
"Without going into too many details, in contrast to the common data collators, this data collator treats the `input_values` and `labels` differently and thus applies to separate padding functions on them (again making use of XLS-R processor's context manager). This is necessary because in speech input and output are of different modalities meaning that they should not be treated by the same padding function.\n",
"Analogous to the common data collators, the padding tokens in the labels with `-100` so that those tokens are **not** taken into account when computing the loss."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tborvC9hx88e"
},
"outputs": [],
"source": [
"import torch\n",
"\n",
"from dataclasses import dataclass, field\n",
"from typing import Any, Dict, List, Optional, Union\n",
"\n",
"@dataclass\n",
"class DataCollatorCTCWithPadding:\n",
" \"\"\"\n",
" Data collator that will dynamically pad the inputs received.\n",
" Args:\n",
" processor (:class:`~transformers.Wav2Vec2Processor`)\n",
" The processor used for proccessing the data.\n",
" padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):\n",
" Select a strategy to pad the returned sequences (according to the model's padding side and padding index)\n",
" among:\n",
" * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n",
" sequence if provided).\n",
" * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the\n",
" maximum acceptable input length for the model if that argument is not provided.\n",
" * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of\n",
" different lengths).\n",
" \"\"\"\n",
"\n",
" processor: Wav2Vec2Processor\n",
" padding: Union[bool, str] = True\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 lenghts and need\n",
" # different padding methods\n",
" input_features = [{\"input_values\": feature[\"input_values\"]} for feature in features]\n",
" label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n",
"\n",
" batch = self.processor.pad(\n",
" input_features,\n",
" padding=self.padding,\n",
" return_tensors=\"pt\",\n",
" )\n",
" with self.processor.as_target_processor():\n",
" labels_batch = self.processor.pad(\n",
" label_features,\n",
" padding=self.padding,\n",
" return_tensors=\"pt\",\n",
" )\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",
" batch[\"labels\"] = labels\n",
"\n",
" return batch"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "lbQf5GuZyQ4_"
},
"outputs": [],
"source": [
"data_collator = DataCollatorCTCWithPadding(processor=processor, padding=True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xO-Zdj-5cxXp"
},
"source": [
"Next, the evaluation metric is defined. As mentioned earlier, the \n",
"predominant metric in ASR is the word error rate (WER), hence we will use it in this notebook as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9Xsux2gmyXso"
},
"outputs": [],
"source": [
"wer_metric = load_metric(\"wer\")\n",
"cer_metric = load_metric(\"cer\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "E1qZU5p-deqB"
},
"source": [
"The model will return a sequence of logit vectors:\n",
"$\\mathbf{y}_1, \\ldots, \\mathbf{y}_m$ with $\\mathbf{y}_1 = f_{\\theta}(x_1, \\ldots, x_n)[0]$ and $n >> m$.\n",
"\n",
"A logit vector $\\mathbf{y}_1$ contains the log-odds for each word in the vocabulary we defined earlier, thus $\\text{len}(\\mathbf{y}_i) =$ `config.vocab_size`. We are interested in the most likely prediction of the model and thus take the `argmax(...)` of the logits. Also, we transform the encoded labels back to the original string by replacing `-100` with the `pad_token_id` and decoding the ids while making sure that consecutive tokens are **not** grouped to the same token in CTC style ${}^1$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1XZ-kjweyTy_"
},
"outputs": [],
"source": [
"def compute_metrics(pred):\n",
" pred_logits = pred.predictions\n",
" pred_ids = np.argmax(pred_logits, axis=-1)\n",
"\n",
" pred.label_ids[pred.label_ids == -100] = processor.tokenizer.pad_token_id\n",
"\n",
" pred_str = processor.batch_decode(pred_ids)\n",
" # we do not want to group tokens when computing the metrics\n",
" label_str = processor.batch_decode(pred.label_ids, group_tokens=False)\n",
"\n",
" wer = wer_metric.compute(predictions=pred_str, references=label_str)\n",
" cer = cer_metric.compute(predictions=pred_str, references=label_str)\n",
" return {\"wer\" : wer, \"cer\" : cer}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Xmgrx4bRwLIH"
},
"source": [
"Now, we can load the pretrained checkpoint of [Wav2Vec2-XLS-R-300M](https://huggingface.co/facebook/wav2vec2-xls-r-300m). The tokenizer's `pad_token_id` must be to define the model's `pad_token_id` or in the case of `Wav2Vec2ForCTC` also CTC's *blank token* ${}^2$. To save GPU memory, we enable PyTorch's [gradient checkpointing](https://pytorch.org/docs/stable/checkpoint.html) and also set the loss reduction to \"*mean*\".\n",
"\n",
"Because the dataset is quite small (~6h of training data) and because Common Voice is quite noisy, fine-tuning Facebook's [wav2vec2-xls-r-300m checkpoint](https://huggingface.co/facebook/wav2vec2-xls-r-300m) seems to require some hyper-parameter tuning. Therefore, I had to play around a bit with different values for dropout, [SpecAugment](https://arxiv.org/abs/1904.08779)'s masking dropout rate, layer dropout, and the learning rate until training seemed to be stable enough. \n",
"\n",
"**Note**: When using this notebook to train XLS-R on another language of Common Voice those hyper-parameter settings might not work very well. Feel free to adapt those depending on your use case. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "e7cqAWIayn6w",
"outputId": "be39113a-c3aa-44b9-d154-90c8b6439717"
},
"outputs": [],
"source": [
"from transformers import Wav2Vec2ForCTC\n",
"\n",
"model = Wav2Vec2ForCTC.from_pretrained(\n",
" \"facebook/wav2vec2-xls-r-300m\", \n",
" attention_dropout=0.1,\n",
" layerdrop=0.0,\n",
" feat_proj_dropout=0.0,\n",
" mask_time_prob=0.75,\n",
" mask_time_length=10,\n",
" mask_feature_prob=0.25,\n",
" mask_feature_length=64,\n",
" ctc_loss_reduction=\"mean\", \n",
" pad_token_id=processor.tokenizer.pad_token_id,\n",
" vocab_size=len(processor.tokenizer),\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1DwR3XLSzGDD"
},
"source": [
"The first component of XLS-R consists of a stack of CNN layers that are used to extract acoustically meaningful - but contextually independent - features from the raw speech signal. This part of the model has already been sufficiently trained during pretraining and as stated in the [paper](https://arxiv.org/pdf/2006.13979.pdf) does not need to be fine-tuned anymore. \n",
"Thus, we can set the `requires_grad` to `False` for all parameters of the *feature extraction* part."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "oGI8zObtZ3V0",
"outputId": "5972978a-f8c8-4ff8-c6f2-41113ef3c56f"
},
"outputs": [],
"source": [
"model.freeze_feature_extractor()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lD4aGhQM0K-D"
},
"source": [
"In a final step, we define all parameters related to training. \n",
"To give more explanation on some of the parameters:\n",
"- `group_by_length` makes training more efficient by grouping training samples of similar input length into one batch. This can significantly speed up training time by heavily reducing the overall number of useless padding tokens that are passed through the model\n",
"- `learning_rate` and `weight_decay` were heuristically tuned until fine-tuning has become stable. Note that those parameters strongly depend on the Common Voice dataset and might be suboptimal for other speech datasets.\n",
"\n",
"For more explanations on other parameters, one can take a look at the [docs](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer#trainingarguments).\n",
"\n",
"During training, a checkpoint will be uploaded asynchronously to the hub every 400 training steps. It allows you to also play around with the demo widget even while your model is still training.\n",
"\n",
"**Note**: If one does not want to upload the model checkpoints to the hub, simply set `push_to_hub=False`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Xzn6034AOaUT"
},
"outputs": [],
"source": [
"import os\n",
"os.environ['MLFLOW_TRACKING_USERNAME'] = \"kingabzpro\"\n",
"os.environ['MLFLOW_TRACKING_PASSWORD'] = \"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KbeKSV7uzGPP"
},
"outputs": [],
"source": [
"from transformers import TrainingArguments\n",
"\n",
"training_args = TrainingArguments(\n",
" output_dir=\"Model\",\n",
" group_by_length=True,\n",
" per_device_train_batch_size=32,\n",
" gradient_accumulation_steps=2,\n",
" evaluation_strategy=\"steps\",\n",
" num_train_epochs=200,\n",
" gradient_checkpointing=True,\n",
" fp16=True,\n",
" save_steps=400,\n",
" eval_steps=400,\n",
" logging_steps=400,\n",
" learning_rate=1e-4,\n",
" warmup_steps=1000,\n",
" save_total_limit=2,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OsW-WZcL1ZtN"
},
"source": [
"Now, all instances can be passed to Trainer and we are ready to start training!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zp7scktZJIBd"
},
"outputs": [],
"source": [
"from transformers.integrations import TensorBoardCallback,MLflowCallback"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "rY7vBmFCPFgC",
"outputId": "b80818ca-d083-408d-a382-0b4902107815"
},
"outputs": [],
"source": [
"from transformers import Trainer\n",
"\n",
"\n",
"trainer = Trainer(\n",
" model=model,\n",
" data_collator=data_collator,\n",
" args=training_args,\n",
" compute_metrics=compute_metrics,\n",
" train_dataset=common_voice_train,\n",
" eval_dataset=common_voice_test,\n",
" tokenizer=processor.feature_extractor,\n",
" callbacks=[MLflowCallback]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Bq9tPZVg92pW",
"outputId": "0f02a82a-f9e5-4dab-8711-7d0151423d7c"
},
"outputs": [],
"source": [
"trainer.get_optimizer_cls_and_kwargs(training_args)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gUZbbfa3MWfW"
},
"outputs": [],
"source": [
"trainer.remove_callback(TensorBoardCallback)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UoXBx1JAA0DX"
},
"source": [
"\n",
"\n",
"---\n",
"\n",
"${}^1$ To allow models to become independent of the speaker rate, in CTC, consecutive tokens that are identical are simply grouped as a single token. However, the encoded labels should not be grouped when decoding since they don't correspond to the predicted tokens of the model, which is why the `group_tokens=False` parameter has to be passed. If we wouldn't pass this parameter a word like `\"hello\"` would incorrectly be encoded, and decoded as `\"helo\"`.\n",
"\n",
"${}^2$ The blank token allows the model to predict a word, such as `\"hello\"` by forcing it to insert the blank token between the two l's. A CTC-conform prediction of `\"hello\"` of our model would be `[PAD] [PAD] \"h\" \"e\" \"e\" \"l\" \"l\" [PAD] \"l\" \"o\" \"o\" [PAD]`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rpvZHM1xReIW"
},
"source": [
"### Training"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rWlS5WsqIWPF"
},
"outputs": [],
"source": [
"import mlflow"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ionf-3KGuzXY"
},
"outputs": [],
"source": [
"# mlflow.delete_run(\"d4caf8e76ce14040b0c8ccf3f306f89d\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dBgk8Uaw1BqC"
},
"outputs": [],
"source": [
"# mlflow.set_experiment(experiment_id=0)\n",
"# with mlflow.start_run(run_id=\"2a28fb02c3ce4670997d5303f0de7118\") as run:\n",
"# mlflow.set_tag('mlflow.source.git.commit', \"d316332f0def9d679491b81b2b35aee7bbf21457\") "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ccHvQwNw1taG"
},
"outputs": [],
"source": [
"# mlflow.end_run()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 717
},
"id": "9fRr9TG5pGBl",
"outputId": "ab7bf491-44e6-4dba-c42f-af33e6b56f06"
},
"outputs": [],
"source": [
"mlflow.set_tracking_uri(\"https://dagshub.com/kingabzpro/Urdu-ASR-SOTA.mlflow\")\n",
"# mlflow.set_tag('mlflow.source.git.commit', \"d316332f0def9d679491b81b2b35aee7bbf21457\") \n",
"trainer.train()\n",
"mlflow.end_run()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a9q4mgMZplr_"
},
"source": [
"The training loss and validation WER go down nicely."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4Ya7WEy0pd13"
},
"source": [
"You can now upload the result of the training to the πŸ€— Hub, just execute this instruction:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "m6w5pWkLT5qn"
},
"outputs": [],
"source": [
"import dagshub\n",
"\n",
"with dagshub.dagshub_logger() as logger:\n",
" logger.log_hyperparams(model_class=\"wav2vec2-xls-r-300m\")\n",
" logger.log_hyperparams(training_args.to_dict())\n",
" logger.log_metrics(trainer.evaluate())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ElIer3iRbzEh"
},
"outputs": [],
"source": [
"!dvc remote add origin https://dagshub.com/kingabzpro/Urdu-ASR-SOTA.dvc\n",
"!dvc remote modify origin --local auth basic\n",
"!dvc remote modify origin --local user kingabzpro\n",
"!dvc remote modify origin --local password <pass>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ArG1Thf6NBWm"
},
"outputs": [],
"source": [
"!fds commit -m \"second experiment\"\n",
"!fds push origin"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
"machine_shape": "hm",
"name": "Urdu_Fine_Tune_XLS_R_on_Common_Voice (3).ipynb",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"005bfde85ca84ac2baeecca8b29e8128": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_3bd607444dc6462089423e0044c49e16",
"placeholder": "​",
"style": "IPY_MODEL_8c4a4c3b2c4441b1b945d249b2c3d765",
"value": ""
}
},
"0802e170d72e4ff999697bf8ffd2c597": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "DescriptionStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"1149c8d876b8434db67f23f8d0cf4e54": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HBoxModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_acdbfc9bae2f40689944317666bd33ba",
"IPY_MODEL_80cbdf747dfe45939c266bf31e7042d8",
"IPY_MODEL_a19d35352882473e88e7cd9900f04b18"
],
"layout": "IPY_MODEL_5bd22dfd12084f1381137dc9bf0d26eb"
}
},
"184cd1a0e9ae44c1a2800cb34cf21f6e": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "DescriptionStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"2e52b247ac7140e1b009141a20e0e4e0": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_9d951e2829464ae3bcbd596352e3af2d",
"placeholder": "​",
"style": "IPY_MODEL_e6ae489f1dcf48eb9f154dfc4a6e38a7",
"value": " 341/? [00:02&lt;00:00, 113.05ex/s]"
}
},
"3bd607444dc6462089423e0044c49e16": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"44ba7b2c76c34d3ca9a18b55cc22e1d0": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_818ee624f78949d89d9a5db63c5d6d57",
"placeholder": "​",
"style": "IPY_MODEL_0802e170d72e4ff999697bf8ffd2c597",
"value": " 1/1 [00:00&lt;00:00, 11.10ba/s]"
}
},
"5379091c1a344d9382b4fd50e675b11e": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": "20px"
}
},
"5411fe5b9c994caeacb21abd6bd82374": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"5bd22dfd12084f1381137dc9bf0d26eb": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"68175a4447a749a8a795355c8d1760f5": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HBoxModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_74a4b915a4c14c9f88c6c6915fef43aa",
"IPY_MODEL_d3ee69375f624322945585683abd15d0",
"IPY_MODEL_8a4f576b565940f48ee0141337eea9ad"
],
"layout": "IPY_MODEL_c10ec5576e4540e2b3a80687c6a35203"
}
},
"6b75b166f7fc4a71b710f6be726a955b": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name"<