File size: 29,560 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Token_Classification_Named_Entity_Recognition.ipynb",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU",
    "pycharm": {
      "stem_cell": {
        "cell_type": "raw",
        "source": [],
        "metadata": {
          "collapsed": false
        }
      }
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "BRANCH = 'r1.17.0'"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "o_0K1lsW1dj9",
        "colab_type": "code",
        "colab": {}
      },
      "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]\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "pycharm": {
          "name": "#%%\n"
        },
        "id": "pC0slAc0h9zN",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:\n",
        "# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'\n",
        "\n",
        "! pip install ipywidgets\n",
        "! jupyter nbextension enable --py widgetsnbextension\n",
        "\n",
        "# Please restart the kernel after running this cell"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "dzqD2WDFOIN-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "from nemo.collections import nlp as nemo_nlp\n",
        "from nemo.utils.exp_manager import exp_manager\n",
        "\n",
        "import os\n",
        "import wget \n",
        "import torch\n",
        "import pytorch_lightning as pl\n",
        "from omegaconf import OmegaConf"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "daYw_Xll2ZR9",
        "colab_type": "text"
      },
      "source": [
        "# Task Description\n",
        "**Named entity recognition (NER)**, also referred to as entity chunking, identification or extraction, is the task of detecting and classifying key information (entities) in text.\n",
        "For example, in a sentence:  `Mary lives in Santa Clara and works at NVIDIA`, we should detect that `Mary` is a person, `Santa Clara` is a location and `NVIDIA` is a company."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZnuziSwJ1yEB",
        "colab_type": "text"
      },
      "source": [
        "# Dataset\n",
        "\n",
        "In this tutorial we going to use [GMB(Groningen Meaning Bank)](http://www.let.rug.nl/bjerva/gmb/about.php) corpus for entity recognition. \n",
        "\n",
        "GMB is a fairly large corpus with a lot of annotations. Note, that GMB is not completely human annotated and it’s not considered 100% correct. \n",
        "The data is labeled using the [IOB format](https://en.wikipedia.org/wiki/Inside%E2%80%93outside%E2%80%93beginning_(tagging)) (short for inside, outside, beginning). \n",
        "\n",
        "The following classes appear in the dataset:\n",
        "* LOC = Geographical Entity\n",
        "* ORG = Organization\n",
        "* PER = Person\n",
        "* GPE = Geopolitical Entity\n",
        "* TIME = Time indicator\n",
        "* ART = Artifact\n",
        "* EVE = Event\n",
        "* NAT = Natural Phenomenon\n",
        "\n",
        "For this tutorial, classes ART, EVE, and NAT were combined into a MISC class due to small number of examples for these classes.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qzcZ3nb_-SVT",
        "colab_type": "text"
      },
      "source": [
        "# NeMo Token Classification Data Format\n",
        "\n",
        "[TokenClassification Model](https://github.com/NVIDIA/NeMo/blob/stable/nemo/collections/nlp/models/token_classification/token_classification_model.py) in NeMo supports NER and other token level classification tasks, as long as the data follows the format specified below. \n",
        "\n",
        "Token Classification Model requires the data to be split into 2 files: \n",
        "* text.txt and \n",
        "* labels.txt. \n",
        "\n",
        "Each line of the **text.txt** file contains text sequences, where words are separated with spaces, i.e.: \n",
        "[WORD] [SPACE] [WORD] [SPACE] [WORD].\n",
        "\n",
        "The **labels.txt** file contains corresponding labels for each word in text.txt, the labels are separated with spaces, i.e.:\n",
        "[LABEL] [SPACE] [LABEL] [SPACE] [LABEL].\n",
        "\n",
        "Example of a text.txt file:\n",
        "```\n",
        "Jennifer is from New York City .\n",
        "She likes ...\n",
        "...\n",
        "```\n",
        "Corresponding labels.txt file:\n",
        "```\n",
        "B-PER O O B-LOC I-LOC I-LOC O\n",
        "O O ...\n",
        "...\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VsEmwIPO4L4V",
        "colab_type": "text"
      },
      "source": [
        "To convert an IOB format data to the format required for training, run [examples/nlp/token_classification/data/import_from_iob_format.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/data/import_from_iob_format.py) on your train and dev files, as follows:\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "```\n",
        "python examples/nlp/token_classification/data/import_from_iob_format.py --data_file PATH_TO_IOB_FORMAT_DATAFILE\n",
        "```\n",
        "\n",
        "For this tutorial, we are going to use the preprocessed GMB dataset.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SL58EWkd2ZVb",
        "colab_type": "text"
      },
      "source": [
        "## Download and preprocess the data¶"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "n8HZrDmr12_-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "DATA_DIR = \"DATA_DIR\"\n",
        "WORK_DIR = \"WORK_DIR\"\n",
        "MODEL_CONFIG = \"token_classification_config.yaml\""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jrx2ZXHrCHb_",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# download preprocessed data\n",
        "os.makedirs(WORK_DIR, exist_ok=True)\n",
        "os.makedirs(DATA_DIR, exist_ok=True)\n",
        "print('Downloading GMB data...')\n",
        "wget.download('https://dldata-public.s3.us-east-2.amazonaws.com/gmb_v_2.2.0_clean.zip', DATA_DIR)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NhUzIeF0Yg0l",
        "colab_type": "text"
      },
      "source": [
        "Let's extract files from the .zip file:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y01BdjPRW-7B",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "! unzip {DATA_DIR}/gmb_v_2.2.0_clean.zip -d {DATA_DIR}\n",
        "DATA_DIR = os.path.join(DATA_DIR, 'gmb_v_2.2.0_clean')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "U8Ty5_S7Ye8h",
        "colab_type": "text"
      },
      "source": [
        "Now, the data folder should contain 4 files:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L8vsyh3JZH26",
        "colab_type": "text"
      },
      "source": [
        "\n",
        "\n",
        "* labels_dev.txt\n",
        "* labels_train.txt\n",
        "* text_dev.txt\n",
        "* text_train.txt\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qB0oLE4R9EhJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "! ls -l {DATA_DIR}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6UDPgadLN6SG",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's take a look at the data \n",
        "print('Text:')\n",
        "! head -n 5 {DATA_DIR}/text_train.txt\n",
        "\n",
        "print('\\nLabels:')\n",
        "! head -n 5 {DATA_DIR}/labels_train.txt"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "daludzzL2Jba",
        "colab_type": "text"
      },
      "source": [
        "# Model Configuration"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tit5kG4Z5SXu",
        "colab_type": "text"
      },
      "source": [
        "# Using an Out-of-the-Box Model\n",
        "\n",
        "To use a pretrained NER model, run:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BKe5Jn4u9xng",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# this line will download pre-trained NER model from NVIDIA's NGC cloud and instantiate it for you\n",
        "pretrained_ner_model = nemo_nlp.models.TokenClassificationModel.from_pretrained(model_name=\"ner_en_bert\") "
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "y8SFxPJd-hkH"
      },
      "source": [
        "To see how the model performs, let’s get model's predictions for a few examples:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DQhsamclRtxJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# define the list of queries for inference\n",
        "queries = [\n",
        "    'we bought four shirts from the nvidia gear store in santa clara.',\n",
        "    'Nvidia is a company.',\n",
        "    'The Adventures of Tom Sawyer by Mark Twain is an 1876 novel about a young boy growing '\n",
        "    + 'up along the Mississippi River.',\n",
        "]\n",
        "results = pretrained_ner_model.add_predictions(queries)\n",
        "\n",
        "for query, result in zip(queries, results):\n",
        "    print()\n",
        "    print(f'Query : {query}')\n",
        "    print(f'Result: {result.strip()}\\n')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_whKCxfTMo6Y",
        "colab_type": "text"
      },
      "source": [
        "Now, let's take a closer look at the model's configuration and learn to train the model from scratch and finetune the pretrained model.\n",
        "\n",
        "# Model configuration\n",
        "\n",
        "Our Named Entity Recognition model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model followed by a Token Classification layer.\n",
        "\n",
        "The model is defined in a config file which declares multiple important sections. They are:\n",
        "- **model**: All arguments that are related to the Model - language model, token classifier, optimizer and schedulers, datasets and any other related information\n",
        "\n",
        "- **trainer**: Any argument to be passed to PyTorch Lightning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "T1gA8PsJ13MJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# download the model's configuration file \n",
        "config_dir = WORK_DIR + '/configs/'\n",
        "os.makedirs(config_dir, exist_ok=True)\n",
        "if not os.path.exists(config_dir + MODEL_CONFIG):\n",
        "    print('Downloading config file...')\n",
        "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG, config_dir)\n",
        "else:\n",
        "    print ('config file is already exists')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mX3KmWMvSUQw",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# this line will print the entire config of the model\n",
        "config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\n",
        "print(config_path)\n",
        "config = OmegaConf.load(config_path)\n",
        "print(OmegaConf.to_yaml(config))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZCgWzNBkaQLZ",
        "colab_type": "text"
      },
      "source": [
        "# Model Training From Scratch\n",
        "## Setting up Data within the config\n",
        "\n",
        "Among other things, the config file contains dictionaries called dataset, train_ds and validation_ds. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
        "\n",
        "We assume that both training and evaluation files are located in the same directory, and use the default names mentioned during the data download step. \n",
        "So, to start model training, we simply need to specify `model.dataset.data_dir`, like we are going to do below.\n",
        "\n",
        "Also notice that some config lines, including `model.dataset.data_dir`, have `???` in place of paths, this means that values for these fields are required to be specified by the user.\n",
        "\n",
        "Let's now add the data directory path to the config."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LQHCJN-ZaoLp",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# in this tutorial train and dev datasets are located in the same folder, so it is enought to add the path of the data directory to the config\n",
        "config.model.dataset.data_dir = DATA_DIR\n",
        "\n",
        "# if you want to use the full dataset, set NUM_SAMPLES to -1\n",
        "NUM_SAMPLES = 1000\n",
        "config.model.train_ds.num_samples = NUM_SAMPLES\n",
        "config.model.validation_ds.num_samples = NUM_SAMPLES"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nB96-3sTc3yk",
        "colab_type": "text"
      },
      "source": [
        "## Building the PyTorch Lightning Trainer\n",
        "\n",
        "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem.\n",
        "\n",
        "Let's first instantiate a Trainer object"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1tG4FzZ4Ui60",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "print(\"Trainer config - \\n\")\n",
        "print(OmegaConf.to_yaml(config.trainer))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "knF6QeQQdMrH",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# lets modify some trainer configs\n",
        "# checks if we have GPU available and uses it\n",
        "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
        "config.trainer.devices = 1\n",
        "config.trainer.accelerator = accelerator\n",
        "\n",
        "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
        "\n",
        "# for mixed precision training, uncomment the line below (precision should be set to 16 and amp_level to O1):\n",
        "# config.trainer.amp_level = O1\n",
        "\n",
        "# remove distributed training flags\n",
        "config.trainer.strategy = None\n",
        "\n",
        "# setup max number of steps to reduce training time for demonstration purposes of this tutorial\n",
        "config.trainer.max_steps = 32\n",
        "\n",
        "trainer = pl.Trainer(**config.trainer)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8IlEMdVxdr6p",
        "colab_type": "text"
      },
      "source": [
        "## Setting up a NeMo Experiment¶\n",
        "\n",
        "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8uztqGAmdrYt",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
        "\n",
        "# the exp_dir provides a path to the current experiment for easy access\n",
        "exp_dir = str(exp_dir)\n",
        "exp_dir"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8tjLhUvL_o7_",
        "colab_type": "text"
      },
      "source": [
        "Before initializing the model, we might want to modify some of the model configs. For example, we might want to modify the pretrained BERT model:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Xeuc2i7Y_nP5",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# get the list of supported BERT-like models, for the complete list of HugginFace models, see https://huggingface.co/models\n",
        "print(nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True))\n",
        "\n",
        "# specify BERT-like model, you want to use\n",
        "PRETRAINED_BERT_MODEL = \"bert-base-uncased\""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RK2xglXyAUOO",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# add the specified above model parameters to the config\n",
        "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fzNZNAVRjDD-",
        "colab_type": "text"
      },
      "source": [
        "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.\n",
        "Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NgsGLydWo-6-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "model_from_scratch = nemo_nlp.models.TokenClassificationModel(cfg=config.model, trainer=trainer)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kQ592Tx4pzyB",
        "colab_type": "text"
      },
      "source": [
        "## Monitoring training progress\n",
        "Optionally, you can create a Tensorboard visualization to monitor training progress."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mTJr16_pp0aS",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  from google import colab\n",
        "  COLAB_ENV = True\n",
        "except (ImportError, ModuleNotFoundError):\n",
        "  COLAB_ENV = False\n",
        "\n",
        "# Load the TensorBoard notebook extension\n",
        "if COLAB_ENV:\n",
        "  %load_ext tensorboard\n",
        "  %tensorboard --logdir {exp_dir}\n",
        "else:\n",
        "  print(\"To use tensorboard, please use this notebook in a Google Colab environment.\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hUvnSpyjp0Dh",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# start model training\n",
        "trainer.fit(model_from_scratch)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JxBiIKMlH8yv",
        "colab_type": "text"
      },
      "source": [
        "After training for 5 epochs, with the default config and NUM_SAMPLES = -1 (i.e.all data is used), your model performance should look similar to this: \n",
        "```\n",
        "    label                                                precision    recall       f1           support   \n",
        "    O (label_id: 0)                                         99.14      99.19      99.17     131141\n",
        "    B-GPE (label_id: 1)                                     95.86      94.03      94.93       2362\n",
        "    B-LOC (label_id: 2)                                     83.99      90.31      87.04       5346\n",
        "    B-MISC (label_id: 3)                                    39.82      34.62      37.04        130\n",
        "    B-ORG (label_id: 4)                                     78.33      67.82      72.70       2980\n",
        "    B-PER (label_id: 5)                                     84.36      84.32      84.34       2577\n",
        "    B-TIME (label_id: 6)                                    91.94      91.23      91.58       2975\n",
        "    I-GPE (label_id: 7)                                     88.89      34.78      50.00         23\n",
        "    I-LOC (label_id: 8)                                     77.18      79.13      78.14       1030\n",
        "    I-MISC (label_id: 9)                                    28.57      24.00      26.09         75\n",
        "    I-ORG (label_id: 10)                                    78.67      75.67      77.14       2384\n",
        "    I-PER (label_id: 11)                                    86.69      90.17      88.40       2687\n",
        "    I-TIME (label_id: 12)                                   83.21      83.48      83.34        938\n",
        "    -------------------\n",
        "    micro avg                                               96.95      96.95      96.95     154648\n",
        "    macro avg                                               78.20      72.98      74.61     154648\n",
        "    weighted avg                                            96.92      96.95      96.92     154648\n",
        "```\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VPdzJVAgSFaJ",
        "colab_type": "text"
      },
      "source": [
        "# Inference\n",
        "\n",
        "To see how the model performs, we can run generate prediction similar to the way we did it earlier"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QaW0A1OOwefR",
        "colab_type": "text"
      },
      "source": [
        "## Generate Predictions\n",
        "\n",
        "To see how the model performs, we can generate prediction the same way we did it earlier or we can use our model to generate predictions for a dataset from a file, for example, to perform final evaluation or to do error analysis.\n",
        "Below, we are using a subset of dev set, but it could be any text file as long as it follows the data format described above.\n",
        "Labels_file is optional here, and if provided will be used to get metrics."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "92PB0iTqNnW-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's first create a subset of our dev data\n",
        "! head -n 100 {DATA_DIR}/text_dev.txt > {DATA_DIR}/sample_text_dev.txt\n",
        "! head -n 100 {DATA_DIR}/labels_dev.txt > {DATA_DIR}/sample_labels_dev.txt"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vXnx2tKoOohy",
        "colab_type": "text"
      },
      "source": [
        "Now, let's generate predictions for the provided text file.\n",
        "If labels file is also specified, the model will evaluate the predictions and plot confusion matrix. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "sglcZV1bwsv0",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "model_from_scratch.evaluate_from_file(\n",
        "    text_file=os.path.join(DATA_DIR, 'sample_text_dev.txt'),\n",
        "    labels_file=os.path.join(DATA_DIR, 'sample_labels_dev.txt'),\n",
        "    output_dir=exp_dir,\n",
        ")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ref1qSonGNhP",
        "colab_type": "text"
      },
      "source": [
        "## Training Script\n",
        "\n",
        "If you have NeMo installed locally, you can also train the model with [nlp/token_classification/token_classification_train.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/token_classification_train.py).\n",
        "\n",
        "To run training script, use:\n",
        "\n",
        "`python token_classification_train.py model.dataset.data_dir=PATH_TO_DATA_DIR`\n",
        "\n",
        "# Finetuning model with your data\n",
        "\n",
        "When we were training from scratch, the datasets were prepared for training during the model initialization. When we are using a pretrained NER model, before training, we need to setup training and evaluation data.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yu9fZc2vPQfw",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's reload our pretrained NER model\n",
        "pretrained_ner_model = nemo_nlp.models.TokenClassificationModel.from_pretrained('ner_en_bert')\n",
        "\n",
        "# then we need to setup the data dir to get class weights statistics\n",
        "pretrained_ner_model.update_data_dir(DATA_DIR)\n",
        "\n",
        "# setup train and validation Pytorch DataLoaders\n",
        "pretrained_ner_model.setup_training_data()\n",
        "pretrained_ner_model.setup_validation_data()\n",
        "\n",
        "# then we're setting up loss, use class_balancing='weighted_loss' if you want to add class weights to the CrossEntropyLoss\n",
        "pretrained_ner_model.setup_loss()\n",
        "\n",
        "# and now we can create a PyTorch Lightning trainer and call `fit` again\n",
        "# for this tutorial we are setting fast_dev_run to True, and the trainer will run 1 training batch and 1 validation batch\n",
        "# for actual model training, disable the flag\n",
        "fast_dev_run = True\n",
        "trainer = pl.Trainer(devices=1, accelerator='gpu', fast_dev_run=fast_dev_run)\n",
        "trainer.fit(pretrained_ner_model)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "source": [
        "# Labeling your own data\n",
        "\n",
        "If you have raw data, NeMo recommends using the Datasaur labeling platform to apply labels to data. Datasaur was designed specifically for labeling text data and supports basic NLP labeling tasks such as Named Entity Recognition and text classification through advanced NLP tasks such as dependency parsing and coreference resolution. You can sign up for Datasaur for free at https://datasaur.ai/sign-up/. Once you upload a file, you can choose from multiple NLP project types and use the Datasaur interface to label the data. After labeling, you can export the labeled data using the conll_2003 format, which integrates directly with NeMo. A video walkthrough can be found here: https://www.youtube.com/watch?v=I9WVmnnSciE.\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    }
  ]
}