File size: 23,965 Bytes
7934b29 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
{
"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\": \"<UNK>\", \n",
" \"sep_token\": \"<SEP>\", \n",
" \"pad_token\": \"<PAD>\", \n",
" \"bos_token\": \"<CLS>\", \n",
" \"mask_token\": \"<MASK>\",\n",
" \"eos_token\": \"<SEP>\",\n",
" \"cls_token\": \"<CLS>\"}\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": [
"`['<MASK>', '<CLS>', '<SEP>', '<PAD>', '<SEP>', '<CLS>', '<UNK>'] \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('<MY_NEW_TOKEN> and another word')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see in the above, the tokenizer splits `<MY_NEW_TOKEN>` 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': '<BOS>',\n",
" 'cls_token': '<CSL>',\n",
" 'additional_special_tokens': ['<MY_NEW_TOKEN>', '<ANOTHER_TOKEN>']}\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('<MY_NEW_TOKEN> 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
}
|