{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "X87q4jmW4Rmi" }, "outputs": [], "source": [ "BRANCH = 'r1.17.0'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "djqHSONJ20X8" }, "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 NeMo\n", "BRANCH = 'r1.17.0'\n", "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "CmvtH0pxHDQC" }, "outputs": [], "source": [ "import os\n", "import wget\n", "from nemo.collections import nlp as nemo_nlp\n", "from nemo.collections import common as nemo_common\n", "from omegaconf import OmegaConf" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "J6AARcXXUEbs" }, "source": [ "# Tokenizers Background\n", "\n", "For Natural Language Processing, tokenization is an essential part of data preprocessing. It is the process of splitting a string into a list of tokens. One can think of token as parts like a word is a token in a sentence.\n", "Depending on the application, different tokenizers are more suitable than others. \n", "\n", "\n", "For example, a WordTokenizer that splits the string on any whitespace, would tokenize the following string \n", "\n", "\"My first program, Hello World.\" -> [\"My\", \"first\", \"program,\", \"Hello\", \"World.\"]\n", "\n", "To turn the tokens into numerical model input, the standard method is to use a vocabulary and one-hot vectors for [word embeddings](https://en.wikipedia.org/wiki/Word_embedding). If a token appears in the vocabulary, its index is returned, if not the index of the unknown token is returned to mitigate out-of-vocabulary (OOV).\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Fx7kTz00FL9W" }, "source": [ "# Tokenizers in NeMo\n", "\n", "In NeMo, we support the most used tokenization algorithms. We offer a wrapper around [Hugging Faces's AutoTokenizer](https://huggingface.co/transformers/model_doc/auto.html#autotokenizer) - a factory class that gives access to all Hugging Face tokenizers. This includes particularly all BERT-like model tokenizers, such as BertTokenizer, AlbertTokenizer, RobertaTokenizer, GPT2Tokenizer. Apart from that, we also support other tokenizers such as WordTokenizer, CharTokenizer, and [Google's SentencePieceTokenizer](https://github.com/google/sentencepiece). \n", "\n", "\n", "We make sure that all tokenizers are compatible with BERT-like models, e.g. BERT, Roberta, Albert, and Megatron. For that, we provide a high-level user API `get_tokenizer()`, which allows the user to instantiate a tokenizer model with only four input arguments: \n", "* `tokenizer_name: str`\n", "* `tokenizer_model: Optional[str] = None`\n", "* `vocab_file: Optional[str] = None`\n", "* `special_tokens: Optional[Dict[str, str]] = None`\n", "\n", "Hugging Face and Megatron tokenizers (which uses Hugging Face underneath) can be automatically instantiated by only `tokenizer_name`, which downloads the corresponding `vocab_file` from the internet. \n", "\n", "For SentencePieceTokenizer, WordTokenizer, and CharTokenizers `tokenizer_model` or/and `vocab_file` can be generated offline in advance using [`scripts/tokenizers/process_asr_text_tokenizer.py`](https://github.com/NVIDIA/NeMo/blob/stable/scripts/tokenizers/process_asr_text_tokenizer.py)\n", "\n", "The tokenizers in NeMo are designed to be used interchangeably, especially when\n", "used in combination with a BERT-based model.\n", "\n", "Let's take a look at the list of available tokenizers:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "zp7F45bgX7SU" }, "outputs": [], "source": [ "nemo_nlp.modules.get_tokenizer_list()" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "9O-TJpIgG1Mt" }, "source": [ "# Hugging Face AutoTokenizer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "5xQdZmj-IuZi" }, "outputs": [], "source": [ "# instantiate tokenizer wrapper using pretrained model name only\n", "tokenizer1 = nemo_nlp.modules.get_tokenizer(tokenizer_name=\"bert-base-cased\")\n", "\n", "# the wrapper has a reference to the original HuggingFace tokenizer\n", "print(tokenizer1.tokenizer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "_Z7__VbTolBK" }, "outputs": [], "source": [ "# check vocabulary (this can be very long)\n", "print(tokenizer1.tokenizer.vocab)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "z1CRAkRdonV9" }, "outputs": [], "source": [ "# show all special tokens if it has any\n", "print(tokenizer1.tokenizer.all_special_tokens)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "SnE7LetCoCFY" }, "outputs": [], "source": [ "# instantiate tokenizer using custom vocabulary\n", "vocab_file = \"myvocab.txt\"\n", "vocab = [\"he\", \"llo\", \"world\"]\n", "with open(vocab_file, 'w', encoding='utf-8') as vocab_fp:\n", " vocab_fp.write(\"\\n\".join(vocab))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "UEznqEwRo3Jw" }, "outputs": [], "source": [ "tokenizer2 = nemo_nlp.modules.get_tokenizer(tokenizer_name=\"bert-base-cased\", vocab_file=vocab_file)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "FsdSZ0pYoySH" }, "outputs": [], "source": [ "# Since we did not overwrite special tokens they should be the same as before\n", "print(tokenizer1.tokenizer.all_special_tokens == tokenizer2.tokenizer.all_special_tokens )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding Special tokens\n", "\n", "We do not recommend overwriting special tokens for Hugging Face pretrained models, \n", "since these are the commonly used default values. \n", "\n", "If a user still wants to overwrite the special tokens, specify some of the following keys:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "apQz4QPHoGRW" }, "outputs": [], "source": [ "special_tokens_dict = {\"unk_token\": \"\", \n", " \"sep_token\": \"\", \n", " \"pad_token\": \"\", \n", " \"bos_token\": \"\", \n", " \"mask_token\": \"\",\n", " \"eos_token\": \"\",\n", " \"cls_token\": \"\"}\n", "tokenizer3 = nemo_nlp.modules.get_tokenizer(tokenizer_name=\"bert-base-cased\",\n", " vocab_file=vocab_file,\n", " special_tokens=special_tokens_dict)\n", "\n", "# print newly set special tokens\n", "print(tokenizer3.tokenizer.all_special_tokens)\n", "# the special tokens should be different from the previous special tokens\n", "print(tokenizer3.tokenizer.all_special_tokens != tokenizer1.tokenizer.all_special_tokens )" ] }, { "cell_type": "markdown", "metadata": { "colab": {}, "colab_type": "code", "id": "MA1ttDXro64B" }, "source": [ "Notice, that if you specify tokens that were not previously included in the tokenizer's vocabulary file, new tokens will be added to the vocabulary file. You will see a message like this:" ] }, { "cell_type": "markdown", "metadata": { "colab": {}, "colab_type": "code", "id": "MA1ttDXro64B" }, "source": [ "`['', '', '', '', '', '', ''] \n", " will be added to the vocabulary.\n", " Please resize your model accordingly`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# A safer way to add special tokens is the following:\n", "\n", "# define your model\n", "pretrained_model_name = 'bert-base-uncased'\n", "config = {\"language_model\": {\"pretrained_model_name\": pretrained_model_name}, \"tokenizer\": {}}\n", "omega_conf = OmegaConf.create(config)\n", "model = nemo_nlp.modules.get_lm_model(cfg=omega_conf)\n", "\n", "# define pretrained tokenizer\n", "tokenizer_default = nemo_nlp.modules.get_tokenizer(tokenizer_name=pretrained_model_name)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tokenizer_default.text_to_tokens(' and another word')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see in the above, the tokenizer splits `` into subtokens. Let's add this to the special tokens to make sure the tokenizer does not split this into subtokens." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "special_tokens = {'bos_token': '',\n", " 'cls_token': '',\n", " 'additional_special_tokens': ['', '']}\n", "tokenizer_default.add_special_tokens(special_tokens_dict=special_tokens)\n", "\n", "# resize your model so that the embeddings for newly added tokens are updated during training/finetuning\n", "model.resize_token_embeddings(tokenizer_default.vocab_size)\n", "\n", "# let's make sure the tokenizer doesn't split our special tokens into subtokens\n", "tokenizer_default.text_to_tokens(' and another word')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, the model doesn't break down our special token into the subtokens." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "y4Ptfo5dXmk_" }, "source": [ "## Megatron model tokenizer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "5zllsvBojxuJ" }, "outputs": [], "source": [ "# Megatron tokenizers are instances of the Hugging Face BertTokenizer. \n", "tokenizer4 = nemo_nlp.modules.get_tokenizer(tokenizer_name=\"megatron-bert-cased\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jEgEo0aPj3Ws" }, "source": [ "# Train custom tokenizer model and vocabulary from text file " ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ykwKmREuPQE-" }, "source": [ "We use the [`scripts/tokenizers/process_asr_text_tokenizer.py`](https://github.com/NVIDIA/NeMo/blob/stable/scripts/tokenizers/process_asr_text_tokenizer.py) script to create a custom tokenizer model with its own vocabulary from an input file" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "OD5FUul3QGhA" }, "outputs": [], "source": [ "# download tokenizer script\n", "script_file = \"process_asr_text_tokenizer.py\"\n", "\n", "if not os.path.exists(script_file):\n", " print('Downloading script file...')\n", " wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/tokenizers/process_asr_text_tokenizer.py')\n", "else:\n", " print ('Script already exists')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "T1gA8PsJ13MJ" }, "outputs": [], "source": [ "# Let's prepare some small text data for the tokenizer\n", "data_text = \"NeMo is a toolkit for creating Conversational AI applications. \\\n", "NeMo toolkit makes it possible for researchers to easily compose complex neural network architectures \\\n", "for conversational AI using reusable components - Neural Modules. \\\n", "Neural Modules are conceptual blocks of neural networks that take typed inputs and produce typed outputs. \\\n", "Such modules typically represent data layers, encoders, decoders, language models, loss functions, or methods of combining activations. \\\n", "The toolkit comes with extendable collections of pre-built modules and ready-to-use models for automatic speech recognition (ASR), \\\n", "natural language processing (NLP) and text synthesis (TTS). \\\n", "Built for speed, NeMo can utilize NVIDIA's Tensor Cores and scale out training to multiple GPUs and multiple nodes.\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "SaqyxVZgpMJk" }, "outputs": [], "source": [ "# Write the text data into a file\n", "data_file=\"data.txt\"\n", "\n", "with open(data_file, 'w') as data_fp:\n", " data_fp.write(data_text)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "iWz31g-opP9z" }, "outputs": [], "source": [ "# Some additional parameters for the tokenizer\n", "# To tokenize at unigram, char or word boundary instead of using bpe, change --spe_type accordingly. \n", "# More details see https://github.com/google/sentencepiece#train-sentencepiece-model\n", "\n", "tokenizer_spe_type = \"bpe\" # <-- Can be `bpe`, `unigram`, `word` or `char`\n", "vocab_size = 32" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "mX3KmWMvSUQw" }, "outputs": [], "source": [ "! python process_asr_text_tokenizer.py --data_file=$data_file --data_root=. --vocab_size=$vocab_size --tokenizer=spe --spe_type=$tokenizer_spe_type" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "v6hlcCYyKFiY" }, "outputs": [], "source": [ "# See created tokenizer model and vocabulary\n", "spe_model_dir=f\"tokenizer_spe_{tokenizer_spe_type}_v{vocab_size}\"\n", "! ls $spe_model_dir" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "EVp4zvxPatga" }, "source": [ "# Use custom tokenizer for data preprocessing\n", "## Example: SentencePiece for BPE" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "0o-XPMrIQBmm" }, "outputs": [], "source": [ "# initialize tokenizer with created tokenizer model, which inherently includes the vocabulary and specify optional special tokens\n", "tokenizer_spe = nemo_nlp.modules.get_tokenizer(tokenizer_name=\"sentencepiece\", tokenizer_model=spe_model_dir+\"/tokenizer.model\", special_tokens=special_tokens_dict)\n", "\n", "# specified special tokens are added to the vocabuary\n", "print(tokenizer_spe.vocab_size)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "caafJmVLmEVD" }, "source": [ "# Using any tokenizer to tokenize text into BERT compatible input\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "ms4DAC4BpvqS" }, "outputs": [], "source": [ "text=\"hello world\"\n", "\n", "# create tokens\n", "tokenized = [tokenizer_spe.bos_token] + tokenizer_spe.text_to_tokens(text) + [tokenizer_spe.eos_token]\n", "print(tokenized)\n", "\n", "# turn token into input_ids for a neural model, such as BERTModule\n", "\n", "print(tokenizer_spe.tokens_to_ids(tokenized))" ] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "02_NLP_Tokenizers.ipynb", "provenance": [], "toc_visible": true }, "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.8.12" }, "pycharm": { "stem_cell": { "cell_type": "raw", "metadata": { "collapsed": false }, "source": [] } } }, "nbformat": 4, "nbformat_minor": 1 }