{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "Publish_NeMo_Model_On_Hugging_Face_Hub.ipynb", "provenance": [], "collapsed_sections": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "qjQ5KQIkaK2J" }, "outputs": [], "source": [ "\"\"\"\n", "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n", "\n", "Instructions for setting up Colab are as follows:\n", "1. Open a new Python 3 notebook.\n", "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n", "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n", "4. Run this cell to set up dependencies.\n", "\"\"\"\n", "# If you're using Google Colab and not running locally, run this cell.\n", "\n", "## Install dependencies\n", "!apt-get install sox libsndfile1 ffmpeg\n", "!pip install wget\n", "!pip install text-unidecode\n", "\n", "### Install NeMo\n", "BRANCH = 'r1.17.0'\n", "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]" ] }, { "cell_type": "code", "source": [ "### Install Hugging Face Hub\n", "!python -m pip install huggingface_hub\n", "!python -m pip install evaluate" ], "metadata": { "id": "J6d04-VRjC-O" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# NeMo models on Hugging Face Hub\n", "\n", "This guide will briefly show how to upload NeMo models to Hugging Face programmatically.\n", "\n", "This enables community members to share their NeMo models (any model!) with all users of NeMo!\n", "\n", "**Note**: While in this tutorial we showcase an ASR model, there is no particular restriction to any domain - all NeMo models (.nemo files) of every domain can be uploaded and shared in the same way." ], "metadata": { "id": "aS-Y5O_oGBTc" } }, { "cell_type": "markdown", "source": [ "# Login to Hugging Face\n", "\n", "Use the notebook login, and access your user access token (or create one to upload models to Hugging Face).\n", "\n", "For more information, visit the User Access Token section - https://huggingface.co/docs/hub/security-tokens" ], "metadata": { "id": "Us3UlvwCiEZi" } }, { "cell_type": "code", "source": [ "from huggingface_hub import notebook_login\n", "\n", "notebook_login()" ], "metadata": { "id": "4RTYbCLziEnb" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "!git config --global credential.helper store" ], "metadata": { "id": "dgZbTPcFiaml" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Prepare a model to upload to HF\n", "\n", "In this example, we will download a NeMo ASR model from NGC and then upload it to Hugging Face for simplicity and to showcase the method.\n", "\n", "**You can swap out this ASR model for any model that you restore via `restore_from()` and follow the same steps to upload your own models !**" ], "metadata": { "id": "s-FiNn1eiFAl" } }, { "cell_type": "code", "source": [ "import torch\n", "import torch.nn as nn\n", "\n", "from omegaconf import DictConfig, OmegaConf, open_dict" ], "metadata": { "id": "5KnVl-M0ax14" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "import nemo.collections.asr as nemo_asr # use any domain's models !\n", "import nemo.collections.nlp as nemo_nlp # use any domain's models !\n", "import nemo.collections.tts as nemo_tts # use any domain's models !" ], "metadata": { "id": "ZEDpkIinbwmm" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Model Name\n", "\n", "NeMo adheres to strict requirements when naming a model for upload to NGC / Hugging Face Hub. \n", "\n", "It is **mandatory** to share the model name across the model card, the NeMo file itself. Otherwise NeMo model from Hugging Face will fail to restore correctly." ], "metadata": { "id": "mLuQo1vnHVcP" } }, { "cell_type": "markdown", "source": [ "## Naming Convention\n", "\n", "NeMo model names can vary based on domain and purpose. While we attempt to conform to standard guidelines when naming our models, we do not expect the same level of strictness for community contributions.\n", "\n", "Here are some common guidelines we encourage (but do not enforce) users to follow : \n", "\n", "- `Task name`: Usually a short 2-3 character representation of the task that the model performs.\n", " - `stt` = Speech To Text (ASR)\n", " - `tts` = Text to Speech (TTS)\n", " - `ssl` = (Speech) Self Supervised Learning (SSL)\n", " - `nlp` = Natural Language Processing (NLP)\n", " - `nmt` = Neural Machine Translation (NMT) and many more.\n", "\n", "- `Language ID`: Usually a 2/3 digit universal language id. For multilingual models, each domain has its own rules, but some common ones are `{lang_1}{lang_2}{...}` or call them `multilingual.`\n", "\n", "- `Model Identifier`: Since models vary so drastically across domains, there is a lot of flexibility here. We try to adhere to naming conventions in literature as much as possible. For example, you can attach `model architecture` (Conformer/Citrinet), `training loss` (CTC/Transducer), and `model size` (small, large, discrete integer sizes, etc.).\n", "\n", "- `Optional: Additional Modifiers`: These are additional identifiers such as gender of speaker (TTS), dataset name (ls for Librispeech), etc. It can be set on a case-by-case basis.\n", "\n", "All these name segments are jointed by `_`.\n", "\n", "-----\n", "\n", "As an example of the following model we will try today : \n", "\n", "`{task name}_{language id}_{model identifier}_[OPTIONAL modifiers]` = `stt_en_conformer_ctc_small`" ], "metadata": { "id": "MRO2f9fhHywJ" } }, { "cell_type": "markdown", "source": [ "**Set the MODEL_NAME carefully** !" ], "metadata": { "id": "BjLstKWnPzWV" } }, { "cell_type": "code", "source": [ "MODEL_NAME = \"stt_en_conformer_ctc_small\"" ], "metadata": { "id": "UzHjXDbckU0M" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "**Restore a NeMo Model**\n", "\n", "Here, we restore a model from NGC directly, but you can restore a model from your training runs using `restore_from()` or use a local .nemo file." ], "metadata": { "id": "qibj1RwvKjSQ" } }, { "cell_type": "code", "source": [ "model = nemo_asr.models.ASRModel.from_pretrained(MODEL_NAME)" ], "metadata": { "id": "MsC3pE65d_z2" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Create a Hugging Face Model\n", "\n", "Now that we have a NeMo model and have logged into Hugging Face with our user API key, we can begin by creating a new repository and uploading our model." ], "metadata": { "id": "y1AkXPFVKfC2" } }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "After the model has been restored, create an HfApi object to interact with the model repository." ], "metadata": { "id": "iv17qFG7KzlL" } }, { "cell_type": "code", "source": [ "from huggingface_hub import HfApi\n", "api = HfApi()\n", "username = api.whoami()['name']" ], "metadata": { "id": "aJUXCOTjKy-2" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "try:\n", " api.create_repo(repo_id=MODEL_NAME)\n", " print(\"Successfully created repository !\")\n", "except Exception as e:\n", " print(\"Repository is possibly already created. Refer to error here - \\n\\n\", e)" ], "metadata": { "id": "DKRlMeaEkeAH" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from huggingface_hub import Repository" ], "metadata": { "id": "N2-deSyTlCdS" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Note two essential names - \n", "\n", "- `hf_model_name`: A string name that is the composite of your `username` and `MODEL_NAME` as set above. This name is used for multiple purposes, so keep track of it.\n", "\n", "- `model_filename`: The actual filename of the NeMo model that will be uploaded to Hugging Face. Note that this filename is explicitly set to `{MODEL_NAME}.nemo`. If this model filename is altered, then the model cannot correctly be restored by NeMo when downloaded from Hugging Face Hub, so please be careful." ], "metadata": { "id": "aTa4RqDYLGMI" } }, { "cell_type": "code", "source": [ "local_dir = f'model-{MODEL_NAME}/'\n", "hf_model_name = f'{username}/{MODEL_NAME}'\n", "\n", "commit_message = \"Upload model\"\n", "model_filename = f'{MODEL_NAME}.nemo'\n", "\n", "with Repository(local_dir=local_dir, clone_from=hf_model_name, repo_type='model').commit(commit_message):\n", " model.save_to(model_filename)" ], "metadata": { "id": "xhTTMNpBskMS" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "print(\"Finished uploading model to :\", hf_model_name)" ], "metadata": { "id": "BhvNp8MYvxLi" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## Test if the model works \n", "\n", "Now that we uploaded the model, let's try to use it in NeMo !\n", "\n", "The only change required between normally calling `from_pretrained(model_name)` is to call **`from_pretrained({username}/{filename})`**" ], "metadata": { "id": "Qrs-MlW9vVbH" } }, { "cell_type": "code", "source": [ "hf_model_name = f'{username}/{MODEL_NAME}'\n", "hf_model = nemo_asr.models.ASRModel.from_pretrained(hf_model_name)" ], "metadata": { "id": "NyuyyRv5snkr" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "print(\"Successfully used HF model -\", hf_model_name)" ], "metadata": { "id": "Yhi922WVv4G_" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# Model Card\n", "\n", "Now that we have uploaded the model, we are nearly 50% done!\n", "\n", "The next step is to update the model card to have some helpful information regarding the uploaded model and its scores compared to other models.\n", "\n", "You can do this in two ways, manually (by clicking the link below) or programmatically fill in part of the model card by following the instructions below." ], "metadata": { "id": "9gG1ElJywEJT" } }, { "cell_type": "code", "source": [ "hf_url = f'https://huggingface.co/{username}/{MODEL_NAME}'\n", "print(f\"Visit {hf_url} to manually edit your model card\")" ], "metadata": { "id": "aZJRKoxhwBLr" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "Here, we are going to setup some variables for our model card.\n", "\n", "First up are the tags:" ], "metadata": { "id": "ZlA4hNq6w4rH" } }, { "cell_type": "code", "source": [ "TAGS = [\n", " \"automatic-speech-recognition\", # Task id, refer to https://github.com/huggingface/datasets/blob/master/src/datasets/utils/resources/tasks.json for allowed values.\n", " \"speech\", # add as many other tags as required\n", " \"audio\",\n", " \"CTC\",\n", " \"Conformer\",\n", " \"Transformer\",\n", " \"NeMo\", # required for library identification\n", " \"pytorch\", # required, for toolkit identification\n", " # \"hf-asr-leaderboard\", # Should only be used if model is evaluated on benchmark scores for ASR.\n", "]" ], "metadata": { "id": "QxKtPynWyUWX" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "Next, we list down all the datasets that were used to train the model.\n", "\n", "By convention, try to search if the dataset already exists on Hugging Face Datasets - it is usually listed at the top and in lower case.\n", "\n", "If you train on datasets that don't yet exist in Hugging Face Datasets, you can still add them but try to differentiate them by using capitalized names." ], "metadata": { "id": "Fh7rYWEMM0Vz" } }, { "cell_type": "code", "source": [ "# Replace all spaces with `-`\n", "DATASETS = [\n", " \"librispeech_asr\",\n", " \"mozilla-foundation/common_voice_7_0\",\n", " \"vctk\",\n", " \"fisher_corpus\",\n", " \"Switchboard-1\",\n", " \"WSJ-0\",\n", " \"WSJ-1\",\n", " \"National-Singapore-Corpus-Part-1\",\n", " \"National-Singapore-Corpus-Part-6\",\n", " \"VoxPopuli-(EN)\",\n", " \"Europarl-ASR-(EN)\",\n", " \"Multilingual-LibriSpeech-(2000-hours)\",\n", "]" ], "metadata": { "id": "qy-5aDAgzuGD" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "Now we create an automated template based on a config for the top portion of the readme file." ], "metadata": { "id": "_0w1X_z4NN5-" } }, { "cell_type": "code", "source": [ "from dataclasses import dataclass, field\n", "from typing import List, Optional, Dict, Any\n", "\n", "@dataclass\n", "class NeMoHuggingFaceModelConfig:\n", " language: List[str]\n", " license: str\n", "\n", " library_name: str = \"nemo\"\n", " datasets: List[str] = field(default_factory=lambda: DATASETS)\n", " thumbnail: Optional[str] = None\n", " tags: List[str] = field(default_factory=lambda: TAGS)\n", " model_index: Any = field(default_factory=lambda: [dict(name=MODEL_NAME, results=[])])" ], "metadata": { "id": "O88WFyPJwjJD" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "config = NeMoHuggingFaceModelConfig(language=['en'], license=\"cc-by-4.0\") # choose appropriate license here\n", "config = OmegaConf.structured(config)\n", "\n", "with open_dict(config):\n", " # Update `model_index` to `model-index`\n", " model_index = config.pop('model_index')\n", " config['model-index'] = model_index\n", "\n", " # Replace all spaces with `-` in datasets\n", " normalized_datasets = [ds_name.replace(\" \", \"-\") for ds_name in config['datasets']]\n", " config['datasets'] = OmegaConf.create(normalized_datasets)\n", "\n", "print(OmegaConf.to_yaml(config))" ], "metadata": { "id": "BpInrBdNxxZ3" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## Markdown Template\n", "\n", "Now that we have an auto-generated header for our readme, next, we write down some template markdown for the actual contents of the markdown.\n", "\n", "You can edit the code here directly if you want, or if you prefer the GUI to see the actual changes in real-time, you can finish uploading this model card and then edit the readme file on the Hugging Face webpage itself." ], "metadata": { "id": "0TECX8QrC6FY" } }, { "cell_type": "code", "source": [ "hf_model_name = f'{username}/{MODEL_NAME}'\n", "\n", "TEMPLATE = f\"\"\"\n", "## Model Overview\n", "\n", "\n", "\n", "## NVIDIA NeMo: Training\n", "\n", "To train, fine-tune or play with the model you will need to install [NVIDIA NeMo](https://github.com/NVIDIA/NeMo). We recommend you install it after you've installed latest Pytorch version.\n", "```\n", "pip install nemo_toolkit['all']\n", "``` \n", "\n", "## How to Use this Model\n", "\n", "The model is available for use in the NeMo toolkit [3], and can be used as a pre-trained checkpoint for inference or for fine-tuning on another dataset.\n", "\n", "### Automatically instantiate the model\n", "\n", "```python\n", "import nemo.collections.asr as nemo_asr\n", "asr_model = nemo_asr.models.ASRModel.from_pretrained(\"{hf_model_name}\")\n", "```\n", "\n", "### Transcribing using Python\n", "First, let's get a sample\n", "```\n", "wget https://dldata-public.s3.us-east-2.amazonaws.com/2086-149220-0033.wav\n", "```\n", "Then simply do:\n", "```\n", "asr_model.transcribe(['2086-149220-0033.wav'])\n", "```\n", "\n", "### Transcribing many audio files\n", "\n", "```shell\n", "python [NEMO_GIT_FOLDER]/examples/asr/transcribe_speech.py \\\n", " pretrained_name=\"{hf_model_name}\" \\\n", " audio_dir=\"\"\n", "```\n", "\n", "### Input\n", "\n", "This model accepts 16000 KHz Mono-channel Audio (wav files) as input.\n", "\n", "### Output\n", "\n", "This model provides transcribed speech as a string for a given audio sample.\n", "\n", "## Model Architecture\n", "\n", "\n", "\n", "## Training\n", "\n", "\n", "\n", "### Datasets\n", "\n", "\n", "\n", "## Performance\n", "\n", "\n", "\n", "## Limitations\n", "\n", "\n", "\n", "Eg: \n", "Since this model was trained on publically available speech datasets, the performance of this model might degrade for speech which includes technical terms, or vernacular that the model has not been trained on. The model might also perform worse for accented speech.\n", "\n", "\n", "## References\n", "\n", "\n", "\n", "[1] [NVIDIA NeMo Toolkit](https://github.com/NVIDIA/NeMo)\n", "\n", "\"\"\"" ], "metadata": { "id": "SSmm7_OiC9Ex" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "Below, we will upload this model card in a temporary file called **`\"readme_template.md\"`**. This is done to prevent overwriting of the \"final\" model card that the user may have manually edited.\n", "\n", "Once this step is finished, **please copy the contents of this file, create a README.md file and paste the contents into it**." ], "metadata": { "id": "KPa53S_5NzNp" } }, { "cell_type": "code", "source": [ "local_dir = f'model-{MODEL_NAME}/'\n", "hf_model_name = f'{username}/{MODEL_NAME}'\n", "\n", "commit_message = \"Upload config\"\n", "filename = 'readme_template.md'\n", "\n", "with Repository(local_dir=local_dir, clone_from=hf_model_name, repo_type='model').commit(commit_message):\n", " with open(filename, 'w') as f:\n", " f.write(\"---\\n\")\n", " f.write(OmegaConf.to_yaml(config))\n", " f.write(\"\\n---\\n\\n\")\n", " f.write(TEMPLATE)\n", " " ], "metadata": { "id": "0vk5KK4gzpSU" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "Please visit the URL below to copy the contents of the `readme_template.md` file into your `README.md` file." ], "metadata": { "id": "dfXoihCQmWDa" } }, { "cell_type": "code", "source": [ "hf_url = f'https://huggingface.co/{username}/{MODEL_NAME}'\n", "print(f\"Visit {hf_url} to edit your model card from the generated template file `{filename}`\")" ], "metadata": { "id": "but-5LuLTHFd" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## Evaluation Results\n", "\n", "Now that we have both the model checkpoint and the readme uploaded to the Hub, we can optionally add some evaluation results to the card as well!\n", "\n", "While this next section is optional, it is highly encouraged to do!" ], "metadata": { "id": "5vPEnlE62dGU" } }, { "cell_type": "code", "source": [ "import evaluate\n", "# evaluate.list_evaluation_modules(module_type='metric', with_details=True)" ], "metadata": { "id": "rkXMtapA0YzH" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Uncomment in order to see what values you can supply to the `evaluate` library to push to the Hub.\n", "# help(evaluate.push_to_hub)" ], "metadata": { "id": "50rzG9Qb3yLR" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "hf_model_name = f'{username}/{MODEL_NAME}'\n", "metric_value = 8.1 # value obtained from https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_conformer_ctc_small \n", "\n", "evaluate.push_to_hub(\n", " model_id=hf_model_name,\n", " task_type=\"automatic-speech-recognition\",\n", " dataset_type=\"librispeech_asr\",\n", " dataset_name=\"Librispeech (clean)\",\n", " metric_type=\"wer\",\n", " metric_name=\"WER\",\n", " dataset_split=\"test\", # corresponds to test-clean set\n", " dataset_config=\"other\", # corresponds to test-clean set\n", " dataset_args=dict(language=\"en\"), # metadata for dataset\n", " # the actual score obtained by the model\n", " metric_value=metric_value,\n", ")" ], "metadata": { "id": "5A4g3SGf4d0V" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "-----\n", "\n", "Done! Now we have a model checkpoint, a model card as well as evaluation results all set up for the NeMo model on Hugging Face!\n", "\n", "To add more metrics, you can copy-paste the above cell and repeat the procedure for as many metrics as needed!" ], "metadata": { "id": "f3YYa7liO_m3" } } ] }