{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip3 install pandas\n", "!pip3 install numpy" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ba-anandhus/Documents/fine tuning/fine/lib/python3.8/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "import pandas as pd\n", "import librosa\n", "from scipy.io import wavfile\n", "from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer, Wav2Vec2CTCTokenizer\n", "import numpy\n", "import torch\n", "import processor\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "The tokenizer class you load from this checkpoint is not the same type as the class this function is called from. It may result in unexpected tokenization. \n", "The tokenizer class you load from this checkpoint is 'Wav2Vec2CTCTokenizer'. \n", "The class this function is called from is 'Wav2Vec2Tokenizer'.\n", "/home/ba-anandhus/Documents/fine tuning/fine/lib/python3.8/site-packages/transformers/models/wav2vec2/tokenization_wav2vec2.py:421: FutureWarning: The class `Wav2Vec2Tokenizer` is deprecated and will be removed in version 5 of Transformers. Please use `Wav2Vec2Processor` or `Wav2Vec2CTCTokenizer` instead.\n", " warnings.warn(\n" ] } ], "source": [ "# tokenizer = Wav2Vec2CTCTokenizer(\"./vocab.json\", unk_token=\"[UNK]\", pad_token=\"[PAD]\", word_delimiter_token=\"|\")\n", "tokenizer = Wav2Vec2Tokenizer.from_pretrained(\"facebook/wav2vec2-base-960h\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "#reading the custom dataset\n", "data = pd.read_csv('Dataset_voice_to_text.csv')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Number Filename Text\n", "0 1 audiofile1.wav good morning everyone\n", "1 2 audiofile2.wav it is always nice to meet you in a fresh mood\n", "2 3 audiofile3.wav this is the custom dataset which is used to tr...\n", "3 4 audiofile4.wav this consist of test train and validation data...\n", "4 5 audiofile5.wav train data is used to train the deep learning ...\n" ] } ], "source": [ "print(data.head())" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\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", "
FilenameText
0audiofile1.wavgood morning everyone
1audiofile2.wavit is always nice to meet you in a fresh mood
2audiofile3.wavthis is the custom dataset which is used to tr...
3audiofile4.wavthis consist of test train and validation data...
4audiofile5.wavtrain data is used to train the deep learning ...
\n", "
" ], "text/plain": [ " Filename Text\n", "0 audiofile1.wav good morning everyone\n", "1 audiofile2.wav it is always nice to meet you in a fresh mood\n", "2 audiofile3.wav this is the custom dataset which is used to tr...\n", "3 audiofile4.wav this consist of test train and validation data...\n", "4 audiofile5.wav train data is used to train the deep learning ..." ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data = data.drop('Number',axis=1)\n", "data.head()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/home/ba-anandhus/Documents/fine tuning/mono/audiofile1.wav'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "file_path = \"/home/ba-anandhus/Documents/fine tuning/mono/\"\n", "filenames = data[\"Filename\"]\n", "file_path+filenames[0]" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([[-0.0003, -0.0003, -0.0003, ..., 0.0019, -0.0012, 0.0023]])\n", "[array([-0.00031036, -0.00031036, -0.00031036, ..., 0.00189681,\n", " -0.00119323, 0.00233824], dtype=float32)]\n" ] }, { "data": { "text/plain": [ "numpy.ndarray" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#getting the vectorized form of the audio\n", "file_path = \"/home/ba-anandhus/Documents/fine tuning/mono/\"\n", "filenames = data[\"Filename\"]\n", "sample_rate, audio_data = wavfile.read(\"audiofile1.wav\")\n", "audio, sampling_rate = librosa.load(\"audiofile1.wav\",sr=sample_rate)\n", "input_values = tokenizer(audio, return_tensors = 'pt')\n", "print(input_values['input_values'])\n", "input_values = input_values['input_values'].numpy()\n", "print(str(input_values))\n", "type(input_values)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "tokenizer = Wav2Vec2CTCTokenizer(\"./vocab.json\", unk_token=\"[UNK]\", pad_token=\"[PAD]\", word_delimiter_token=\"|\")\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "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=False)\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "from transformers import Wav2Vec2Processor\n", "\n", "processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Downloading: 100%|██████████| 1.80k/1.80k [00:00<00:00, 646kB/s]\n", "/home/ba-anandhus/Documents/fine tuning/fine/lib/python3.8/site-packages/transformers/configuration_utils.py:336: UserWarning: Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the `Trainer` API, pass `gradient_checkpointing=True` in your `TrainingArguments`.\n", " warnings.warn(\n", "Downloading: 100%|██████████| 363M/363M [00:33<00:00, 11.3MB/s] \n", "Some weights of the model checkpoint at facebook/wav2vec2-base were not used when initializing Wav2Vec2ForCTC: ['project_hid.weight', 'project_q.weight', 'quantizer.weight_proj.weight', 'project_hid.bias', 'quantizer.weight_proj.bias', 'project_q.bias', 'quantizer.codevectors']\n", "- This IS expected if you are initializing Wav2Vec2ForCTC from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", "- This IS NOT expected if you are initializing Wav2Vec2ForCTC from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n", "Some weights of Wav2Vec2ForCTC were not initialized from the model checkpoint at facebook/wav2vec2-base and are newly initialized: ['lm_head.weight', 'lm_head.bias']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] } ], "source": [ "#model loading\n", "model = Wav2Vec2ForCTC.from_pretrained(\n", " \"facebook/wav2vec2-base\", \n", " ctc_loss_reduction=\"mean\", \n", " pad_token_id=processor.tokenizer.pad_token_id,\n", ")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "model.freeze_feature_extractor()\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "from transformers import TrainingArguments\n", "\n", "training_args = TrainingArguments(\n", " output_dir=\".\",\n", " group_by_length=True,\n", " per_device_train_batch_size=32,\n", " evaluation_strategy=\"steps\",\n", " num_train_epochs=30,\n", " fp16=False,\n", " gradient_checkpointing=True, \n", " save_steps=500,\n", " eval_steps=500,\n", " logging_steps=500,\n", " learning_rate=1e-4,\n", " weight_decay=0.005,\n", " warmup_steps=1000,\n", " save_total_limit=2,\n", " push_to_hub=False,\n", ")\n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "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", " max_length (:obj:`int`, `optional`):\n", " Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).\n", " max_length_labels (:obj:`int`, `optional`):\n", " Maximum length of the ``labels`` returned list and optionally padding length (see above).\n", " pad_to_multiple_of (:obj:`int`, `optional`):\n", " If set will pad the sequence to a multiple of the provided value.\n", " This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=\n", " 7.5 (Volta).\n", " \"\"\"\n", "\n", " processor: Wav2Vec2Processor\n", " padding: Union[bool, str] = True\n", " max_length: Optional[int] = None\n", " max_length_labels: Optional[int] = None\n", " pad_to_multiple_of: Optional[int] = None\n", " pad_to_multiple_of_labels: Optional[int] = None\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\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", " max_length=self.max_length,\n", " pad_to_multiple_of=self.pad_to_multiple_of,\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", " max_length=self.max_length_labels,\n", " pad_to_multiple_of=self.pad_to_multiple_of_labels,\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\n" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "data_collator = DataCollatorCTCWithPadding(processor=processor, padding=True)\n" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "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", "\n", " return {\"wer\": wer}\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'timit_prepared' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[27], line 8\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mtransformers\u001b[39;00m \u001b[39mimport\u001b[39;00m Trainer\n\u001b[1;32m 3\u001b[0m trainer \u001b[39m=\u001b[39m Trainer(\n\u001b[1;32m 4\u001b[0m model\u001b[39m=\u001b[39mmodel,\n\u001b[1;32m 5\u001b[0m data_collator\u001b[39m=\u001b[39mdata_collator,\n\u001b[1;32m 6\u001b[0m args\u001b[39m=\u001b[39mtraining_args,\n\u001b[1;32m 7\u001b[0m compute_metrics\u001b[39m=\u001b[39mcompute_metrics,\n\u001b[0;32m----> 8\u001b[0m train_dataset\u001b[39m=\u001b[39mtimit_prepared[\u001b[39m\"\u001b[39m\u001b[39mtrain\u001b[39m\u001b[39m\"\u001b[39m],\n\u001b[1;32m 9\u001b[0m eval_dataset\u001b[39m=\u001b[39mtimit_prepared[\u001b[39m\"\u001b[39m\u001b[39mtest\u001b[39m\u001b[39m\"\u001b[39m],\n\u001b[1;32m 10\u001b[0m tokenizer\u001b[39m=\u001b[39mprocessor\u001b[39m.\u001b[39mfeature_extractor,\n\u001b[1;32m 11\u001b[0m )\n", "\u001b[0;31mNameError\u001b[0m: name 'timit_prepared' is not defined" ] } ], "source": [ "from transformers import Trainer\n", "\n", "trainer = Trainer(\n", " model=model,\n", " data_collator=data_collator,\n", " args=training_args,\n", " compute_metrics=compute_metrics,\n", " train_dataset=timit_prepared[\"train\"],\n", " eval_dataset=timit_prepared[\"test\"],\n", " tokenizer=processor.feature_extractor,\n", ")\n" ] } ], "metadata": { "kernelspec": { "display_name": "fine", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }